]> git.lizzy.rs Git - rust.git/commitdiff
Rollup merge of #23000 - Florob:unicode-FL, r=brson
authorManish Goregaokar <manishsmail@gmail.com>
Wed, 4 Mar 2015 10:16:17 +0000 (15:46 +0530)
committerManish Goregaokar <manishsmail@gmail.com>
Thu, 5 Mar 2015 07:07:48 +0000 (12:37 +0530)
 This handles the ranges contained in UnicodeData.txt.
Counterintuitively this actually makes the tables shorter.

389 files changed:
mk/debuggers.mk
mk/docs.mk
mk/llvm.mk
mk/target.mk
mk/tests.mk
src/compiletest/common.rs
src/compiletest/compiletest.rs
src/compiletest/errors.rs
src/compiletest/header.rs
src/compiletest/procsrv.rs
src/compiletest/runtest.rs
src/compiletest/util.rs
src/doc/reference.md
src/doc/trpl/pointers.md
src/etc/tidy.py
src/grammar/parser-lalr.y
src/liballoc/arc.rs
src/liballoc/boxed.rs
src/liballoc/heap.rs
src/liballoc/lib.rs
src/liballoc/rc.rs
src/libarena/lib.rs
src/libcollections/binary_heap.rs
src/libcollections/linked_list.rs
src/libcollections/slice.rs
src/libcollections/vec.rs
src/libcollections/vec_map.rs
src/libcore/iter.rs
src/libcoretest/any.rs
src/libcoretest/hash/mod.rs
src/libcoretest/iter.rs
src/libcoretest/option.rs
src/libcoretest/str.rs
src/libgetopts/lib.rs
src/librand/rand_impls.rs
src/librbml/io.rs
src/librustc/lib.rs
src/librustc/metadata/common.rs
src/librustc/metadata/creader.rs
src/librustc/metadata/cstore.rs
src/librustc/metadata/decoder.rs
src/librustc/metadata/encoder.rs
src/librustc/metadata/filesearch.rs
src/librustc/metadata/loader.rs
src/librustc/middle/astencode.rs
src/librustc/middle/const_eval.rs
src/librustc/middle/dataflow.rs
src/librustc/middle/infer/region_inference/graphviz.rs
src/librustc/plugin/load.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_back/archive.rs
src/librustc_back/fs.rs
src/librustc_back/lib.rs
src/librustc_back/rpath.rs
src/librustc_back/sha2.rs
src/librustc_back/target/mod.rs
src/librustc_driver/driver.rs
src/librustc_driver/lib.rs
src/librustc_driver/pretty.rs
src/librustc_llvm/archive_ro.rs
src/librustc_llvm/lib.rs
src/librustc_trans/back/link.rs
src/librustc_trans/back/lto.rs
src/librustc_trans/back/write.rs
src/librustc_trans/lib.rs
src/librustc_trans/save/mod.rs
src/librustc_trans/save/recorder.rs
src/librustc_trans/trans/base.rs
src/librustc_trans/trans/debuginfo.rs
src/librustc_trans/trans/inline.rs
src/librustc_typeck/check/callee.rs
src/librustdoc/clean/mod.rs
src/librustdoc/externalfiles.rs
src/librustdoc/flock.rs
src/librustdoc/html/layout.rs
src/librustdoc/html/render.rs
src/librustdoc/lib.rs
src/librustdoc/markdown.rs
src/librustdoc/test.rs
src/libserialize/lib.rs
src/libserialize/serialize.rs
src/libstd/ffi/c_str.rs
src/libstd/io/mod.rs
src/libstd/lib.rs
src/libstd/old_io/fs.rs
src/libstd/old_io/net/ip.rs
src/libstd/old_io/stdio.rs
src/libstd/old_io/timer.rs
src/libstd/process.rs
src/libstd/rt/unwind.rs
src/libstd/sync/mpsc/mod.rs
src/libstd/sync/mpsc/mpsc_queue.rs
src/libstd/sync/mpsc/spsc_queue.rs
src/libstd/sys/unix/ext.rs
src/libstd/sys/windows/ext.rs
src/libstd/sys/windows/process.rs
src/libstd/thread.rs
src/libstd/thunk.rs
src/libsyntax/ast.rs
src/libsyntax/ast_map/mod.rs
src/libsyntax/codemap.rs
src/libsyntax/diagnostic.rs
src/libsyntax/ext/base.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/hash.rs
src/libsyntax/ext/deriving/primitive.rs
src/libsyntax/ext/deriving/rand.rs
src/libsyntax/ext/deriving/show.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/fold.rs
src/libsyntax/lib.rs
src/libsyntax/owned_slice.rs
src/libsyntax/parse/lexer/comments.rs
src/libsyntax/parse/lexer/mod.rs
src/libsyntax/parse/mod.rs
src/libsyntax/parse/parser.rs
src/libsyntax/print/pp.rs
src/libsyntax/print/pprust.rs
src/libterm/lib.rs
src/libterm/terminfo/parser/compiled.rs
src/libterm/terminfo/searcher.rs
src/libtest/lib.rs
src/rustbook/book.rs
src/rustbook/build.rs
src/rustbook/error.rs
src/rustbook/help.rs
src/rustbook/main.rs
src/rustbook/serve.rs
src/rustbook/term.rs
src/rustbook/test.rs
src/test/auxiliary/cross_crate_spans.rs [new file with mode: 0644]
src/test/auxiliary/macro_crate_test.rs
src/test/auxiliary/plugin_args.rs
src/test/auxiliary/procedural_mbe_matching.rs [new file with mode: 0644]
src/test/bench/shootout-k-nucleotide.rs
src/test/bench/sudoku.rs
src/test/compile-fail/borrow-tuple-fields.rs
src/test/compile-fail/borrowck-bad-nested-calls-free.rs
src/test/compile-fail/borrowck-bad-nested-calls-move.rs
src/test/compile-fail/borrowck-borrow-immut-deref-of-box-as-mut.rs
src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs
src/test/compile-fail/borrowck-box-insensitivity.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-two-mut.rs
src/test/compile-fail/borrowck-closures-use-after-free.rs
src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs
src/test/compile-fail/borrowck-issue-14498.rs
src/test/compile-fail/borrowck-issue-2657-1.rs
src/test/compile-fail/borrowck-issue-2657-2.rs
src/test/compile-fail/borrowck-lend-flow-if.rs
src/test/compile-fail/borrowck-lend-flow-loop.rs
src/test/compile-fail/borrowck-lend-flow.rs
src/test/compile-fail/borrowck-loan-blocks-move-cc.rs
src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs
src/test/compile-fail/borrowck-move-by-capture.rs
src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs
src/test/compile-fail/borrowck-move-moved-value-into-closure.rs
src/test/compile-fail/borrowck-multiple-captures.rs
src/test/compile-fail/borrowck-no-cycle-in-exchange-heap.rs
src/test/compile-fail/borrowck-overloaded-index-2.rs
src/test/compile-fail/borrowck-uniq-via-lend.rs
src/test/compile-fail/cross-borrow-trait.rs
src/test/compile-fail/dst-bad-assign-2.rs
src/test/compile-fail/dst-bad-assign.rs
src/test/compile-fail/empty-extern-arg.rs
src/test/compile-fail/issue-10291.rs
src/test/compile-fail/issue-10398.rs
src/test/compile-fail/issue-11192.rs
src/test/compile-fail/issue-11515.rs
src/test/compile-fail/issue-11925.rs
src/test/compile-fail/issue-12127.rs
src/test/compile-fail/issue-17263.rs
src/test/compile-fail/issue-17441.rs
src/test/compile-fail/issue-17651.rs
src/test/compile-fail/issue-17913.rs
src/test/compile-fail/issue-18783.rs
src/test/compile-fail/issue-3763.rs
src/test/compile-fail/issue-4335.rs
src/test/compile-fail/issue-5543.rs
src/test/compile-fail/kindck-impl-type-params-2.rs
src/test/compile-fail/kindck-inherited-copy-bound.rs
src/test/compile-fail/liveness-use-after-move.rs
src/test/compile-fail/map-types.rs
src/test/compile-fail/move-in-guard-1.rs
src/test/compile-fail/move-in-guard-2.rs
src/test/compile-fail/move-out-of-tuple-field.rs
src/test/compile-fail/moves-based-on-type-no-recursive-stack-closure.rs
src/test/compile-fail/mut-cross-borrowing.rs
src/test/compile-fail/region-object-lifetime-in-coercion.rs
src/test/compile-fail/regions-close-associated-type-into-object.rs
src/test/compile-fail/regions-close-param-into-object.rs
src/test/compile-fail/regions-nested-fns.rs
src/test/compile-fail/regions-proc-bound-capture.rs
src/test/compile-fail/regions-steal-closure.rs
src/test/compile-fail/static-region-bound.rs
src/test/compile-fail/trait-coercion-generic-bad.rs
src/test/compile-fail/trait-coercion-generic-regions.rs
src/test/compile-fail/unboxed-closure-illegal-move.rs
src/test/compile-fail/unique-pinned-nocopy.rs
src/test/compile-fail/unique-unique-kind.rs
src/test/compile-fail/unique-vec-res.rs
src/test/compile-fail/use-after-move-implicity-coerced-object.rs
src/test/debuginfo/borrowed-struct.rs
src/test/debuginfo/boxed-struct.rs
src/test/debuginfo/closure-in-generic-function.rs
src/test/debuginfo/cross-crate-spans.rs [new file with mode: 0644]
src/test/debuginfo/generic-method-on-generic-struct.rs
src/test/debuginfo/method-on-enum.rs
src/test/debuginfo/method-on-generic-struct.rs
src/test/debuginfo/method-on-struct.rs
src/test/debuginfo/method-on-trait.rs
src/test/debuginfo/method-on-tuple-struct.rs
src/test/debuginfo/self-in-default-method.rs
src/test/debuginfo/self-in-generic-default-method.rs
src/test/debuginfo/unique-enum.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/circular_modules_main.rs
src/test/parse-fail/issue-5806.rs
src/test/run-fail/panic-macro-any-wrapped.rs
src/test/run-fail/unique-panic.rs
src/test/run-fail/unwind-unique.rs
src/test/run-make/issue-19371/foo.rs
src/test/run-make/save-analysis/foo.rs
src/test/run-pass-fulldeps/compiler-calls.rs
src/test/run-pass-fulldeps/mbe_matching_test_macro.rs [new file with mode: 0644]
src/test/run-pass-fulldeps/qquote.rs
src/test/run-pass-fulldeps/quote-tokens.rs
src/test/run-pass-valgrind/dst-dtor-1.rs
src/test/run-pass-valgrind/dst-dtor-2.rs
src/test/run-pass/assert-eq-macro-success.rs
src/test/run-pass/associated-types-doubleendediterator-object.rs
src/test/run-pass/autoderef-method-on-trait.rs
src/test/run-pass/autoderef-method-priority.rs
src/test/run-pass/autoderef-method-twice-but-not-thrice.rs
src/test/run-pass/autoderef-method-twice.rs
src/test/run-pass/autoderef-method.rs
src/test/run-pass/autoref-intermediate-types-issue-3585.rs
src/test/run-pass/bitv-perf-test.rs
src/test/run-pass/borrowck-move-by-capture-ok.rs
src/test/run-pass/borrowck-mut-uniq.rs
src/test/run-pass/cci_borrow.rs
src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs
src/test/run-pass/clone-with-exterior.rs
src/test/run-pass/coerce-expect-unsized.rs
src/test/run-pass/coerce-match.rs
src/test/run-pass/const-bound.rs
src/test/run-pass/crate-method-reexport-grrrrrrr.rs
src/test/run-pass/deref-lval.rs
src/test/run-pass/deriving-default-box.rs
src/test/run-pass/deriving-encodable-decodable-box.rs
src/test/run-pass/deriving-eq-ord-boxed-slice.rs
src/test/run-pass/dst-deref-mut.rs
src/test/run-pass/dst-deref.rs
src/test/run-pass/dst-struct.rs
src/test/run-pass/dst-trait.rs
src/test/run-pass/empty-allocation-non-null.rs
src/test/run-pass/empty-allocation-rvalue-non-null.rs
src/test/run-pass/explicit-self-generic.rs
src/test/run-pass/explicit-self.rs
src/test/run-pass/expr-block-unique.rs
src/test/run-pass/expr-if-unique.rs
src/test/run-pass/expr-match-unique.rs
src/test/run-pass/func-arg-incomplete-pattern.rs
src/test/run-pass/func-arg-ref-pattern.rs
src/test/run-pass/generic-alias-unique.rs
src/test/run-pass/hashmap-memory.rs
src/test/run-pass/hrtb-precedence-of-plus.rs
src/test/run-pass/ifmt.rs
src/test/run-pass/init-res-into-things.rs
src/test/run-pass/intrinsic-atomics.rs
src/test/run-pass/intrinsic-move-val.rs
src/test/run-pass/issue-10802.rs
src/test/run-pass/issue-11205.rs
src/test/run-pass/issue-11677.rs
src/test/run-pass/issue-12744.rs
src/test/run-pass/issue-13808.rs
src/test/run-pass/issue-14399.rs
src/test/run-pass/issue-14589.rs
src/test/run-pass/issue-14919.rs
src/test/run-pass/issue-15571.rs
src/test/run-pass/issue-16668.rs
src/test/run-pass/issue-17734.rs
src/test/run-pass/issue-18425.rs
src/test/run-pass/issue-20575.rs
src/test/run-pass/issue-2633-2.rs
src/test/run-pass/issue-2708.rs
src/test/run-pass/issue-2718.rs
src/test/run-pass/issue-2935.rs
src/test/run-pass/issue-3012-2.rs
src/test/run-pass/issue-3026.rs
src/test/run-pass/issue-3052.rs
src/test/run-pass/issue-3290.rs
src/test/run-pass/issue-3424.rs
src/test/run-pass/issue-3609.rs
src/test/run-pass/issue-3878.rs
src/test/run-pass/issue-5718.rs
src/test/run-pass/issue-6117.rs
src/test/run-pass/issue-8498.rs
src/test/run-pass/last-use-in-cap-clause.rs
src/test/run-pass/last-use-is-capture.rs
src/test/run-pass/let-assignability.rs
src/test/run-pass/match-implicit-copy-unique.rs
src/test/run-pass/method-two-trait-defer-resolution-2.rs
src/test/run-pass/move-1-unique.rs
src/test/run-pass/move-2-unique.rs
src/test/run-pass/move-2.rs
src/test/run-pass/move-3-unique.rs
src/test/run-pass/move-guard-const.rs
src/test/run-pass/newlambdas-ret-infer.rs
src/test/run-pass/newlambdas-ret-infer2.rs
src/test/run-pass/overloaded-autoderef.rs
src/test/run-pass/overloaded-deref.rs
src/test/run-pass/overloaded-index-autoderef.rs
src/test/run-pass/owned-implies-static.rs
src/test/run-pass/pure-sum.rs
src/test/run-pass/rcvr-borrowed-to-region.rs
src/test/run-pass/regions-borrow-at.rs
src/test/run-pass/regions-borrow-uniq.rs
src/test/run-pass/regions-copy-closure.rs
src/test/run-pass/regions-escape-into-other-fn.rs
src/test/run-pass/regions-fn-subtyping.rs
src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs
src/test/run-pass/regions-infer-borrow-scope.rs
src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs
src/test/run-pass/regions-static-closure.rs
src/test/run-pass/self-in-mut-slot-default-method.rs
src/test/run-pass/self-re-assign.rs
src/test/run-pass/sendfn-spawn-with-fn-arg.rs
src/test/run-pass/show-boxed-slice.rs
src/test/run-pass/task-spawn-move-and-copy.rs
src/test/run-pass/trait-bounds-in-arc.rs
src/test/run-pass/trait-coercion-generic.rs
src/test/run-pass/trait-coercion.rs
src/test/run-pass/traits-conditional-dispatch.rs
src/test/run-pass/type-param-constraints.rs
src/test/run-pass/ufcs-explicit-self.rs
src/test/run-pass/unboxed-closures-call-sugar-object-autoderef.rs
src/test/run-pass/unboxed-closures-call-sugar-object.rs
src/test/run-pass/unboxed-closures-monomorphization.rs
src/test/run-pass/unboxed-closures-prelude.rs
src/test/run-pass/uniq-self-in-mut-slot.rs
src/test/run-pass/unique-assign-copy.rs
src/test/run-pass/unique-assign-drop.rs
src/test/run-pass/unique-assign-generic.rs
src/test/run-pass/unique-assign.rs
src/test/run-pass/unique-autoderef-field.rs
src/test/run-pass/unique-autoderef-index.rs
src/test/run-pass/unique-cmp.rs
src/test/run-pass/unique-containing-tag.rs
src/test/run-pass/unique-create.rs
src/test/run-pass/unique-decl-init-copy.rs
src/test/run-pass/unique-decl-init.rs
src/test/run-pass/unique-decl-move.rs
src/test/run-pass/unique-deref.rs
src/test/run-pass/unique-drop-complex.rs
src/test/run-pass/unique-in-vec-copy.rs
src/test/run-pass/unique-in-vec.rs
src/test/run-pass/unique-init.rs
src/test/run-pass/unique-kinds.rs
src/test/run-pass/unique-log.rs
src/test/run-pass/unique-match-discrim.rs
src/test/run-pass/unique-move-drop.rs
src/test/run-pass/unique-move-temp.rs
src/test/run-pass/unique-move.rs
src/test/run-pass/unique-mutable.rs
src/test/run-pass/unique-rec.rs
src/test/run-pass/unique-send.rs
src/test/run-pass/unique-swap.rs
src/test/run-pass/unsized3.rs
src/test/run-pass/unused-move-capture.rs
src/test/run-pass/unused-move.rs
src/test/run-pass/unwind-unique.rs

index 899cc42d066e4a2032a37a5646925fecb7e913d2..e6a2174f84a82dab0104b0520535561d298aa692 100644 (file)
@@ -56,29 +56,32 @@ define DEF_INSTALL_DEBUGGER_SCRIPTS_HOST
 tmp/install-debugger-scripts$(1)_H_$(2)-gdb.done: \
   $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_GDB_ABS) \
   $$(DEBUGGER_BIN_SCRIPTS_GDB_ABS)
+       $(Q)touch $$@.start_time
        $(Q)mkdir -p $$(HBIN$(1)_H_$(2))
        $(Q)mkdir -p $$(HLIB$(1)_H_$(2))/rustlib/etc
        $(Q)install $$(DEBUGGER_BIN_SCRIPTS_GDB_ABS) $$(HBIN$(1)_H_$(2))
        $(Q)install $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_GDB_ABS) $$(HLIB$(1)_H_$(2))/rustlib/etc
-       $(Q)touch $$@
+       $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
 
 tmp/install-debugger-scripts$(1)_H_$(2)-lldb.done: \
   $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_LLDB_ABS) \
   $$(DEBUGGER_BIN_SCRIPTS_LLDB_ABS)
+       $(Q)touch $$@.start_time
        $(Q)mkdir -p $$(HBIN$(1)_H_$(2))
        $(Q)mkdir -p $$(HLIB$(1)_H_$(2))/rustlib/etc
        $(Q)install $$(DEBUGGER_BIN_SCRIPTS_LLDB_ABS) $$(HBIN$(1)_H_$(2))
        $(Q)install $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_LLDB_ABS) $$(HLIB$(1)_H_$(2))/rustlib/etc
-       $(Q)touch $$@
+       $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
 
 tmp/install-debugger-scripts$(1)_H_$(2)-all.done: \
   $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_ALL_ABS) \
   $$(DEBUGGER_BIN_SCRIPTS_ALL_ABS)
+       $(Q)touch $$@.start_time
        $(Q)mkdir -p $$(HBIN$(1)_H_$(2))
        $(Q)mkdir -p $$(HLIB$(1)_H_$(2))/rustlib/etc
        $(Q)install $$(DEBUGGER_BIN_SCRIPTS_ALL_ABS) $$(HBIN$(1)_H_$(2))
        $(Q)install $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_ALL_ABS) $$(HLIB$(1)_H_$(2))/rustlib/etc
-       $(Q)touch $$@
+       $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
 
 tmp/install-debugger-scripts$(1)_H_$(2)-none.done:
        $(Q)touch $$@
@@ -98,29 +101,32 @@ define DEF_INSTALL_DEBUGGER_SCRIPTS_TARGET
 tmp/install-debugger-scripts$(1)_T_$(2)_H_$(3)-gdb.done: \
   $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_GDB_ABS) \
   $$(DEBUGGER_BIN_SCRIPTS_GDB_ABS)
+       $(Q)touch $$@.start_time
        $(Q)mkdir -p $$(TBIN$(1)_T_$(2)_H_$(3))
        $(Q)mkdir -p $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
        $(Q)install $(DEBUGGER_BIN_SCRIPTS_GDB_ABS) $$(TBIN$(1)_T_$(2)_H_$(3))
        $(Q)install $(DEBUGGER_RUSTLIB_ETC_SCRIPTS_GDB_ABS) $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
-       $(Q)touch $$@
+       $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
 
 tmp/install-debugger-scripts$(1)_T_$(2)_H_$(3)-lldb.done: \
   $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_LLDB_ABS) \
   $$(DEBUGGER_BIN_SCRIPTS_LLDB_ABS)
+       $(Q)touch $$@.start_time
        $(Q)mkdir -p $$(TBIN$(1)_T_$(2)_H_$(3))
        $(Q)mkdir -p $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
        $(Q)install $(DEBUGGER_BIN_SCRIPTS_LLDB_ABS) $$(TBIN$(1)_T_$(2)_H_$(3))
        $(Q)install $(DEBUGGER_RUSTLIB_ETC_SCRIPTS_LLDB_ABS) $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
-       $(Q)touch $$@
+       $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
 
 tmp/install-debugger-scripts$(1)_T_$(2)_H_$(3)-all.done: \
   $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_ALL_ABS) \
   $$(DEBUGGER_BIN_SCRIPTS_ALL_ABS)
+       $(Q)touch $$@.start_time
        $(Q)mkdir -p $$(TBIN$(1)_T_$(2)_H_$(3))
        $(Q)mkdir -p $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
        $(Q)install $(DEBUGGER_BIN_SCRIPTS_ALL_ABS) $$(TBIN$(1)_T_$(2)_H_$(3))
        $(Q)install $(DEBUGGER_RUSTLIB_ETC_SCRIPTS_ALL_ABS) $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
-       $(Q)touch $$@
+       $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
 
 tmp/install-debugger-scripts$(1)_T_$(2)_H_$(3)-none.done:
        $(Q)touch $$@
index 743032f676d217d4201246b9cf8d5984ff8608d0..f7ab86d3a29b92d2dde26091d38dc578758ec25a 100644 (file)
@@ -273,11 +273,13 @@ compiler-docs: $(COMPILER_DOC_TARGETS)
 trpl: doc/book/index.html
 
 doc/book/index.html: $(RUSTBOOK_EXE) $(wildcard $(S)/src/doc/trpl/*.md) | doc/
+       @$(call E, rustbook: $@)
        $(Q)rm -rf doc/book
        $(Q)$(RUSTBOOK) build $(S)src/doc/trpl doc/book
 
 style: doc/style/index.html
 
 doc/style/index.html: $(RUSTBOOK_EXE) $(wildcard $(S)/src/doc/style/*.md) | doc/
+       @$(call E, rustbook: $@)
        $(Q)rm -rf doc/style
        $(Q)$(RUSTBOOK) build $(S)src/doc/style doc/style
index ba2e073803935b89632a9e476a40a4293fd45cfb..b07c2a1d62fdb8c441c4a6f0062fcd0e6b10189b 100644 (file)
@@ -38,9 +38,10 @@ endif
 # the stamp in the source dir.
 $$(LLVM_STAMP_$(1)): $(S)src/rustllvm/llvm-auto-clean-trigger
        @$$(call E, make: cleaning llvm)
+       $(Q)touch $$@.start_time
        $(Q)$(MAKE) clean-llvm$(1)
        @$$(call E, make: done cleaning llvm)
-       touch $$@
+       touch -r $$@.start_time $$@ && rm $$@.start_time
 
 ifeq ($$(CFG_ENABLE_LLVM_STATIC_STDCPP),1)
 LLVM_STDCPP_LOCATION_$(1) = $$(shell $$(CC_$(1)) $$(CFG_GCCISH_CFLAGS_$(1)) \
index 1f67d9ed8da2934a6f3c68cdf2fc6e3823d255b7..2435edfb9dc361373fcb065dcae8014d27023c0d 100644 (file)
@@ -75,6 +75,7 @@ $$(TLIB$(1)_T_$(2)_H_$(3))/stamp.$(4): \
                $$(TSREQ$(1)_T_$(2)_H_$(3)) \
                | $$(TLIB$(1)_T_$(2)_H_$(3))/
        @$$(call E, rustc: $$(@D)/lib$(4))
+       @touch $$@.start_time
        $$(call REMOVE_ALL_OLD_GLOB_MATCHES, \
            $$(dir $$@)$$(call CFG_LIB_GLOB_$(2),$(4)))
        $$(call REMOVE_ALL_OLD_GLOB_MATCHES, \
@@ -89,7 +90,7 @@ $$(TLIB$(1)_T_$(2)_H_$(3))/stamp.$(4): \
                --out-dir $$(@D) \
                -C extra-filename=-$$(CFG_FILENAME_EXTRA) \
                $$<
-       @touch $$@
+       @touch -r $$@.start_time $$@ && rm $$@.start_time
        $$(call LIST_ALL_OLD_GLOB_MATCHES, \
            $$(dir $$@)$$(call CFG_LIB_GLOB_$(2),$(4)))
        $$(call LIST_ALL_OLD_GLOB_MATCHES, \
index ca2d1a45d571f3a0317ebfe6268a6dbb971a115c..838ed0dccfcbbf971971f640121e5ddef109203d 100644 (file)
@@ -389,10 +389,11 @@ check-stage$(1)-T-$(2)-H-$(3)-$(4)-exec: $$(call TEST_OK_FILE,$(1),$(2),$(3),$(4
 $$(call TEST_OK_FILE,$(1),$(2),$(3),$(4)): \
                $(3)/stage$(1)/test/$(4)test-$(2)$$(X_$(2))
        @$$(call E, run: $$<)
+       $$(Q)touch $$@.start_time
        $$(Q)$$(call CFG_RUN_TEST_$(2),$$<,$(1),$(2),$(3)) $$(TESTARGS) \
            --logfile $$(call TEST_LOG_FILE,$(1),$(2),$(3),$(4)) \
            $$(call CRATE_TEST_EXTRA_ARGS,$(1),$(2),$(3),$(4)) \
-           && touch $$@
+           && touch -r $$@.start_time $$@ && rm $$@.start_time
 endef
 
 define DEF_TEST_CRATE_RULES_android
@@ -401,6 +402,7 @@ check-stage$(1)-T-$(2)-H-$(3)-$(4)-exec: $$(call TEST_OK_FILE,$(1),$(2),$(3),$(4
 $$(call TEST_OK_FILE,$(1),$(2),$(3),$(4)): \
                $(3)/stage$(1)/test/$(4)test-$(2)$$(X_$(2))
        @$$(call E, run: $$< via adb)
+       $$(Q)touch $$@.start_time
        $$(Q)$(CFG_ADB) push $$< $(CFG_ADB_TEST_DIR)
        $$(Q)$(CFG_ADB) shell '(cd $(CFG_ADB_TEST_DIR); LD_LIBRARY_PATH=./$(2) \
                ./$$(notdir $$<) \
@@ -414,7 +416,7 @@ $$(call TEST_OK_FILE,$(1),$(2),$(3),$(4)): \
        @if grep -q "result: ok" tmp/check-stage$(1)-T-$(2)-H-$(3)-$(4).tmp; \
        then \
                rm tmp/check-stage$(1)-T-$(2)-H-$(3)-$(4).tmp; \
-               touch $$@; \
+               touch -r $$@.start_time $$@ && rm $$@.start_time; \
        else \
                rm tmp/check-stage$(1)-T-$(2)-H-$(3)-$(4).tmp; \
                exit 101; \
@@ -690,10 +692,11 @@ $$(call TEST_OK_FILE,$(1),$(2),$(3),$(4)): \
                $$(TEST_SREQ$(1)_T_$(2)_H_$(3)) \
                 $$(CTEST_DEPS_$(4)_$(1)-T-$(2)-H-$(3))
        @$$(call E, run $(4) [$(2)]: $$<)
+       $$(Q)touch $$@.start_time
        $$(Q)$$(call CFG_RUN_CTEST_$(2),$(1),$$<,$(3)) \
                $$(CTEST_ARGS$(1)-T-$(2)-H-$(3)-$(4)) \
                --logfile $$(call TEST_LOG_FILE,$(1),$(2),$(3),$(4)) \
-                && touch $$@
+                && touch -r $$@.start_time $$@ && rm $$@.start_time
 
 else
 
@@ -750,10 +753,11 @@ $$(call TEST_OK_FILE,$(1),$(2),$(3),$(4)): \
                $$(PRETTY_DEPS_$(4)) \
                $$(PRETTY_DEPS$(1)_H_$(3)_$(4))
        @$$(call E, run pretty-rpass [$(2)]: $$<)
+       $$(Q)touch $$@.start_time
        $$(Q)$$(call CFG_RUN_CTEST_$(2),$(1),$$<,$(3)) \
                $$(PRETTY_ARGS$(1)-T-$(2)-H-$(3)-$(4)) \
                --logfile $$(call TEST_LOG_FILE,$(1),$(2),$(3),$(4)) \
-                && touch $$@
+                && touch -r $$@.start_time $$@ && rm $$@.start_time
 
 endef
 
@@ -799,8 +803,10 @@ endif
 ifeq ($(2),$$(CFG_BUILD))
 $$(call TEST_OK_FILE,$(1),$(2),$(3),doc-$(4)): $$(DOCTESTDEP_$(1)_$(2)_$(3)_$(4))
        @$$(call E, run doc-$(4) [$(2)])
+       $$(Q)touch $$@.start_time
        $$(Q)$$(RUSTDOC_$(1)_T_$(2)_H_$(3)) --cfg dox --test $$< \
-               --test-args "$$(TESTARGS)" && touch $$@
+               --test-args "$$(TESTARGS)" && \
+               touch -r $$@.start_time $$@ && rm $$@.start_time
 else
 $$(call TEST_OK_FILE,$(1),$(2),$(3),doc-$(4)):
        touch $$@
@@ -835,9 +841,11 @@ check-stage$(1)-T-$(2)-H-$(3)-doc-crate-$(4)-exec: \
 ifeq ($(2),$$(CFG_BUILD))
 $$(call TEST_OK_FILE,$(1),$(2),$(3),doc-crate-$(4)): $$(CRATEDOCTESTDEP_$(1)_$(2)_$(3)_$(4))
        @$$(call E, run doc-crate-$(4) [$(2)])
+       $$(Q)touch $$@.start_time
        $$(Q)CFG_LLVM_LINKAGE_FILE=$$(LLVM_LINKAGE_PATH_$(3)) \
            $$(RUSTDOC_$(1)_T_$(2)_H_$(3)) --test --cfg dox \
-               $$(CRATEFILE_$(4)) --test-args "$$(TESTARGS)" && touch $$@
+               $$(CRATEFILE_$(4)) --test-args "$$(TESTARGS)" && \
+               touch -r $$@.start_time $$@ && rm $$@.start_time
 else
 $$(call TEST_OK_FILE,$(1),$(2),$(3),doc-crate-$(4)):
        touch $$@
@@ -984,6 +992,7 @@ $(3)/test/run-make/%-$(1)-T-$(2)-H-$(3).ok: \
                $$(CSREQ$(1)_T_$(2)_H_$(3))
        @rm -rf $(3)/test/run-make/$$*
        @mkdir -p $(3)/test/run-make/$$*
+       $$(Q)touch $$@.start_time
        $$(Q)$$(CFG_PYTHON) $(S)src/etc/maketest.py $$(dir $$<) \
         $$(MAKE) \
            $$(HBIN$(1)_H_$(3))/rustc$$(X_$(3)) \
@@ -996,7 +1005,7 @@ $(3)/test/run-make/%-$(1)-T-$(2)-H-$(3).ok: \
            "$$(LD_LIBRARY_PATH_ENV_TARGETDIR$(1)_T_$(2)_H_$(3))" \
            $(1) \
            $$(S)
-       @touch $$@
+       @touch -r $$@.start_time $$@ && rm $$@.start_time
 else
 # FIXME #11094 - The above rule doesn't work right for multiple targets
 check-stage$(1)-T-$(2)-H-$(3)-rmake-exec:
index 2c046d252799ee02338b399fb4e38a1b1cae75e4..fe556cecef6981eef5b856bb40ccc48d3250c272 100644 (file)
@@ -11,6 +11,7 @@
 
 use std::fmt;
 use std::str::FromStr;
+use std::path::PathBuf;
 
 #[derive(Clone, Copy, PartialEq, Debug)]
 pub enum Mode {
@@ -68,13 +69,13 @@ pub struct Config {
     pub run_lib_path: String,
 
     // The rustc executable
-    pub rustc_path: Path,
+    pub rustc_path: PathBuf,
 
     // The clang executable
-    pub clang_path: Option<Path>,
+    pub clang_path: Option<PathBuf>,
 
     // The llvm binaries path
-    pub llvm_bin_path: Option<Path>,
+    pub llvm_bin_path: Option<PathBuf>,
 
     // The valgrind path
     pub valgrind_path: Option<String>,
@@ -84,13 +85,13 @@ pub struct Config {
     pub force_valgrind: bool,
 
     // The directory containing the tests to run
-    pub src_base: Path,
+    pub src_base: PathBuf,
 
     // The directory where programs should be built
-    pub build_base: Path,
+    pub build_base: PathBuf,
 
     // Directory for auxiliary libraries
-    pub aux_base: Path,
+    pub aux_base: PathBuf,
 
     // The name of the stage being built (stage1, etc)
     pub stage_id: String,
@@ -105,7 +106,7 @@ pub struct Config {
     pub filter: Option<String>,
 
     // Write out a parseable log of tests that were run
-    pub logfile: Option<Path>,
+    pub logfile: Option<PathBuf>,
 
     // A command line to prefix program execution with,
     // for running under valgrind
@@ -133,7 +134,7 @@ pub struct Config {
     pub lldb_version: Option<String>,
 
     // Path to the android tools
-    pub android_cross_path: Path,
+    pub android_cross_path: PathBuf,
 
     // Extra parameter to run adb on arm-linux-androideabi
     pub adb_path: String,
index 4993dd140d335daac402fd10c2bff54192bd3373..b9e6f1842eeab8f3a58eaaf817a89280457bf330 100644 (file)
 #![feature(test)]
 #![feature(unicode)]
 #![feature(core)]
+#![feature(path)]
+#![feature(os)]
+#![feature(io)]
+#![feature(fs)]
+#![feature(net)]
 
 #![deny(warnings)]
 
@@ -31,8 +36,9 @@
 extern crate log;
 
 use std::env;
+use std::fs;
 use std::old_io;
-use std::old_io::fs;
+use std::path::{Path, PathBuf};
 use std::thunk::Thunk;
 use getopts::{optopt, optflag, reqopt};
 use common::Config;
@@ -114,9 +120,9 @@ pub fn parse_config(args: Vec<String> ) -> Config {
         panic!()
     }
 
-    fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
+    fn opt_path(m: &getopts::Matches, nm: &str) -> PathBuf {
         match m.opt_str(nm) {
-            Some(s) => Path::new(s),
+            Some(s) => PathBuf::new(&s),
             None => panic!("no option (=path) found for {}", nm),
         }
     }
@@ -131,10 +137,10 @@ fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
         compile_lib_path: matches.opt_str("compile-lib-path").unwrap(),
         run_lib_path: matches.opt_str("run-lib-path").unwrap(),
         rustc_path: opt_path(matches, "rustc-path"),
-        clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)),
+        clang_path: matches.opt_str("clang-path").map(|s| PathBuf::new(&s)),
         valgrind_path: matches.opt_str("valgrind-path"),
         force_valgrind: matches.opt_present("force-valgrind"),
-        llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)),
+        llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| PathBuf::new(&s)),
         src_base: opt_path(matches, "src-base"),
         build_base: opt_path(matches, "build-base"),
         aux_base: opt_path(matches, "aux-base"),
@@ -142,7 +148,7 @@ fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
         mode: matches.opt_str("mode").unwrap().parse().ok().expect("invalid mode"),
         run_ignored: matches.opt_present("ignored"),
         filter: filter,
-        logfile: matches.opt_str("logfile").map(|s| Path::new(s)),
+        logfile: matches.opt_str("logfile").map(|s| PathBuf::new(&s)),
         runtool: matches.opt_str("runtool"),
         host_rustcflags: matches.opt_str("host-rustcflags"),
         target_rustcflags: matches.opt_str("target-rustcflags"),
@@ -276,9 +282,9 @@ pub fn make_tests(config: &Config) -> Vec<test::TestDescAndFn> {
     debug!("making tests from {:?}",
            config.src_base.display());
     let mut tests = Vec::new();
-    let dirs = fs::readdir(&config.src_base).unwrap();
-    for file in &dirs {
-        let file = file.clone();
+    let dirs = fs::read_dir(&config.src_base).unwrap();
+    for file in dirs {
+        let file = file.unwrap().path();
         debug!("inspecting file {:?}", file.display());
         if is_test(config, &file) {
             let t = make_test(config, &file, || {
@@ -301,7 +307,7 @@ pub fn is_test(config: &Config, testfile: &Path) -> bool {
           _ => vec!(".rc".to_string(), ".rs".to_string())
         };
     let invalid_prefixes = vec!(".".to_string(), "#".to_string(), "~".to_string());
-    let name = testfile.filename_str().unwrap();
+    let name = testfile.file_name().unwrap().to_str().unwrap();
 
     let mut valid = false;
 
@@ -337,9 +343,9 @@ pub fn make_test_name(config: &Config, testfile: &Path) -> test::TestName {
 
     // Try to elide redundant long paths
     fn shorten(path: &Path) -> String {
-        let filename = path.filename_str();
-        let p = path.dir_path();
-        let dir = p.filename_str();
+        let filename = path.file_name().unwrap().to_str();
+        let p = path.parent().unwrap();
+        let dir = p.file_name().unwrap().to_str();
         format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
     }
 
@@ -348,19 +354,17 @@ fn shorten(path: &Path) -> String {
 
 pub fn make_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
     let config = (*config).clone();
-    // FIXME (#9639): This needs to handle non-utf8 paths
-    let testfile = testfile.as_str().unwrap().to_string();
+    let testfile = testfile.to_path_buf();
     test::DynTestFn(Thunk::new(move || {
-        runtest::run(config, testfile)
+        runtest::run(config, &testfile)
     }))
 }
 
 pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
     let config = (*config).clone();
-    // FIXME (#9639): This needs to handle non-utf8 paths
-    let testfile = testfile.as_str().unwrap().to_string();
+    let testfile = testfile.to_path_buf();
     test::DynMetricFn(box move |mm: &mut test::MetricMap| {
-        runtest::run_metrics(config, testfile, mm)
+        runtest::run_metrics(config, &testfile, mm)
     })
 }
 
index 7411a9b48d417e70936dcacfad51c6b10822a5ee..25f962c5785a175654e5511d3d827604057ad9dd 100644 (file)
@@ -9,7 +9,10 @@
 // except according to those terms.
 use self::WhichLine::*;
 
-use std::old_io::{BufferedReader, File};
+use std::fs::File;
+use std::io::BufReader;
+use std::io::prelude::*;
+use std::path::Path;
 
 pub struct ExpectedError {
     pub line: uint,
@@ -29,7 +32,7 @@ enum WhichLine { ThisLine, FollowPrevious(uint), AdjustBackward(uint) }
 ///          //~| ERROR message two for that same line.
 // Load any test directives embedded in the file
 pub fn load_errors(testfile: &Path) -> Vec<ExpectedError> {
-    let mut rdr = BufferedReader::new(File::open(testfile).unwrap());
+    let rdr = BufReader::new(File::open(testfile).unwrap());
 
     // `last_nonfollow_error` tracks the most recently seen
     // line with an error template that did not use the
index e5570fe0b8fb0c84cd0dd0121e9f445f0c84f702..21cebc61b3a9d3d4dcc821e15de197b896bdd769 100644 (file)
@@ -9,6 +9,10 @@
 // except according to those terms.
 
 use std::env;
+use std::fs::File;
+use std::io::BufReader;
+use std::io::prelude::*;
+use std::path::{Path, PathBuf};
 
 use common::Config;
 use common;
@@ -23,7 +27,7 @@ pub struct TestProps {
     pub run_flags: Option<String>,
     // If present, the name of a file that this test should match when
     // pretty-printed
-    pub pp_exact: Option<Path>,
+    pub pp_exact: Option<PathBuf>,
     // Modules from aux directory that should be compiled
     pub aux_builds: Vec<String> ,
     // Environment settings to use during execution
@@ -62,7 +66,7 @@ pub fn load_props(testfile: &Path) -> TestProps {
     let mut pretty_mode = None;
     let mut pretty_compare_only = false;
     let mut forbid_output = Vec::new();
-    iter_header(testfile, |ln| {
+    iter_header(testfile, &mut |ln| {
         match parse_error_pattern(ln) {
           Some(ep) => error_patterns.push(ep),
           None => ()
@@ -219,7 +223,7 @@ fn ignore_lldb(config: &Config, line: &str) -> bool {
         }
     }
 
-    let val = iter_header(testfile, |ln| {
+    let val = iter_header(testfile, &mut |ln| {
         !parse_name_directive(ln, "ignore-test") &&
         !parse_name_directive(ln, &ignore_target(config)) &&
         !parse_name_directive(ln, &ignore_stage(config)) &&
@@ -232,12 +236,8 @@ fn ignore_lldb(config: &Config, line: &str) -> bool {
     !val
 }
 
-fn iter_header<F>(testfile: &Path, mut it: F) -> bool where
-    F: FnMut(&str) -> bool,
-{
-    use std::old_io::{BufferedReader, File};
-
-    let mut rdr = BufferedReader::new(File::open(testfile).unwrap());
+fn iter_header(testfile: &Path, it: &mut FnMut(&str) -> bool) -> bool {
+    let rdr = BufReader::new(File::open(testfile).unwrap());
     for ln in rdr.lines() {
         // Assume that any directives will be found before the first
         // module or function. This doesn't seem to be an optimization
@@ -322,12 +322,12 @@ fn parse_exec_env(line: &str) -> Option<(String, String)> {
     })
 }
 
-fn parse_pp_exact(line: &str, testfile: &Path) -> Option<Path> {
+fn parse_pp_exact(line: &str, testfile: &Path) -> Option<PathBuf> {
     match parse_name_value_directive(line, "pp-exact") {
-      Some(s) => Some(Path::new(s)),
+      Some(s) => Some(PathBuf::new(&s)),
       None => {
         if parse_name_directive(line, "pp-exact") {
-            testfile.filename().map(|s| Path::new(s))
+            testfile.file_name().map(|s| PathBuf::new(s))
         } else {
             None
         }
index 148a43e6c783196555b044efb3e4ec8e1791d4d6..b684dbcfaceb98b4c465295faf6086fede5b33c0 100644 (file)
@@ -8,7 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use std::old_io::process::{ProcessExit, Command, Process, ProcessOutput};
+use std::process::{ExitStatus, Command, Child, Output, Stdio};
+use std::io::prelude::*;
 use std::dynamic_lib::DynamicLibrary;
 
 fn add_target_env(cmd: &mut Command, lib_path: &str, aux_path: Option<&str>) {
@@ -25,10 +26,10 @@ fn add_target_env(cmd: &mut Command, lib_path: &str, aux_path: Option<&str>) {
     let var = DynamicLibrary::envvar();
     let newpath = DynamicLibrary::create_path(&path);
     let newpath = String::from_utf8(newpath).unwrap();
-    cmd.env(var.to_string(), newpath);
+    cmd.env(var, &newpath);
 }
 
-pub struct Result {pub status: ProcessExit, pub out: String, pub err: String}
+pub struct Result {pub status: ExitStatus, pub out: String, pub err: String}
 
 pub fn run(lib_path: &str,
            prog: &str,
@@ -38,10 +39,13 @@ pub fn run(lib_path: &str,
            input: Option<String>) -> Option<Result> {
 
     let mut cmd = Command::new(prog);
-    cmd.args(args);
+    cmd.args(args)
+       .stdin(Stdio::piped())
+       .stdout(Stdio::piped())
+       .stderr(Stdio::piped());
     add_target_env(&mut cmd, lib_path, aux_path);
     for (key, val) in env {
-        cmd.env(key, val);
+        cmd.env(&key, &val);
     }
 
     match cmd.spawn() {
@@ -49,13 +53,13 @@ pub fn run(lib_path: &str,
             if let Some(input) = input {
                 process.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
             }
-            let ProcessOutput { status, output, error } =
+            let Output { status, stdout, stderr } =
                 process.wait_with_output().unwrap();
 
             Some(Result {
                 status: status,
-                out: String::from_utf8(output).unwrap(),
-                err: String::from_utf8(error).unwrap()
+                out: String::from_utf8(stdout).unwrap(),
+                err: String::from_utf8(stderr).unwrap()
             })
         },
         Err(..) => None
@@ -67,13 +71,16 @@ pub fn run_background(lib_path: &str,
            aux_path: Option<&str>,
            args: &[String],
            env: Vec<(String, String)> ,
-           input: Option<String>) -> Option<Process> {
+           input: Option<String>) -> Option<Child> {
 
     let mut cmd = Command::new(prog);
-    cmd.args(args);
+    cmd.args(args)
+       .stdin(Stdio::piped())
+       .stdout(Stdio::piped())
+       .stderr(Stdio::piped());
     add_target_env(&mut cmd, lib_path, aux_path);
     for (key, val) in env {
-        cmd.env(key, val);
+        cmd.env(&key, &val);
     }
 
     match cmd.spawn() {
index 7ac8a9b041c8327f33c8b6a38f2d8d9f518ca56f..7fb1a436ba3859e824c5e73db05c5392912f5ab0 100644 (file)
 use self::TargetLocation::*;
 
 use common::Config;
-use common::{CompileFail, ParseFail, Pretty, RunFail, RunPass, RunPassValgrind, DebugInfoGdb};
-use common::{Codegen, DebugInfoLldb};
+use common::{CompileFail, ParseFail, Pretty, RunFail, RunPass, RunPassValgrind};
+use common::{Codegen, DebugInfoLldb, DebugInfoGdb};
 use errors;
 use header::TestProps;
 use header;
 use procsrv;
 use util::logv;
-#[cfg(target_os = "windows")]
-use util;
-
-#[cfg(target_os = "windows")]
-use std::ascii::AsciiExt;
-use std::old_io::File;
-use std::old_io::fs::PathExtensions;
-use std::old_io::fs;
-use std::old_io::net::tcp;
-use std::old_io::process::ProcessExit;
-use std::old_io::process;
-use std::old_io::timer;
-use std::old_io;
+
 use std::env;
+use std::ffi::OsStr;
+use std::fmt;
+use std::fs::{self, File};
+use std::io::BufReader;
+use std::io::prelude::*;
 use std::iter::repeat;
+use std::net::TcpStream;
+use std::old_io::timer;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output, ExitStatus};
 use std::str;
-use std::string::String;
-use std::thread;
 use std::time::Duration;
 use test::MetricMap;
 
-pub fn run(config: Config, testfile: String) {
+pub fn run(config: Config, testfile: &Path) {
     match &*config.target {
 
         "arm-linux-androideabi" | "aarch64-linux-android" => {
@@ -55,12 +50,11 @@ pub fn run(config: Config, testfile: String) {
     run_metrics(config, testfile, &mut _mm);
 }
 
-pub fn run_metrics(config: Config, testfile: String, mm: &mut MetricMap) {
+pub fn run_metrics(config: Config, testfile: &Path, mm: &mut MetricMap) {
     if config.verbose {
         // We're going to be dumping a lot of info. Start on a new line.
         print!("\n\n");
     }
-    let testfile = Path::new(testfile);
     debug!("running {:?}", testfile.display());
     let props = header::load_props(&testfile);
     debug!("loaded props");
@@ -127,8 +121,8 @@ fn run_rfail_test(config: &Config, props: &TestProps, testfile: &Path) {
     };
 
     // The value our Makefile configures valgrind to return on failure
-    const VALGRIND_ERR: int = 100;
-    if proc_res.status.matches_exit_status(VALGRIND_ERR) {
+    const VALGRIND_ERR: i32 = 100;
+    if proc_res.status.code() == Some(VALGRIND_ERR) {
         fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
     }
 
@@ -139,10 +133,10 @@ fn run_rfail_test(config: &Config, props: &TestProps, testfile: &Path) {
 
 fn check_correct_failure_status(proc_res: &ProcRes) {
     // The value the rust runtime returns on failure
-    const RUST_ERR: int = 101;
-    if !proc_res.status.matches_exit_status(RUST_ERR) {
+    const RUST_ERR: i32 = 101;
+    if proc_res.status.code() != Some(RUST_ERR) {
         fatal_proc_rec(
-            &format!("failure produced the wrong error: {:?}",
+            &format!("failure produced the wrong error: {}",
                      proc_res.status),
             proc_res);
     }
@@ -201,8 +195,8 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
     let rounds =
         match props.pp_exact { Some(_) => 1, None => 2 };
 
-    let src = File::open(testfile).read_to_end().unwrap();
-    let src = String::from_utf8(src.clone()).unwrap();
+    let mut src = String::new();
+    File::open(testfile).unwrap().read_to_string(&mut src).unwrap();
     let mut srcs = vec!(src);
 
     let mut round = 0;
@@ -226,9 +220,10 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
 
     let mut expected = match props.pp_exact {
         Some(ref file) => {
-            let filepath = testfile.dir_path().join(file);
-            let s = File::open(&filepath).read_to_end().unwrap();
-            String::from_utf8(s).unwrap()
+            let filepath = testfile.parent().unwrap().join(file);
+            let mut s = String::new();
+            File::open(&filepath).unwrap().read_to_string(&mut s).unwrap();
+            s
         }
         None => { srcs[srcs.len() - 2].clone() }
     };
@@ -283,7 +278,7 @@ fn print_source(config: &Config,
                                      pretty_type.to_string()),
                         props.exec_env.clone(),
                         &config.compile_lib_path,
-                        Some(aux_dir.as_str().unwrap()),
+                        Some(aux_dir.to_str().unwrap()),
                         Some(src))
     }
 
@@ -299,11 +294,11 @@ fn make_pp_args(config: &Config,
                             pretty_type,
                             format!("--target={}", config.target),
                             "-L".to_string(),
-                            aux_dir.as_str().unwrap().to_string());
+                            aux_dir.to_str().unwrap().to_string());
         args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
         args.extend(split_maybe_args(&props.compile_flags).into_iter());
         return ProcArgs {
-            prog: config.rustc_path.as_str().unwrap().to_string(),
+            prog: config.rustc_path.to_str().unwrap().to_string(),
             args: args,
         };
     }
@@ -345,14 +340,14 @@ fn make_typecheck_args(config: &Config, props: &TestProps, testfile: &Path) -> P
                             "--crate-type=lib".to_string(),
                             format!("--target={}", target),
                             "-L".to_string(),
-                            config.build_base.as_str().unwrap().to_string(),
+                            config.build_base.to_str().unwrap().to_string(),
                             "-L".to_string(),
-                            aux_dir.as_str().unwrap().to_string());
+                            aux_dir.to_str().unwrap().to_string());
         args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
         args.extend(split_maybe_args(&props.compile_flags).into_iter());
         // FIXME (#9639): This needs to handle non-utf8 paths
         return ProcArgs {
-            prog: config.rustc_path.as_str().unwrap().to_string(),
+            prog: config.rustc_path.to_str().unwrap().to_string(),
             args: args,
         };
     }
@@ -390,18 +385,19 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
             // write debugger script
             let mut script_str = String::with_capacity(2048);
             script_str.push_str("set charset UTF-8\n");
-            script_str.push_str(&format!("file {}\n", exe_file.as_str().unwrap()));
+            script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
             script_str.push_str("target remote :5039\n");
             script_str.push_str(&format!("set solib-search-path \
                                          ./{}/stage2/lib/rustlib/{}/lib/\n",
                                          config.host, config.target));
             for line in breakpoint_lines.iter() {
                 script_str.push_str(&format!("break {:?}:{}\n",
-                                             testfile.filename_display(),
+                                             testfile.file_name().unwrap()
+                                                     .to_string_lossy(),
                                              *line)[..]);
             }
             script_str.push_str(&cmds);
-            script_str.push_str("quit\n");
+            script_str.push_str("\nquit\n");
 
             debug!("script_str = {}", script_str);
             dump_output_file(config,
@@ -415,7 +411,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                          None,
                          &[
                             "push".to_string(),
-                            exe_file.as_str().unwrap().to_string(),
+                            exe_file.to_str().unwrap().to_string(),
                             config.adb_test_dir.clone()
                          ],
                          vec!(("".to_string(), "".to_string())),
@@ -440,9 +436,8 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                                   if config.target.contains("aarch64")
                                   {"64"} else {""},
                                   config.adb_test_dir.clone(),
-                                  str::from_utf8(
-                                      exe_file.filename()
-                                      .unwrap()).unwrap());
+                                  exe_file.file_name().unwrap().to_str()
+                                          .unwrap());
 
             let mut process = procsrv::run_background("",
                                                       &config.adb_path
@@ -459,16 +454,12 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
             loop {
                 //waiting 1 second for gdbserver start
                 timer::sleep(Duration::milliseconds(1000));
-                let result = thread::spawn(move || {
-                    tcp::TcpStream::connect("127.0.0.1:5039").unwrap();
-                }).join();
-                if result.is_err() {
-                    continue;
+                if TcpStream::connect("127.0.0.1:5039").is_ok() {
+                    break
                 }
-                break;
             }
 
-            let tool_path = match config.android_cross_path.as_str() {
+            let tool_path = match config.android_cross_path.to_str() {
                 Some(x) => x.to_string(),
                 None => fatal("cannot find android cross path")
             };
@@ -479,7 +470,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                 vec!("-quiet".to_string(),
                      "-batch".to_string(),
                      "-nx".to_string(),
-                     format!("-command={}", debugger_script.as_str().unwrap()));
+                     format!("-command={}", debugger_script.to_str().unwrap()));
 
             let mut gdb_path = tool_path;
             gdb_path.push_str(&format!("/bin/{}-gdb", config.target));
@@ -503,12 +494,12 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
             };
 
             debugger_run_result = ProcRes {
-                status: status,
+                status: Status::Normal(status),
                 stdout: out,
                 stderr: err,
                 cmdline: cmdline
             };
-            if process.signal_kill().is_err() {
+            if process.kill().is_err() {
                 println!("Adb process is already finished.");
             }
         }
@@ -518,7 +509,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                 .expect("Could not find Rust source root");
             let rust_pp_module_rel_path = Path::new("./src/etc");
             let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
-                                                       .as_str()
+                                                       .to_str()
                                                        .unwrap()
                                                        .to_string();
             // write debugger script
@@ -538,7 +529,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                         // GDB's script auto loading safe path
                         script_str.push_str(
                             &format!("add-auto-load-safe-path {}\n",
-                                     rust_pp_module_abs_path.replace("\\", "\\\\"))
+                                     rust_pp_module_abs_path.replace(r"\", r"\\"))
                                 );
                     }
                 }
@@ -553,21 +544,24 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
             script_str.push_str("set print pretty off\n");
 
             // Add the pretty printer directory to GDB's source-file search path
-            script_str.push_str(&format!("directory {}\n", rust_pp_module_abs_path)[..]);
+            script_str.push_str(&format!("directory {}\n",
+                                         rust_pp_module_abs_path));
 
             // Load the target executable
             script_str.push_str(&format!("file {}\n",
-                                         exe_file.as_str().unwrap().replace("\\", "\\\\"))[..]);
+                                         exe_file.to_str().unwrap()
+                                                 .replace(r"\", r"\\")));
 
             // Add line breakpoints
             for line in &breakpoint_lines {
                 script_str.push_str(&format!("break '{}':{}\n",
-                                             testfile.filename_display(),
-                                             *line)[..]);
+                                             testfile.file_name().unwrap()
+                                                     .to_string_lossy(),
+                                             *line));
             }
 
             script_str.push_str(&cmds);
-            script_str.push_str("quit\n");
+            script_str.push_str("\nquit\n");
 
             debug!("script_str = {}", script_str);
             dump_output_file(config,
@@ -576,13 +570,8 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                              "debugger.script");
 
             // run debugger script with gdb
-            #[cfg(windows)]
-            fn debugger() -> String {
-                "gdb.exe".to_string()
-            }
-            #[cfg(unix)]
-            fn debugger() -> String {
-                "gdb".to_string()
+            fn debugger() -> &'static str {
+                if cfg!(windows) {"gdb.exe"} else {"gdb"}
             }
 
             let debugger_script = make_out_name(config, testfile, "debugger.script");
@@ -592,10 +581,10 @@ fn debugger() -> String {
                 vec!("-quiet".to_string(),
                      "-batch".to_string(),
                      "-nx".to_string(),
-                     format!("-command={}", debugger_script.as_str().unwrap()));
+                     format!("-command={}", debugger_script.to_str().unwrap()));
 
             let proc_args = ProcArgs {
-                prog: debugger(),
+                prog: debugger().to_string(),
                 args: debugger_opts,
             };
 
@@ -618,7 +607,7 @@ fn debugger() -> String {
     check_debugger_output(&debugger_run_result, &check_lines);
 }
 
-fn find_rust_src_root(config: &Config) -> Option<Path> {
+fn find_rust_src_root(config: &Config) -> Option<PathBuf> {
     let mut path = config.src_base.clone();
     let path_postfix = Path::new("src/etc/lldb_batchmode.py");
 
@@ -632,8 +621,6 @@ fn find_rust_src_root(config: &Config) -> Option<Path> {
 }
 
 fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) {
-    use std::old_io::process::{Command, ProcessOutput};
-
     if config.lldb_python_dir.is_none() {
         fatal("Can't run LLDB test because LLDB's python path is not set.");
     }
@@ -685,11 +672,12 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
         .expect("Could not find Rust source root");
     let rust_pp_module_rel_path = Path::new("./src/etc/lldb_rust_formatters.py");
     let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
-                                               .as_str()
+                                               .to_str()
                                                .unwrap()
                                                .to_string();
 
-    script_str.push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[..])[..]);
+    script_str.push_str(&format!("command script import {}\n",
+                                 &rust_pp_module_abs_path[..])[..]);
     script_str.push_str("type summary add --no-value ");
     script_str.push_str("--python-function lldb_rust_formatters.print_val ");
     script_str.push_str("-x \".*\" --category Rust\n");
@@ -707,7 +695,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
     }
 
     // Finally, quit the debugger
-    script_str.push_str("quit\n");
+    script_str.push_str("\nquit\n");
 
     // Write the script into a file
     debug!("script_str = {}", script_str);
@@ -735,22 +723,19 @@ fn run_lldb(config: &Config,
                 rust_src_root: &Path)
                 -> ProcRes {
         // Prepare the lldb_batchmode which executes the debugger script
-        let lldb_script_path = rust_src_root.join(Path::new("./src/etc/lldb_batchmode.py"));
+        let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
 
         let mut cmd = Command::new("python");
-        cmd.arg(lldb_script_path)
+        cmd.arg(&lldb_script_path)
            .arg(test_executable)
            .arg(debugger_script)
-           .env_set_all(&[("PYTHONPATH", config.lldb_python_dir.clone().unwrap())]);
-
-        let (status, out, err) = match cmd.spawn() {
-            Ok(process) => {
-                let ProcessOutput { status, output, error } =
-                    process.wait_with_output().unwrap();
+           .env("PYTHONPATH", config.lldb_python_dir.as_ref().unwrap());
 
+        let (status, out, err) = match cmd.output() {
+            Ok(Output { status, stdout, stderr }) => {
                 (status,
-                 String::from_utf8(output).unwrap(),
-                 String::from_utf8(error).unwrap())
+                 String::from_utf8(stdout).unwrap(),
+                 String::from_utf8(stderr).unwrap())
             },
             Err(e) => {
                 fatal(&format!("Failed to setup Python process for \
@@ -760,7 +745,7 @@ fn run_lldb(config: &Config,
 
         dump_output(config, test_executable, &out, &err);
         return ProcRes {
-            status: status,
+            status: Status::Normal(status),
             stdout: out,
             stderr: err,
             cmdline: format!("{:?}", cmd)
@@ -776,8 +761,6 @@ struct DebuggerCommands {
 
 fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
                            -> DebuggerCommands {
-    use std::old_io::{BufferedReader, File};
-
     let command_directive = format!("{}-command", debugger_prefix);
     let check_directive = format!("{}-check", debugger_prefix);
 
@@ -785,7 +768,7 @@ fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
     let mut commands = vec!();
     let mut check_lines = vec!();
     let mut counter = 1;
-    let mut reader = BufferedReader::new(File::open(file_path).unwrap());
+    let reader = BufReader::new(File::open(file_path).unwrap());
     for line in reader.lines() {
         match line {
             Ok(line) => {
@@ -963,16 +946,17 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
 
     let prefixes = expected_errors.iter().map(|ee| {
         format!("{}:{}:", testfile.display(), ee.line)
-    }).collect::<Vec<String> >();
-
-    #[cfg(windows)]
-    fn prefix_matches( line : &str, prefix : &str ) -> bool {
-        line.to_ascii_lowercase().starts_with(&prefix.to_ascii_lowercase())
-    }
-
-    #[cfg(unix)]
-    fn prefix_matches( line : &str, prefix : &str ) -> bool {
-        line.starts_with( prefix )
+    }).collect::<Vec<String>>();
+
+    fn prefix_matches(line: &str, prefix: &str) -> bool {
+        use std::ascii::AsciiExt;
+        // On windows just translate all '\' path separators to '/'
+        let line = line.replace(r"\", "/");
+        if cfg!(windows) {
+            line.to_ascii_lowercase().starts_with(&prefix.to_ascii_lowercase())
+        } else {
+            line.starts_with(prefix)
+        }
     }
 
     // A multi-line error will have followup lines which will always
@@ -1113,12 +1097,42 @@ struct ProcArgs {
 }
 
 struct ProcRes {
-    status: ProcessExit,
+    status: Status,
     stdout: String,
     stderr: String,
     cmdline: String,
 }
 
+enum Status {
+    Parsed(i32),
+    Normal(ExitStatus),
+}
+
+impl Status {
+    fn code(&self) -> Option<i32> {
+        match *self {
+            Status::Parsed(i) => Some(i),
+            Status::Normal(ref e) => e.code(),
+        }
+    }
+
+    fn success(&self) -> bool {
+        match *self {
+            Status::Parsed(i) => i == 0,
+            Status::Normal(ref e) => e.success(),
+        }
+    }
+}
+
+impl fmt::Display for Status {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        match *self {
+            Status::Parsed(i) => write!(f, "exit code: {}", i),
+            Status::Normal(ref e) => e.fmt(f),
+        }
+    }
+}
+
 fn compile_test(config: &Config, props: &TestProps,
                 testfile: &Path) -> ProcRes {
     compile_test_(config, props, testfile, &[])
@@ -1133,7 +1147,7 @@ fn compile_test_(config: &Config, props: &TestProps,
     let aux_dir = aux_output_dir_name(config, testfile);
     // FIXME (#9639): This needs to handle non-utf8 paths
     let mut link_args = vec!("-L".to_string(),
-                             aux_dir.as_str().unwrap().to_string());
+                             aux_dir.to_str().unwrap().to_string());
     link_args.extend(extra_args.iter().cloned());
     let args = make_compile_args(config,
                                  props,
@@ -1160,7 +1174,7 @@ fn exec_compiled_test(config: &Config, props: &TestProps,
                             make_run_args(config, props, testfile),
                             env,
                             &config.run_lib_path,
-                            Some(aux_dir.as_str().unwrap()),
+                            Some(aux_dir.to_str().unwrap()),
                             None)
         }
     }
@@ -1179,7 +1193,7 @@ fn compose_and_run_compiler(
 
     let aux_dir = aux_output_dir_name(config, testfile);
     // FIXME (#9639): This needs to handle non-utf8 paths
-    let extra_link_args = vec!("-L".to_string(), aux_dir.as_str().unwrap().to_string());
+    let extra_link_args = vec!("-L".to_string(), aux_dir.to_str().unwrap().to_string());
 
     for rel_ab in &props.aux_builds {
         let abs_ab = config.aux_base.join(rel_ab);
@@ -1196,7 +1210,8 @@ fn compose_and_run_compiler(
                               crate_type,
                               |a,b| {
                                   let f = make_lib_name(a, b, testfile);
-                                  TargetLocation::ThisDirectory(f.dir_path())
+                                  let parent = f.parent().unwrap();
+                                  TargetLocation::ThisDirectory(parent.to_path_buf())
                               },
                               &abs_ab);
         let auxres = compose_and_run(config,
@@ -1204,7 +1219,7 @@ fn compose_and_run_compiler(
                                      aux_args,
                                      Vec::new(),
                                      &config.compile_lib_path,
-                                     Some(aux_dir.as_str().unwrap()),
+                                     Some(aux_dir.to_str().unwrap()),
                                      None);
         if !auxres.status.success() {
             fatal_proc_rec(
@@ -1226,13 +1241,13 @@ fn compose_and_run_compiler(
                     args,
                     Vec::new(),
                     &config.compile_lib_path,
-                    Some(aux_dir.as_str().unwrap()),
+                    Some(aux_dir.to_str().unwrap()),
                     input)
 }
 
 fn ensure_dir(path: &Path) {
     if path.is_dir() { return; }
-    fs::mkdir(path, old_io::USER_RWX).unwrap();
+    fs::create_dir(path).unwrap();
 }
 
 fn compose_and_run(config: &Config, testfile: &Path,
@@ -1246,8 +1261,8 @@ fn compose_and_run(config: &Config, testfile: &Path,
 }
 
 enum TargetLocation {
-    ThisFile(Path),
-    ThisDirectory(Path),
+    ThisFile(PathBuf),
+    ThisDirectory(PathBuf),
 }
 
 fn make_compile_args<F>(config: &Config,
@@ -1265,9 +1280,9 @@ fn make_compile_args<F>(config: &Config,
         &*config.target
     };
     // FIXME (#9639): This needs to handle non-utf8 paths
-    let mut args = vec!(testfile.as_str().unwrap().to_string(),
+    let mut args = vec!(testfile.to_str().unwrap().to_string(),
                         "-L".to_string(),
-                        config.build_base.as_str().unwrap().to_string(),
+                        config.build_base.to_str().unwrap().to_string(),
                         format!("--target={}", target));
     args.push_all(&extras);
     if !props.no_prefer_dynamic {
@@ -1284,7 +1299,7 @@ fn make_compile_args<F>(config: &Config,
             path
         }
     };
-    args.push(path.as_str().unwrap().to_string());
+    args.push(path.to_str().unwrap().to_string());
     if props.force_host {
         args.extend(split_maybe_args(&config.host_rustcflags).into_iter());
     } else {
@@ -1292,24 +1307,24 @@ fn make_compile_args<F>(config: &Config,
     }
     args.extend(split_maybe_args(&props.compile_flags).into_iter());
     return ProcArgs {
-        prog: config.rustc_path.as_str().unwrap().to_string(),
+        prog: config.rustc_path.to_str().unwrap().to_string(),
         args: args,
     };
 }
 
-fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> Path {
+fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> PathBuf {
     // what we return here is not particularly important, as it
     // happens; rustc ignores everything except for the directory.
     let auxname = output_testname(auxfile);
     aux_output_dir_name(config, testfile).join(&auxname)
 }
 
-fn make_exe_name(config: &Config, testfile: &Path) -> Path {
+fn make_exe_name(config: &Config, testfile: &Path) -> PathBuf {
     let mut f = output_base_name(config, testfile);
     if !env::consts::EXE_SUFFIX.is_empty() {
-        let mut fname = f.filename().unwrap().to_vec();
-        fname.extend(env::consts::EXE_SUFFIX.bytes());
-        f.set_filename(fname);
+        let mut fname = f.file_name().unwrap().to_os_string();
+        fname.push_os_str(OsStr::from_str(env::consts::EXE_SUFFIX));
+        f.set_file_name(&fname);
     }
     f
 }
@@ -1322,7 +1337,7 @@ fn make_run_args(config: &Config, props: &TestProps, testfile: &Path) ->
     let exe_file = make_exe_name(config, testfile);
 
     // FIXME (#9639): This needs to handle non-utf8 paths
-    args.push(exe_file.as_str().unwrap().to_string());
+    args.push(exe_file.to_str().unwrap().to_string());
 
     // Add the arguments in the run_flags directive
     args.extend(split_maybe_args(&props.run_flags).into_iter());
@@ -1375,29 +1390,28 @@ fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String
                      input).expect(&format!("failed to exec `{}`", prog));
     dump_output(config, testfile, &out, &err);
     return ProcRes {
-        status: status,
+        status: Status::Normal(status),
         stdout: out,
         stderr: err,
         cmdline: cmdline,
     };
 }
 
-// Linux and mac don't require adjusting the library search path
-#[cfg(unix)]
-fn make_cmdline(_libpath: &str, prog: &str, args: &[String]) -> String {
-    format!("{} {}", prog, args.connect(" "))
-}
-
-#[cfg(windows)]
 fn make_cmdline(libpath: &str, prog: &str, args: &[String]) -> String {
+    use util;
 
-    // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
-    // for diagnostic purposes
-    fn lib_path_cmd_prefix(path: &str) -> String {
-        format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
-    }
+    // Linux and mac don't require adjusting the library search path
+    if cfg!(unix) {
+        format!("{} {}", prog, args.connect(" "))
+    } else {
+        // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
+        // for diagnostic purposes
+        fn lib_path_cmd_prefix(path: &str) -> String {
+            format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
+        }
 
-    format!("{} {} {}", lib_path_cmd_prefix(libpath), prog, args.connect(" "))
+        format!("{} {} {}", lib_path_cmd_prefix(libpath), prog, args.connect(" "))
+    }
 }
 
 fn dump_output(config: &Config, testfile: &Path, out: &str, err: &str) {
@@ -1409,25 +1423,25 @@ fn dump_output(config: &Config, testfile: &Path, out: &str, err: &str) {
 fn dump_output_file(config: &Config, testfile: &Path,
                     out: &str, extension: &str) {
     let outfile = make_out_name(config, testfile, extension);
-    File::create(&outfile).write_all(out.as_bytes()).unwrap();
+    File::create(&outfile).unwrap().write_all(out.as_bytes()).unwrap();
 }
 
-fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> Path {
+fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> PathBuf {
     output_base_name(config, testfile).with_extension(extension)
 }
 
-fn aux_output_dir_name(config: &Config, testfile: &Path) -> Path {
+fn aux_output_dir_name(config: &Config, testfile: &Path) -> PathBuf {
     let f = output_base_name(config, testfile);
-    let mut fname = f.filename().unwrap().to_vec();
-    fname.extend("libaux".bytes());
-    f.with_filename(fname)
+    let mut fname = f.file_name().unwrap().to_os_string();
+    fname.push_os_str(OsStr::from_str("libaux"));
+    f.with_file_name(&fname)
 }
 
-fn output_testname(testfile: &Path) -> Path {
-    Path::new(testfile.filestem().unwrap())
+fn output_testname(testfile: &Path) -> PathBuf {
+    PathBuf::new(testfile.file_stem().unwrap())
 }
 
-fn output_base_name(config: &Config, testfile: &Path) -> Path {
+fn output_base_name(config: &Config, testfile: &Path) -> PathBuf {
     config.build_base
         .join(&output_testname(testfile))
         .with_extension(&config.stage_id)
@@ -1542,11 +1556,11 @@ fn _arm_exec_compiled_test(config: &Config,
                      Some("".to_string()))
         .expect(&format!("failed to exec `{}`", config.adb_path));
 
-    let mut exitcode: int = 0;
+    let mut exitcode: i32 = 0;
     for c in exitcode_out.chars() {
         if !c.is_numeric() { break; }
         exitcode = exitcode * 10 + match c {
-            '0' ... '9' => c as int - ('0' as int),
+            '0' ... '9' => c as i32 - ('0' as i32),
             _ => 101,
         }
     }
@@ -1587,7 +1601,7 @@ fn _arm_exec_compiled_test(config: &Config,
                 &stderr_out);
 
     ProcRes {
-        status: process::ProcessExit::ExitStatus(exitcode),
+        status: Status::Parsed(exitcode),
         stdout: stdout_out,
         stderr: stderr_out,
         cmdline: cmdline
@@ -1597,16 +1611,17 @@ fn _arm_exec_compiled_test(config: &Config,
 fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
     let tdir = aux_output_dir_name(config, testfile);
 
-    let dirs = fs::readdir(&tdir).unwrap();
-    for file in &dirs {
-        if file.extension_str() == Some("so") {
+    let dirs = fs::read_dir(&tdir).unwrap();
+    for file in dirs {
+        let file = file.unwrap().path();
+        if file.extension().and_then(|s| s.to_str()) == Some("so") {
             // FIXME (#9639): This needs to handle non-utf8 paths
             let copy_result = procsrv::run("",
                                            &config.adb_path,
                                            None,
                                            &[
                                             "push".to_string(),
-                                            file.as_str()
+                                            file.to_str()
                                                 .unwrap()
                                                 .to_string(),
                                             config.adb_test_dir.to_string(),
@@ -1627,14 +1642,14 @@ fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
 
 // codegen tests (vs. clang)
 
-fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
+fn append_suffix_to_stem(p: &Path, suffix: &str) -> PathBuf {
     if suffix.len() == 0 {
-        (*p).clone()
+        p.to_path_buf()
     } else {
-        let mut stem = p.filestem().unwrap().to_vec();
-        stem.extend("-".bytes());
-        stem.extend(suffix.bytes());
-        p.with_filename(stem)
+        let mut stem = p.file_stem().unwrap().to_os_string();
+        stem.push_os_str(OsStr::from_str("-"));
+        stem.push_os_str(OsStr::from_str(suffix));
+        p.with_file_name(&stem)
     }
 }
 
@@ -1643,7 +1658,7 @@ fn compile_test_and_save_bitcode(config: &Config, props: &TestProps,
     let aux_dir = aux_output_dir_name(config, testfile);
     // FIXME (#9639): This needs to handle non-utf8 paths
     let mut link_args = vec!("-L".to_string(),
-                             aux_dir.as_str().unwrap().to_string());
+                             aux_dir.to_str().unwrap().to_string());
     let llvm_args = vec!("--emit=llvm-bc,obj".to_string(),
                          "--crate-type=lib".to_string());
     link_args.extend(llvm_args.into_iter());
@@ -1651,7 +1666,8 @@ fn compile_test_and_save_bitcode(config: &Config, props: &TestProps,
                                  props,
                                  link_args,
                                  |a, b| TargetLocation::ThisDirectory(
-                                     output_base_name(a, b).dir_path()),
+                                     output_base_name(a, b).parent()
+                                        .unwrap().to_path_buf()),
                                  testfile);
     compose_and_run_compiler(config, props, testfile, args, None)
 }
@@ -1663,12 +1679,12 @@ fn compile_cc_with_clang_and_save_bitcode(config: &Config, _props: &TestProps,
     let testcc = testfile.with_extension("cc");
     let proc_args = ProcArgs {
         // FIXME (#9639): This needs to handle non-utf8 paths
-        prog: config.clang_path.as_ref().unwrap().as_str().unwrap().to_string(),
+        prog: config.clang_path.as_ref().unwrap().to_str().unwrap().to_string(),
         args: vec!("-c".to_string(),
                    "-emit-llvm".to_string(),
                    "-o".to_string(),
-                   bitcodefile.as_str().unwrap().to_string(),
-                   testcc.as_str().unwrap().to_string())
+                   bitcodefile.to_str().unwrap().to_string(),
+                   testcc.to_str().unwrap().to_string())
     };
     compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
 }
@@ -1682,10 +1698,10 @@ fn extract_function_from_bitcode(config: &Config, _props: &TestProps,
     let prog = config.llvm_bin_path.as_ref().unwrap().join("llvm-extract");
     let proc_args = ProcArgs {
         // FIXME (#9639): This needs to handle non-utf8 paths
-        prog: prog.as_str().unwrap().to_string(),
+        prog: prog.to_str().unwrap().to_string(),
         args: vec!(format!("-func={}", fname),
-                   format!("-o={}", extracted_bc.as_str().unwrap()),
-                   bitcodefile.as_str().unwrap().to_string())
+                   format!("-o={}", extracted_bc.to_str().unwrap()),
+                   bitcodefile.to_str().unwrap().to_string())
     };
     compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
 }
@@ -1699,16 +1715,17 @@ fn disassemble_extract(config: &Config, _props: &TestProps,
     let prog = config.llvm_bin_path.as_ref().unwrap().join("llvm-dis");
     let proc_args = ProcArgs {
         // FIXME (#9639): This needs to handle non-utf8 paths
-        prog: prog.as_str().unwrap().to_string(),
-        args: vec!(format!("-o={}", extracted_ll.as_str().unwrap()),
-                   extracted_bc.as_str().unwrap().to_string())
+        prog: prog.to_str().unwrap().to_string(),
+        args: vec!(format!("-o={}", extracted_ll.to_str().unwrap()),
+                   extracted_bc.to_str().unwrap().to_string())
     };
     compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
 }
 
 
 fn count_extracted_lines(p: &Path) -> uint {
-    let x = File::open(&p.with_extension("ll")).read_to_end().unwrap();
+    let mut x = Vec::new();
+    File::open(&p.with_extension("ll")).unwrap().read_to_end(&mut x).unwrap();
     let x = str::from_utf8(&x).unwrap();
     x.lines().count()
 }
index c0d7c59ef6a1bbf2c1fdc42a002c31cda8a52562..16e2806f72cecd2bdeef69af472fda23e4798311 100644 (file)
@@ -8,10 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use common::Config;
-
-#[cfg(target_os = "windows")]
 use std::env;
+use common::Config;
 
 /// Conversion table from triple OS name to Rust SYSNAME
 const OS_TABLE: &'static [(&'static str, &'static str)] = &[
@@ -36,24 +34,20 @@ pub fn get_os(triple: &str) -> &'static str {
     panic!("Cannot determine OS from triple");
 }
 
-#[cfg(target_os = "windows")]
 pub fn make_new_path(path: &str) -> String {
-
+    assert!(cfg!(windows));
     // Windows just uses PATH as the library search path, so we have to
     // maintain the current value while adding our own
     match env::var(lib_path_env_var()) {
-      Ok(curr) => {
-        format!("{}{}{}", path, path_div(), curr)
-      }
-      Err(..) => path.to_string()
+        Ok(curr) => {
+            format!("{}{}{}", path, path_div(), curr)
+        }
+        Err(..) => path.to_string()
     }
 }
 
-#[cfg(target_os = "windows")]
 pub fn lib_path_env_var() -> &'static str { "PATH" }
-
-#[cfg(target_os = "windows")]
-pub fn path_div() -> &'static str { ";" }
+fn path_div() -> &'static str { ";" }
 
 pub fn logv(config: &Config, s: String) {
     debug!("{}", s);
index 333d6fddbbdf2f7a6fc27626962be24977b53d8e..fa4986816aa1ca5f044b2eda87830f32b4046575 100644 (file)
@@ -764,7 +764,15 @@ usually in [procedural macros](book/plugins.html#syntax-extensions):
 * `quote_pat!`
 * `quote_stmt!`
 * `quote_tokens!`
+* `quote_matcher!`
 * `quote_ty!`
+* `quote_attr!`
+
+Keep in mind that when `$name : ident` appears in the input to
+`quote_tokens!`, the result contains unquoted `name` followed by two tokens.
+However, input of the same form passed to `quote_matcher!` becomes a
+quasiquoted MBE-matcher of a nonterminal. No unquotation happens. Otherwise
+the result of `quote_matcher!` is identical to that of `quote_tokens!`.
 
 Documentation is very limited at the moment.
 
index 0f46b4da0d6f971b6ae3371d4850a5b8774493f0..e56706500a004f394e4bcc0b6a28c839a3f2ed5a 100644 (file)
@@ -709,7 +709,7 @@ fn main() {
         one_hundred: 100,
     });
 
-    let y = box foo(x);
+    let y: Box<BigStruct> = box foo(x);
 }
 ```
 
index fd3309dce12cbd01e1c573e05beeddb096a7c2f1..c524fae7f0a42e6272ce736cd5d54517702baa11 100644 (file)
@@ -13,7 +13,7 @@ import fileinput
 import subprocess
 import re
 import os
-from licenseck import *
+from licenseck import check_license
 import snapshot
 
 err = 0
@@ -22,13 +22,8 @@ cr_flag = "ignore-tidy-cr"
 tab_flag = "ignore-tidy-tab"
 linelength_flag = "ignore-tidy-linelength"
 
-# Be careful to support Python 2.4, 2.6, and 3.x here!
-config_proc = subprocess.Popen(["git", "config", "core.autocrlf"],
-                               stdout=subprocess.PIPE)
-result = config_proc.communicate()[0]
-
-true = "true".encode('utf8')
-autocrlf = result.strip() == true if result is not None else False
+interesting_files = ['.rs', '.py', '.js', '.sh', '.c', '.h']
+uninteresting_files = ['miniz.c', 'jquery', 'rust_android_dummy']
 
 
 def report_error_name_no(name, no, s):
@@ -51,6 +46,34 @@ def do_license_check(name, contents):
     if not check_license(name, contents):
         report_error_name_no(name, 1, "incorrect license")
 
+
+def update_counts(current_name):
+    global file_counts
+    global count_other_linted_files
+
+    _, ext = os.path.splitext(current_name)
+
+    if ext in interesting_files:
+        file_counts[ext] += 1
+    else:
+        count_other_linted_files += 1
+
+
+def interesting_file(f):
+    if any(x in f for x in uninteresting_files):
+        return False
+
+    return any(os.path.splitext(f)[1] == ext for ext in interesting_files)
+
+
+# Be careful to support Python 2.4, 2.6, and 3.x here!
+config_proc = subprocess.Popen(["git", "config", "core.autocrlf"],
+                               stdout=subprocess.PIPE)
+result = config_proc.communicate()[0]
+
+true = "true".encode('utf8')
+autocrlf = result.strip() == true if result is not None else False
+
 current_name = ""
 current_contents = ""
 check_tab = True
@@ -63,28 +86,16 @@ if len(sys.argv) < 2:
 
 src_dir = sys.argv[1]
 
-try:
-    count_lines = 0
-    count_non_blank_lines = 0
+count_lines = 0
+count_non_blank_lines = 0
+count_other_linted_files = 0
 
-    interesting_files = ['.rs', '.py', '.js', '.sh', '.c', '.h']
+file_counts = {ext: 0 for ext in interesting_files}
 
-    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()
+all_paths = set()
 
+try:
     for (dirpath, dirnames, filenames) in os.walk(src_dir):
-
         # Skip some third-party directories
         skippable_dirs = {
             'src/jemalloc',
@@ -103,14 +114,6 @@ try:
         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")
@@ -196,10 +199,11 @@ 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)
+for ext in sorted(file_counts, key=file_counts.get, reverse=True):
+    print "* linted {} {} files".format(file_counts[ext], ext)
+print "* linted {} other files".format(count_other_linted_files)
+print "* total lines of code: {}".format(count_lines)
+print "* total non-blank lines of code: {}".format(count_non_blank_lines)
 print
 
 sys.exit(err)
index 6a6f7e0e9f92cb99627b0fe24cdf71f2e71f8a60..6c3fd186cd423bdea36260cc459fe361602eb0e2 100644 (file)
@@ -152,6 +152,12 @@ extern char *yytext;
 %precedence MOD_SEP
 %precedence RARROW ':'
 
+// In where clauses, "for" should have greater precedence when used as
+// a higher ranked constraint than when used as the beginning of a
+// for_in_type (which is a ty)
+%precedence FORTYPE
+%precedence FOR
+
 // Binops & unops, and their precedences
 %precedence BOX
 %precedence BOXPLACE
@@ -582,6 +588,14 @@ item_impl
 {
   $$ = mk_node("ItemImplNeg", 7, $1, $3, $5, $7, $8, $10, $11);
 }
+| maybe_unsafe IMPL generic_params trait_ref FOR DOTDOT '{' '}'
+{
+  $$ = mk_node("ItemImplDefault", 3, $1, $3, $4);
+}
+| maybe_unsafe IMPL generic_params '!' trait_ref FOR DOTDOT '{' '}'
+{
+  $$ = mk_node("ItemImplDefaultNeg", 3, $1, $3, $4);
+}
 ;
 
 maybe_impl_items
@@ -769,10 +783,14 @@ where_predicates
 ;
 
 where_predicate
-: lifetime ':' bounds    { $$ = mk_node("WherePredicate", 2, $1, $3); }
-| ty ':' ty_param_bounds { $$ = mk_node("WherePredicate", 2, $1, $3); }
+: maybe_for_lifetimes lifetime ':' bounds    { $$ = mk_node("WherePredicate", 3, $1, $2, $4); }
+| maybe_for_lifetimes ty ':' ty_param_bounds { $$ = mk_node("WherePredicate", 3, $1, $2, $4); }
 ;
 
+maybe_for_lifetimes
+: FOR '<' lifetimes '>' { $$ = mk_none(); }
+| %prec FORTYPE %empty  { $$ = mk_none(); }
+
 ty_params
 : ty_param               { $$ = mk_node("TyParams", 1, $1); }
 | ty_params ',' ty_param { $$ = ext_node($1, 1, $3); }
@@ -1024,7 +1042,8 @@ ty_qualified_path_and_generic_values
 }
 | ty_qualified_path ',' ty_sums maybe_bindings
 {
-  $$ = mk_node("GenericValues", 3, mk_none(), ext_node(mk_node("TySums", 1, $1), 1, $3), $4); }
+  $$ = mk_node("GenericValues", 3, mk_none(), mk_node("TySums", 2, $1, $3), $4);
+}
 ;
 
 ty_qualified_path
@@ -1513,31 +1532,35 @@ nonblock_prefix_expr
 ;
 
 expr_qualified_path
-: '<' ty_sum AS trait_ref '>' MOD_SEP ident
+: '<' ty_sum maybe_as_trait_ref '>' MOD_SEP ident
 {
-  $$ = mk_node("ExprQualifiedPath", 3, $2, $4, $7);
+  $$ = mk_node("ExprQualifiedPath", 3, $2, $3, $6);
 }
-| '<' ty_sum AS trait_ref '>' MOD_SEP ident generic_args
+| '<' ty_sum maybe_as_trait_ref '>' MOD_SEP ident generic_args
 {
-  $$ = mk_node("ExprQualifiedPath", 4, $2, $4, $7, $8);
+  $$ = mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7);
 }
-| SHL ty_sum AS trait_ref '>' MOD_SEP ident AS trait_ref '>' MOD_SEP ident
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_as_trait_ref '>' MOD_SEP ident
 {
-  $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 3, $2, $4, $7), $9, $12);
+  $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 3, $2, $3, $6), $7, $10);
 }
-| SHL ty_sum AS trait_ref '>' MOD_SEP ident generic_args AS trait_ref '>' MOD_SEP ident
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident generic_args maybe_as_trait_ref '>' MOD_SEP ident
 {
-  $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 4, $2, $4, $7, $8), $10, $13);
+  $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7), $8, $11);
 }
-| SHL ty_sum AS trait_ref '>' MOD_SEP ident AS trait_ref '>' MOD_SEP ident generic_args
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_as_trait_ref '>' MOD_SEP ident generic_args
 {
-  $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 3, $2, $4, $7), $9, $12, $13);
+  $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 3, $2, $3, $6), $7, $10, $11);
 }
-| SHL ty_sum AS trait_ref '>' MOD_SEP ident generic_args AS trait_ref '>' MOD_SEP ident generic_args
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident generic_args maybe_as_trait_ref '>' MOD_SEP ident generic_args
 {
-  $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 4, $2, $4, $7, $8), $10, $13, $14);
+  $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7), $8, $11, $12);
 }
 
+maybe_as_trait_ref
+: AS trait_ref { $$ = $2; }
+| %empty       { $$ = mk_none(); }
+;
 
 lambda_expr
 : %prec LAMBDA
index c95b413b397edb1fd489298ddde673707e4fce7a..dc1938cac1ada7b51f3d12e264d9e85245f9773d 100644 (file)
@@ -69,6 +69,8 @@
 //! }
 //! ```
 
+use boxed::Box;
+
 use core::prelude::*;
 
 use core::atomic;
@@ -170,7 +172,7 @@ impl<T> Arc<T> {
     pub fn new(data: T) -> Arc<T> {
         // Start the weak pointer count as 1 which is the weak pointer that's
         // held by all the strong pointers (kinda), see std/rc.rs for more info
-        let x = box ArcInner {
+        let x: Box<_> = box ArcInner {
             strong: atomic::AtomicUsize::new(1),
             weak: atomic::AtomicUsize::new(1),
             data: data,
index a93872dfe36bd8d522bd9fa3e56e10715f386605..630ca837daac8eb2ca5b75d56a14ba825f316cd3 100644 (file)
@@ -94,6 +94,7 @@ impl<T> Box<T> {
     /// let x = Box::new(5);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
+    #[inline(always)]
     pub fn new(x: T) -> Box<T> {
         box x
     }
@@ -156,7 +157,7 @@ fn default() -> Box<T> { box Default::default() }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> Default for Box<[T]> {
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn default() -> Box<[T]> { box [] }
+    fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
index 726d5c8a23b739c179c22701b9628a4a450ae11a..3b93171386a076e13d1f77a83e31756f2e8fb4a0 100644 (file)
@@ -387,6 +387,7 @@ mod test {
     extern crate test;
     use self::test::Bencher;
     use core::ptr::PtrExt;
+    use boxed::Box;
     use heap;
 
     #[test]
@@ -404,7 +405,7 @@ fn basic_reallocate_inplace_noop() {
     #[bench]
     fn alloc_owned_small(b: &mut Bencher) {
         b.iter(|| {
-            box 10
+            let _: Box<_> = box 10;
         })
     }
 }
index 82bd13475c74eabb6f106112edd5434c7411cc70..b1fdf139b0c51c739ac10325c00f93857eb538f8 100644 (file)
 
 // Primitive types using the heaps above
 
+// Need to conditionally define the mod from `boxed.rs` to avoid
+// duplicating the lang-items when building in test cfg; but also need
+// to allow code to have `use boxed::HEAP;`
+// and `use boxed::Box;` declarations.
 #[cfg(not(test))]
 pub mod boxed;
 #[cfg(test)]
+mod boxed { pub use std::boxed::{Box, HEAP}; }
+#[cfg(test)]
 mod boxed_test;
 pub mod arc;
 pub mod rc;
index f57286bbf11c9af56ee608e8b9af720ddf00eaa4..763dcc7f256e91534ac4a6c07e8745c8f91767fc 100644 (file)
@@ -795,6 +795,7 @@ fn inner(&self) -> &RcBox<T> {
 #[cfg(test)]
 mod tests {
     use super::{Rc, Weak, weak_count, strong_count};
+    use std::boxed::Box;
     use std::cell::RefCell;
     use std::option::Option;
     use std::option::Option::{Some, None};
@@ -826,7 +827,7 @@ fn test_simple_clone() {
 
     #[test]
     fn test_destructor() {
-        let x = Rc::new(box 5);
+        let x: Rc<Box<_>> = Rc::new(box 5);
         assert_eq!(**x, 5);
     }
 
index b43f9adfb26d92ed9c8f8f4ee8df7bc634c0cb46..4678fe15c8b7ba91efe53d6f9da1525a0ff5dbd1 100644 (file)
@@ -581,11 +581,11 @@ pub fn bench_copy(b: &mut Bencher) {
     #[bench]
     pub fn bench_copy_nonarena(b: &mut Bencher) {
         b.iter(|| {
-            box Point {
+            let _: Box<_> = box Point {
                 x: 1,
                 y: 2,
                 z: 3,
-            }
+            };
         })
     }
 
@@ -634,10 +634,10 @@ pub fn bench_noncopy(b: &mut Bencher) {
     #[bench]
     pub fn bench_noncopy_nonarena(b: &mut Bencher) {
         b.iter(|| {
-            box Noncopy {
+            let _: Box<_> = box Noncopy {
                 string: "hello world".to_string(),
                 array: vec!( 1, 2, 3, 4, 5 ),
-            }
+            };
         })
     }
 
index 36c76dbad14aefcb20076f4d9c63613aa80fe221..2e575ddb00a3275bb23cf8c33fedea0857050192 100644 (file)
@@ -790,7 +790,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::<Box<_>>::from_vec(vec![box 2, box 4, box 9]);
         assert_eq!(heap.len(), 3);
         assert!(*heap.peek().unwrap() == box 9);
         heap.push(box 11);
index 9b5fbfc25114c046012f4f7e2e2748c004017146..5ca3cb380583bc3e5580048b779d9a9ac42e8ccc 100644 (file)
@@ -984,7 +984,7 @@ pub fn check_links<T>(list: &LinkedList<T>) {
 
     #[test]
     fn test_basic() {
-        let mut m = LinkedList::new();
+        let mut m = LinkedList::<Box<_>>::new();
         assert_eq!(m.pop_front(), None);
         assert_eq!(m.pop_back(), None);
         assert_eq!(m.pop_front(), None);
index b3706e203523bb510ceab2587b0d234c9f00779c..23b256568dae416be84828fbee86873943122925 100644 (file)
@@ -1509,6 +1509,7 @@ unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
 
 #[cfg(test)]
 mod tests {
+    use alloc::boxed::Box;
     use core::cmp::Ordering::{Greater, Less, Equal};
     use core::prelude::{Some, None, Clone};
     use core::prelude::{Iterator, IteratorExt};
@@ -1799,7 +1800,7 @@ fn test_swap_remove_fail() {
     #[test]
     fn test_swap_remove_noncopyable() {
         // Tests that we don't accidentally run destructors twice.
-        let mut v = Vec::new();
+        let mut v: Vec<Box<_>> = Vec::new();
         v.push(box 0u8);
         v.push(box 0u8);
         v.push(box 0u8);
@@ -1828,7 +1829,7 @@ fn test_push() {
 
     #[test]
     fn test_truncate() {
-        let mut v = vec![box 6,box 5,box 4];
+        let mut v: Vec<Box<_>> = vec![box 6,box 5,box 4];
         v.truncate(1);
         let v = v;
         assert_eq!(v.len(), 1);
@@ -1838,7 +1839,7 @@ fn test_truncate() {
 
     #[test]
     fn test_clear() {
-        let mut v = vec![box 6,box 5,box 4];
+        let mut v: Vec<Box<_>> = vec![box 6,box 5,box 4];
         v.clear();
         assert_eq!(v.len(), 0);
         // If the unsafe block didn't drop things properly, we blow up here.
@@ -1863,11 +1864,11 @@ fn case(a: Vec<i32>, b: Vec<i32>) {
 
     #[test]
     fn test_dedup_unique() {
-        let mut v0 = vec![box 1, box 1, box 2, box 3];
+        let mut v0: Vec<Box<_>> = vec![box 1, box 1, box 2, box 3];
         v0.dedup();
-        let mut v1 = vec![box 1, box 2, box 2, box 3];
+        let mut v1: Vec<Box<_>> = vec![box 1, box 2, box 2, box 3];
         v1.dedup();
-        let mut v2 = vec![box 1, box 2, box 3, box 3];
+        let mut v2: Vec<Box<_>> = vec![box 1, box 2, box 3, box 3];
         v2.dedup();
         /*
          * If the boxed pointers were leaked or otherwise misused, valgrind
@@ -1877,11 +1878,11 @@ fn test_dedup_unique() {
 
     #[test]
     fn test_dedup_shared() {
-        let mut v0 = vec![box 1, box 1, box 2, box 3];
+        let mut v0: Vec<Box<_>> = vec![box 1, box 1, box 2, box 3];
         v0.dedup();
-        let mut v1 = vec![box 1, box 2, box 2, box 3];
+        let mut v1: Vec<Box<_>> = vec![box 1, box 2, box 2, box 3];
         v1.dedup();
-        let mut v2 = vec![box 1, box 2, box 3, box 3];
+        let mut v2: Vec<Box<_>> = vec![box 1, box 2, box 3, box 3];
         v2.dedup();
         /*
          * If the pointers were leaked or otherwise misused, valgrind and/or
@@ -2175,8 +2176,8 @@ fn test_concat() {
     fn test_connect() {
         let v: [Vec<i32>; 0] = [];
         assert_eq!(v.connect(&0), []);
-        assert_eq!([vec![1i], vec![2, 3]].connect(&0), [1, 0, 2, 3]);
-        assert_eq!([vec![1i], vec![2], vec![3]].connect(&0), [1, 0, 2, 0, 3]);
+        assert_eq!([vec![1], vec![2, 3]].connect(&0), [1, 0, 2, 3]);
+        assert_eq!([vec![1], vec![2], vec![3]].connect(&0), [1, 0, 2, 0, 3]);
 
         let v: [&[_]; 2] = [&[1], &[2, 3]];
         assert_eq!(v.connect(&0), [1, 0, 2, 3]);
@@ -2254,8 +2255,9 @@ fn test_slice_2() {
     #[test]
     #[should_fail]
     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 v: [(Box<_>, Rc<_>); 4] =
+            [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
+             (box 0, Rc::new(0)), (box 0, Rc::new(0))];
         let mut i = 0;
         for _ in v.permutations() {
             if i == 2 {
@@ -2849,7 +2851,7 @@ fn test_mut_last() {
 
     #[test]
     fn test_to_vec() {
-        let xs = box [1, 2, 3];
+        let xs: Box<_> = box [1, 2, 3];
         let ys = xs.to_vec();
         assert_eq!(ys, [1, 2, 3]);
     }
index a4d39974c70135338f8c5881c978caef8dc9a5e8..2e947ea24602aafdedb64848032d87ab8b53dc6a 100644 (file)
@@ -2130,8 +2130,8 @@ fn test_clone() {
     #[test]
     fn test_clone_from() {
         let mut v = vec!();
-        let three = vec!(box 1, box 2, box 3);
-        let two = vec!(box 4, box 5);
+        let three: Vec<Box<_>> = vec!(box 1, box 2, box 3);
+        let two: Vec<Box<_>> = vec!(box 4, box 5);
         // zero, long
         v.clone_from(&three);
         assert_eq!(v, three);
index 5a0aa750bf5670dc1a569ca9f9c5e9715c17c884..515de74e340ac9d5fd6f7b3c78d784a1e05d82a2 100644 (file)
@@ -1205,7 +1205,7 @@ fn test_mut_rev_iterator() {
 
     #[test]
     fn test_move_iter() {
-        let mut m = VecMap::new();
+        let mut m: VecMap<Box<_>> = VecMap::new();
         m.insert(1, box 2);
         let mut called = false;
         for (k, v) in m {
index 9495bc2e19d6505638f763282adaa2752181c997..767828408be868000c79d424d14f4b4260968dcd 100644 (file)
@@ -1570,24 +1570,13 @@ pub struct Map<I, F> {
     f: F,
 }
 
-impl<I: Iterator, F, B> Map<I, F> where F: FnMut(I::Item) -> B {
-    #[inline]
-    fn do_map(&mut self, elt: Option<I::Item>) -> Option<B> {
-        match elt {
-            Some(a) => Some((self.f)(a)),
-            _ => None
-        }
-    }
-}
-
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
     type Item = B;
 
     #[inline]
     fn next(&mut self) -> Option<B> {
-        let next = self.iter.next();
-        self.do_map(next)
+        self.iter.next().map(|a| (self.f)(a))
     }
 
     #[inline]
@@ -1602,8 +1591,7 @@ impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
 {
     #[inline]
     fn next_back(&mut self) -> Option<B> {
-        let next = self.iter.next_back();
-        self.do_map(next)
+        self.iter.next_back().map(|a| (self.f)(a))
     }
 }
 
@@ -1618,8 +1606,7 @@ fn indexable(&self) -> usize {
 
     #[inline]
     fn idx(&mut self, index: usize) -> Option<B> {
-        let elt = self.iter.idx(index);
-        self.do_map(elt)
+        self.iter.idx(index).map(|a| (self.f)(a))
     }
 }
 
index 8b5e46f85fa6ac181b1e7968adaa364214c407ad..39f5d237a2b7364501ab7a52bbccc5ca2b8df2c4 100644 (file)
@@ -68,7 +68,7 @@ fn any_downcast_ref() {
 #[test]
 fn any_downcast_mut() {
     let mut a = 5_usize;
-    let mut b = box 7_usize;
+    let mut b: Box<_> = box 7_usize;
 
     let a_r = &mut a as &mut Any;
     let tmp: &mut uint = &mut *b;
index 9b6af182f729c291751d2db896acfbc4e5c74200..3433813e7b5e6dc821205fe656d5b0437df1a3e1 100644 (file)
@@ -64,7 +64,8 @@ fn hash<T: Hash>(t: &T) -> u64 {
     //assert_eq!(hasher.hash(& s), 97 + 0xFF);
     let cs: &[u8] = &[1u8, 2u8, 3u8];
     assert_eq!(hash(& cs), 9);
-    let cs: Box<[u8]> = box [1u8, 2u8, 3u8];
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let cs: Box<[u8]> = Box::new([1u8, 2u8, 3u8]);
     assert_eq!(hash(& cs), 9);
 
     // FIXME (#18248) Add tests for hashing Rc<str> and Rc<[T]>
@@ -85,7 +86,7 @@ struct CustomHasher { output: u64 }
 
 impl Hasher for CustomHasher {
     fn finish(&self) -> u64 { self.output }
-    fn write(&mut self, data: &[u8]) { panic!() }
+    fn write(&mut self, _: &[u8]) { panic!() }
     fn write_u64(&mut self, data: u64) { self.output = data; }
 }
 
index abf88583c03ffac03f1a6a40a0c9c51a86e20060..b1b10b582e55c5437ba1758ff65d4bbc853e121a 100644 (file)
@@ -404,7 +404,8 @@ fn test_collect() {
 
 #[test]
 fn test_all() {
-    let v: Box<[int]> = box [1, 2, 3, 4, 5];
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let v: Box<[int]> = Box::new([1, 2, 3, 4, 5]);
     assert!(v.iter().all(|&x| x < 10));
     assert!(!v.iter().all(|&x| x % 2 == 0));
     assert!(!v.iter().all(|&x| x > 100));
@@ -413,7 +414,8 @@ fn test_all() {
 
 #[test]
 fn test_any() {
-    let v: Box<[int]> = box [1, 2, 3, 4, 5];
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let v: Box<[int]> = Box::new([1, 2, 3, 4, 5]);
     assert!(v.iter().any(|&x| x < 10));
     assert!(v.iter().any(|&x| x % 2 == 0));
     assert!(!v.iter().any(|&x| x > 100));
@@ -581,8 +583,9 @@ fn test_rposition() {
 #[test]
 #[should_fail]
 fn test_rposition_panic() {
-    let v = [(box 0, box 0), (box 0, box 0),
-             (box 0, box 0), (box 0, box 0)];
+    let v: [(Box<_>, Box<_>); 4] =
+        [(box 0, box 0), (box 0, box 0),
+         (box 0, box 0), (box 0, box 0)];
     let mut i = 0;
     v.iter().rposition(|_elt| {
         if i == 2 {
index 860bd40e21eeed7dcda76a520887bd87e4e14818..59116f23d44b64ab7dbe50ba8e69702d4c557e41 100644 (file)
@@ -16,7 +16,7 @@
 #[test]
 fn test_get_ptr() {
     unsafe {
-        let x = box 0;
+        let x: Box<_> = box 0;
         let addr_x: *const int = mem::transmute(&*x);
         let opt = Some(x);
         let y = opt.unwrap();
index 019f935911f7a78315f834be60b88c8928835c13..a89d3380707051cbdf8613a9484464f82699d133 100644 (file)
@@ -188,15 +188,13 @@ fn trim_ws() {
 
 mod pattern {
     use std::str::Pattern;
-    use std::str::{Searcher, ReverseSearcher, DoubleEndedSearcher};
+    use std::str::{Searcher, ReverseSearcher};
     use std::str::SearchStep::{self, Match, Reject, Done};
 
     macro_rules! make_test {
         ($name:ident, $p:expr, $h:expr, [$($e:expr,)*]) => {
             mod $name {
-                use std::str::Pattern;
-                use std::str::{Searcher, ReverseSearcher, DoubleEndedSearcher};
-                use std::str::SearchStep::{self, Match, Reject, Done};
+                use std::str::SearchStep::{Match, Reject};
                 use super::{cmp_search_to_vec};
                 #[test]
                 fn fwd() {
index 6240b0e6afdd50861f59ced7b8a752cd8dd626b9..6b9d6cb0000f2fa5e296af72026caab82c27ddb5 100644 (file)
@@ -93,6 +93,7 @@
 #![feature(int_uint)]
 #![feature(staged_api)]
 #![feature(str_words)]
+#![feature(core)]
 #![cfg_attr(test, feature(rustc_private))]
 
 #[cfg(test)] #[macro_use] extern crate log;
index c8a757079c348577c00b4d8ad20624ddf00b7251..e2a5276cc78abf8e8782dd8c7e597d58541b9b88 100644 (file)
@@ -214,7 +214,6 @@ fn rand<R: Rng>(rng: &mut R) -> Option<T> {
 
 #[cfg(test)]
 mod tests {
-    use std::prelude::v1::*;
     use std::rand::{Rng, thread_rng, Open01, Closed01};
 
     struct ConstantRng(u64);
index 4ef3c5bc20634f3ccb7f8a162a30cc900eb8a1f5..fc0a9d29ed6f2b7fcf8b7e132a7fe82c46b467d6 100644 (file)
@@ -140,32 +140,32 @@ mod tests {
     fn test_seekable_mem_writer() {
         let mut writer = SeekableMemWriter::new();
         assert_eq!(writer.tell(), Ok(0));
-        writer.write(&[0]).unwrap();
+        writer.write_all(&[0]).unwrap();
         assert_eq!(writer.tell(), Ok(1));
-        writer.write(&[1, 2, 3]).unwrap();
-        writer.write(&[4, 5, 6, 7]).unwrap();
+        writer.write_all(&[1, 2, 3]).unwrap();
+        writer.write_all(&[4, 5, 6, 7]).unwrap();
         assert_eq!(writer.tell(), Ok(8));
         let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
         assert_eq!(writer.get_ref(), b);
 
         writer.seek(0, old_io::SeekSet).unwrap();
         assert_eq!(writer.tell(), Ok(0));
-        writer.write(&[3, 4]).unwrap();
+        writer.write_all(&[3, 4]).unwrap();
         let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7];
         assert_eq!(writer.get_ref(), b);
 
         writer.seek(1, old_io::SeekCur).unwrap();
-        writer.write(&[0, 1]).unwrap();
+        writer.write_all(&[0, 1]).unwrap();
         let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
         assert_eq!(writer.get_ref(), b);
 
         writer.seek(-1, old_io::SeekEnd).unwrap();
-        writer.write(&[1, 2]).unwrap();
+        writer.write_all(&[1, 2]).unwrap();
         let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
         assert_eq!(writer.get_ref(), b);
 
         writer.seek(1, old_io::SeekEnd).unwrap();
-        writer.write(&[1]).unwrap();
+        writer.write_all(&[1]).unwrap();
         let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1];
         assert_eq!(writer.get_ref(), b);
     }
@@ -174,7 +174,7 @@ fn test_seekable_mem_writer() {
     fn seek_past_end() {
         let mut r = SeekableMemWriter::new();
         r.seek(10, old_io::SeekSet).unwrap();
-        assert!(r.write(&[3]).is_ok());
+        assert!(r.write_all(&[3]).is_ok());
     }
 
     #[test]
@@ -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).unwrap();
+                wr.write_all(&src).unwrap();
             }
 
             let v = wr.unwrap();
index aa51320ee7f43ee0c861beeedfb56c76f1b0f911..2d542eafbe1ae3a2dc27c7b3ada24e462772ba10 100644 (file)
@@ -39,6 +39,9 @@
 #![feature(staged_api)]
 #![feature(std_misc)]
 #![feature(os)]
+#![feature(path)]
+#![feature(fs)]
+#![feature(io)]
 #![cfg_attr(test, feature(test))]
 
 extern crate arena;
index a58ef53de9a7135591de41d12b98c66777411a62..b3c1d6cd15fee26f47e326c7642a2f32e12f9715 100644 (file)
@@ -252,3 +252,6 @@ pub struct LinkMeta {
 pub const tag_macro_def_body: uint = 0x9f;
 
 pub const tag_paren_sugar: uint = 0xa0;
+
+pub const tag_codemap: uint = 0xa1;
+pub const tag_codemap_filemap: uint = 0xa2;
index 46155925b3c72dab922b635ad1b00fd6a67d6f31..a19ccceb0571538ce22375c6d33b219853816e75 100644 (file)
 use metadata::loader;
 use metadata::loader::CratePaths;
 
+use std::path::{Path, PathBuf};
 use std::rc::Rc;
 use syntax::ast;
 use syntax::abi;
 use syntax::attr;
 use syntax::attr::AttrMetaMethods;
-use syntax::codemap::{Span, mk_sp};
+use syntax::codemap::{self, Span, mk_sp, Pos};
 use syntax::parse;
 use syntax::parse::token::InternedString;
 use syntax::parse::token;
@@ -126,7 +127,7 @@ fn register_native_lib(sess: &Session,
 // Extra info about a crate loaded for plugins or exported macros.
 struct ExtensionCrate {
     metadata: PMDSource,
-    dylib: Option<Path>,
+    dylib: Option<PathBuf>,
     target_only: bool,
 }
 
@@ -373,15 +374,17 @@ fn register_crate(&mut self,
         // Maintain a reference to the top most crate.
         let root = if root.is_some() { root } else { &crate_paths };
 
-        let cnum_map = self.resolve_crate_deps(root, lib.metadata.as_slice(), span);
+        let loader::Library { dylib, rlib, metadata } = lib;
 
-        let loader::Library{ dylib, rlib, metadata } = lib;
+        let cnum_map = self.resolve_crate_deps(root, metadata.as_slice(), span);
+        let codemap_import_info = import_codemap(self.sess.codemap(), &metadata);
 
         let cmeta = Rc::new( cstore::crate_metadata {
             name: name.to_string(),
             data: metadata,
             cnum_map: cnum_map,
             cnum: cnum,
+            codemap_import_info: codemap_import_info,
             span: span,
         });
 
@@ -549,7 +552,8 @@ pub fn read_exported_macros(&mut self, krate: &ast::Item) -> Vec<ast::MacroDef>
     }
 
     /// Look for a plugin registrar. Returns library path and symbol name.
-    pub fn find_plugin_registrar(&mut self, span: Span, name: &str) -> Option<(Path, String)> {
+    pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
+                                 -> Option<(PathBuf, String)> {
         let ekrate = self.read_extension_crate(span, &CrateInfo {
              name: name.to_string(),
              ident: name.to_string(),
@@ -572,7 +576,7 @@ pub fn find_plugin_registrar(&mut self, span: Span, name: &str) -> Option<(Path,
             .map(|id| decoder::get_symbol(ekrate.metadata.as_slice(), id));
 
         match (ekrate.dylib.as_ref(), registrar) {
-            (Some(dylib), Some(reg)) => Some((dylib.clone(), reg)),
+            (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)),
             (None, Some(_)) => {
                 let message = format!("plugin `{}` only found in rlib format, \
                                        but must be available in dylib format",
@@ -586,3 +590,131 @@ pub fn find_plugin_registrar(&mut self, span: Span, name: &str) -> Option<(Path,
         }
     }
 }
+
+/// Imports the codemap from an external crate into the codemap of the crate
+/// currently being compiled (the "local crate").
+///
+/// The import algorithm works analogous to how AST items are inlined from an
+/// external crate's metadata:
+/// For every FileMap in the external codemap an 'inline' copy is created in the
+/// local codemap. The correspondence relation between external and local
+/// FileMaps is recorded in the `ImportedFileMap` objects returned from this
+/// function. When an item from an external crate is later inlined into this
+/// crate, this correspondence information is used to translate the span
+/// information of the inlined item so that it refers the correct positions in
+/// the local codemap (see `astencode::DecodeContext::tr_span()`).
+///
+/// The import algorithm in the function below will reuse FileMaps already
+/// existing in the local codemap. For example, even if the FileMap of some
+/// source file of libstd gets imported many times, there will only ever be
+/// one FileMap object for the corresponding file in the local codemap.
+///
+/// Note that imported FileMaps do not actually contain the source code of the
+/// file they represent, just information about length, line breaks, and
+/// multibyte characters. This information is enough to generate valid debuginfo
+/// for items inlined from other crates.
+fn import_codemap(local_codemap: &codemap::CodeMap,
+                  metadata: &MetadataBlob)
+                  -> Vec<cstore::ImportedFileMap> {
+    let external_codemap = decoder::get_imported_filemaps(metadata.as_slice());
+
+    let imported_filemaps = external_codemap.into_iter().map(|filemap_to_import| {
+        // Try to find an existing FileMap that can be reused for the filemap to
+        // be imported. A FileMap is reusable if it is exactly the same, just
+        // positioned at a different offset within the codemap.
+        let reusable_filemap = {
+            local_codemap.files
+                         .borrow()
+                         .iter()
+                         .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
+                         .map(|rc| rc.clone())
+        };
+
+        match reusable_filemap {
+            Some(fm) => {
+                cstore::ImportedFileMap {
+                    original_start_pos: filemap_to_import.start_pos,
+                    original_end_pos: filemap_to_import.end_pos,
+                    translated_filemap: fm
+                }
+            }
+            None => {
+                // We can't reuse an existing FileMap, so allocate a new one
+                // containing the information we need.
+                let codemap::FileMap {
+                    name,
+                    start_pos,
+                    end_pos,
+                    lines,
+                    multibyte_chars,
+                    ..
+                } = filemap_to_import;
+
+                let source_length = (end_pos - start_pos).to_usize();
+
+                // Translate line-start positions and multibyte character
+                // position into frame of reference local to file.
+                // `CodeMap::new_imported_filemap()` will then translate those
+                // coordinates to their new global frame of reference when the
+                // offset of the FileMap is known.
+                let lines = lines.into_inner().map_in_place(|pos| pos - start_pos);
+                let multibyte_chars = multibyte_chars
+                    .into_inner()
+                    .map_in_place(|mbc|
+                        codemap::MultiByteChar {
+                            pos: mbc.pos + start_pos,
+                            bytes: mbc.bytes
+                        });
+
+                let local_version = local_codemap.new_imported_filemap(name,
+                                                                       source_length,
+                                                                       lines,
+                                                                       multibyte_chars);
+                cstore::ImportedFileMap {
+                    original_start_pos: start_pos,
+                    original_end_pos: end_pos,
+                    translated_filemap: local_version
+                }
+            }
+        }
+    }).collect();
+
+    return imported_filemaps;
+
+    fn are_equal_modulo_startpos(fm1: &codemap::FileMap,
+                                 fm2: &codemap::FileMap)
+                                 -> bool {
+        if fm1.name != fm2.name {
+            return false;
+        }
+
+        let lines1 = fm1.lines.borrow();
+        let lines2 = fm2.lines.borrow();
+
+        if lines1.len() != lines2.len() {
+            return false;
+        }
+
+        for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
+            if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
+                return false;
+            }
+        }
+
+        let multibytes1 = fm1.multibyte_chars.borrow();
+        let multibytes2 = fm2.multibyte_chars.borrow();
+
+        if multibytes1.len() != multibytes2.len() {
+            return false;
+        }
+
+        for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
+            if (mb1.bytes != mb2.bytes) ||
+               ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {
+                return false;
+            }
+        }
+
+        true
+    }
+}
index a3f7d57da67486b39a976a8289743612960ef5b4..47ec31c0f1ab7d0c26b7d366282cf54d368121b9 100644 (file)
 
 use std::cell::RefCell;
 use std::rc::Rc;
+use std::path::PathBuf;
 use flate::Bytes;
 use syntax::ast;
-use syntax::codemap::Span;
+use syntax::codemap;
 use syntax::parse::token::IdentInterner;
 
 // A map from external crate numbers (as decoded from some crate file) to
@@ -41,12 +42,24 @@ pub enum MetadataBlob {
     MetadataArchive(loader::ArchiveMetadata),
 }
 
+/// Holds information about a codemap::FileMap imported from another crate.
+/// See creader::import_codemap() for more information.
+pub struct ImportedFileMap {
+    /// This FileMap's byte-offset within the codemap of its original crate
+    pub original_start_pos: codemap::BytePos,
+    /// The end of this FileMap within the codemap of its original crate
+    pub original_end_pos: codemap::BytePos,
+    /// The imported FileMap's representation within the local codemap
+    pub translated_filemap: Rc<codemap::FileMap>
+}
+
 pub struct crate_metadata {
     pub name: String,
     pub data: MetadataBlob,
     pub cnum_map: cnum_map,
     pub cnum: ast::CrateNum,
-    pub span: Span,
+    pub codemap_import_info: Vec<ImportedFileMap>,
+    pub span: codemap::Span,
 }
 
 #[derive(Copy, Debug, PartialEq, Clone)]
@@ -66,8 +79,8 @@ pub enum NativeLibraryKind {
 // must be non-None.
 #[derive(PartialEq, Clone)]
 pub struct CrateSource {
-    pub dylib: Option<(Path, PathKind)>,
-    pub rlib: Option<(Path, PathKind)>,
+    pub dylib: Option<(PathBuf, PathKind)>,
+    pub rlib: Option<(PathBuf, PathKind)>,
     pub cnum: ast::CrateNum,
 }
 
@@ -160,7 +173,7 @@ pub fn reset(&self) {
     // topological sort of all crates putting the leaves at the right-most
     // positions.
     pub fn get_used_crates(&self, prefer: LinkagePreference)
-                           -> Vec<(ast::CrateNum, Option<Path>)> {
+                           -> Vec<(ast::CrateNum, Option<PathBuf>)> {
         let mut ordering = Vec::new();
         fn visit(cstore: &CStore, cnum: ast::CrateNum,
                  ordering: &mut Vec<ast::CrateNum>) {
index e32fcaec04734b49730de759492641242d8449fc..90046398c59f4354bc0fb127d1a3b4319d0642a4 100644 (file)
@@ -34,9 +34,9 @@
 
 use std::collections::HashMap;
 use std::hash::{self, Hash, SipHasher};
-use std::num::FromPrimitive;
-use std::num::Int;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
+use std::num::{FromPrimitive, Int};
 use std::rc::Rc;
 use std::slice::bytes;
 use std::str;
@@ -1191,7 +1191,7 @@ fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
 }
 
 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
-                         out: &mut old_io::Writer) -> old_io::IoResult<()> {
+                         out: &mut io::Write) -> io::Result<()> {
     try!(write!(out, "=Crate Attributes ({})=\n", *hash));
 
     let r = get_attributes(md);
@@ -1236,7 +1236,7 @@ fn docstr(doc: rbml::Doc, tag_: uint) -> String {
     return deps;
 }
 
-fn list_crate_deps(data: &[u8], out: &mut old_io::Writer) -> old_io::IoResult<()> {
+fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
     try!(write!(out, "=External Dependencies=\n"));
     for dep in &get_crate_deps(data) {
         try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
@@ -1275,7 +1275,7 @@ pub fn get_crate_name(data: &[u8]) -> String {
     maybe_get_crate_name(data).expect("no crate name in crate")
 }
 
-pub fn list_crate_metadata(bytes: &[u8], out: &mut old_io::Writer) -> old_io::IoResult<()> {
+pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
     let hash = get_crate_hash(bytes);
     let md = rbml::Doc::new(bytes);
     try!(list_crate_attributes(md, &hash, out));
@@ -1561,7 +1561,6 @@ pub fn is_associated_type(cdata: Cmd, id: ast::NodeId) -> bool {
     }
 }
 
-
 pub fn is_default_trait<'tcx>(cdata: Cmd, id: ast::NodeId) -> bool {
     let item_doc = lookup_item(id, cdata.data());
     match item_family(item_doc) {
@@ -1569,3 +1568,19 @@ pub fn is_default_trait<'tcx>(cdata: Cmd, id: ast::NodeId) -> bool {
         _ => false
     }
 }
+
+pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<codemap::FileMap> {
+    let crate_doc = rbml::Doc::new(metadata);
+    let cm_doc = reader::get_doc(crate_doc, tag_codemap);
+
+    let mut filemaps = vec![];
+
+    reader::tagged_docs(cm_doc, tag_codemap_filemap, |filemap_doc| {
+        let mut decoder = reader::Decoder::new(filemap_doc);
+        let filemap: codemap::FileMap = Decodable::decode(&mut decoder).unwrap();
+        filemaps.push(filemap);
+        true
+    });
+
+    return filemaps;
+}
index 8152a2bf16dd1f773a56d949ef14dfd587dfcecd..b9e0e452c8374c34a59e0fb05d4e29a479e1361b 100644 (file)
@@ -1751,6 +1751,28 @@ fn encode_plugin_registrar_fn(ecx: &EncodeContext, rbml_w: &mut Encoder) {
     }
 }
 
+fn encode_codemap(ecx: &EncodeContext, rbml_w: &mut Encoder) {
+    rbml_w.start_tag(tag_codemap);
+    let codemap = ecx.tcx.sess.codemap();
+
+    for filemap in &codemap.files.borrow()[..] {
+
+        if filemap.lines.borrow().len() == 0 || filemap.is_imported() {
+            // No need to export empty filemaps, as they can't contain spans
+            // that need translation.
+            // Also no need to re-export imported filemaps, as any downstream
+            // crate will import them from their original source.
+            continue;
+        }
+
+        rbml_w.start_tag(tag_codemap_filemap);
+        filemap.encode(rbml_w);
+        rbml_w.end_tag();
+    }
+
+    rbml_w.end_tag();
+}
+
 /// Serialize the text of the exported macros
 fn encode_macro_defs(rbml_w: &mut Encoder,
                      krate: &ast::Crate) {
@@ -1968,6 +1990,7 @@ struct Stats {
         lang_item_bytes: u64,
         native_lib_bytes: u64,
         plugin_registrar_fn_bytes: u64,
+        codemap_bytes: u64,
         macro_defs_bytes: u64,
         impl_bytes: u64,
         misc_bytes: u64,
@@ -1982,6 +2005,7 @@ struct Stats {
         lang_item_bytes: 0,
         native_lib_bytes: 0,
         plugin_registrar_fn_bytes: 0,
+        codemap_bytes: 0,
         macro_defs_bytes: 0,
         impl_bytes: 0,
         misc_bytes: 0,
@@ -2047,6 +2071,11 @@ struct Stats {
     encode_plugin_registrar_fn(&ecx, &mut rbml_w);
     stats.plugin_registrar_fn_bytes = rbml_w.writer.tell().unwrap() - i;
 
+    // Encode codemap
+    i = rbml_w.writer.tell().unwrap();
+    encode_codemap(&ecx, &mut rbml_w);
+    stats.codemap_bytes = rbml_w.writer.tell().unwrap() - i;
+
     // Encode macro definitions
     i = rbml_w.writer.tell().unwrap();
     encode_macro_defs(&mut rbml_w, krate);
@@ -2091,6 +2120,7 @@ struct Stats {
         println!("       lang item bytes: {}", stats.lang_item_bytes);
         println!("          native bytes: {}", stats.native_lib_bytes);
         println!("plugin registrar bytes: {}", stats.plugin_registrar_fn_bytes);
+        println!("         codemap bytes: {}", stats.codemap_bytes);
         println!("       macro def bytes: {}", stats.macro_defs_bytes);
         println!("            impl bytes: {}", stats.impl_bytes);
         println!("            misc bytes: {}", stats.misc_bytes);
index d1091b1d3f76ac34963bd6a2902bb6e9db839389..22a4a6fc978dc055a9a79ae360b03c0d51feca7e 100644 (file)
@@ -14,9 +14,9 @@
 
 use std::collections::HashSet;
 use std::env;
-use std::os;
-use std::old_io::fs::PathExtensions;
-use std::old_io::fs;
+use std::fs;
+use std::io::prelude::*;
+use std::path::{Path, PathBuf};
 
 use util::fs as myfs;
 use session::search_paths::{SearchPaths, PathKind};
@@ -50,20 +50,20 @@ pub fn for_each_lib_search_path<F>(&self, mut f: F) where
                 FileMatches => found = true,
                 FileDoesntMatch => ()
             }
-            visited_dirs.insert(path.as_vec().to_vec());
+            visited_dirs.insert(path.to_path_buf());
         }
 
         debug!("filesearch: searching lib path");
         let tlib_path = make_target_lib_path(self.sysroot,
                                              self.triple);
-        if !visited_dirs.contains(tlib_path.as_vec()) {
+        if !visited_dirs.contains(&tlib_path) {
             match f(&tlib_path, PathKind::All) {
                 FileMatches => found = true,
                 FileDoesntMatch => ()
             }
         }
 
-        visited_dirs.insert(tlib_path.as_vec().to_vec());
+        visited_dirs.insert(tlib_path);
         // Try RUST_PATH
         if !found {
             let rustpath = rust_path();
@@ -71,10 +71,10 @@ pub fn for_each_lib_search_path<F>(&self, mut f: F) where
                 let tlib_path = make_rustpkg_lib_path(
                     self.sysroot, path, self.triple);
                 debug!("is {} in visited_dirs? {}", tlib_path.display(),
-                        visited_dirs.contains(&tlib_path.as_vec().to_vec()));
+                        visited_dirs.contains(&tlib_path));
 
-                if !visited_dirs.contains(tlib_path.as_vec()) {
-                    visited_dirs.insert(tlib_path.as_vec().to_vec());
+                if !visited_dirs.contains(&tlib_path) {
+                    visited_dirs.insert(tlib_path.clone());
                     // Don't keep searching the RUST_PATH if one match turns up --
                     // if we did, we'd get a "multiple matching crates" error
                     match f(&tlib_path, PathKind::All) {
@@ -88,7 +88,7 @@ pub fn for_each_lib_search_path<F>(&self, mut f: F) where
         }
     }
 
-    pub fn get_lib_path(&self) -> Path {
+    pub fn get_lib_path(&self) -> PathBuf {
         make_target_lib_path(self.sysroot, self.triple)
     }
 
@@ -97,11 +97,13 @@ pub fn search<F>(&self, mut pick: F)
     {
         self.for_each_lib_search_path(|lib_search_path, kind| {
             debug!("searching {}", lib_search_path.display());
-            match fs::readdir(lib_search_path) {
+            match fs::read_dir(lib_search_path) {
                 Ok(files) => {
+                    let files = files.filter_map(|p| p.ok().map(|s| s.path()))
+                                     .collect::<Vec<_>>();
                     let mut rslt = FileDoesntMatch;
-                    fn is_rlib(p: & &Path) -> bool {
-                        p.extension_str() == Some("rlib")
+                    fn is_rlib(p: &Path) -> bool {
+                        p.extension().and_then(|s| s.to_str()) == Some("rlib")
                     }
                     // Reading metadata out of rlibs is faster, and if we find both
                     // an rlib and a dylib we only read one of the files of
@@ -143,59 +145,60 @@ pub fn new(sysroot: &'a Path,
     }
 
     // Returns a list of directories where target-specific dylibs might be located.
-    pub fn get_dylib_search_paths(&self) -> Vec<Path> {
+    pub fn get_dylib_search_paths(&self) -> Vec<PathBuf> {
         let mut paths = Vec::new();
         self.for_each_lib_search_path(|lib_search_path, _| {
-            paths.push(lib_search_path.clone());
+            paths.push(lib_search_path.to_path_buf());
             FileDoesntMatch
         });
         paths
     }
 
     // Returns a list of directories where target-specific tool binaries are located.
-    pub fn get_tools_search_paths(&self) -> Vec<Path> {
-        let mut p = Path::new(self.sysroot);
-        p.push(find_libdir(self.sysroot));
-        p.push(rustlibdir());
-        p.push(self.triple);
+    pub fn get_tools_search_paths(&self) -> Vec<PathBuf> {
+        let mut p = PathBuf::new(self.sysroot);
+        p.push(&find_libdir(self.sysroot));
+        p.push(&rustlibdir());
+        p.push(&self.triple);
         p.push("bin");
         vec![p]
     }
 }
 
-pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
-    let mut p = Path::new(find_libdir(sysroot));
+pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
+    let mut p = PathBuf::new(&find_libdir(sysroot));
     assert!(p.is_relative());
-    p.push(rustlibdir());
+    p.push(&rustlibdir());
     p.push(target_triple);
     p.push("lib");
     p
 }
 
 fn make_target_lib_path(sysroot: &Path,
-                        target_triple: &str) -> Path {
+                        target_triple: &str) -> PathBuf {
     sysroot.join(&relative_target_lib_path(sysroot, target_triple))
 }
 
 fn make_rustpkg_lib_path(sysroot: &Path,
                          dir: &Path,
-                         triple: &str) -> Path {
-    let mut p = dir.join(find_libdir(sysroot));
+                         triple: &str) -> PathBuf {
+    let mut p = dir.join(&find_libdir(sysroot));
     p.push(triple);
     p
 }
 
-pub fn get_or_default_sysroot() -> Path {
+pub fn get_or_default_sysroot() -> PathBuf {
     // Follow symlinks.  If the resolved path is relative, make it absolute.
-    fn canonicalize(path: Option<Path>) -> Option<Path> {
-        path.and_then(|path|
+    fn canonicalize(path: Option<PathBuf>) -> Option<PathBuf> {
+        path.and_then(|path| {
             match myfs::realpath(&path) {
                 Ok(canon) => Some(canon),
                 Err(e) => panic!("failed to get realpath: {}", e),
-            })
+            }
+        })
     }
 
-    match canonicalize(os::self_exe_name()) {
+    match canonicalize(env::current_exe().ok()) {
         Some(mut p) => { p.pop(); p.pop(); p }
         None => panic!("can't determine value for sysroot")
     }
@@ -216,16 +219,16 @@ pub fn get_rust_path() -> Option<String> {
 /// $HOME/.rust
 /// DIR/.rust for any DIR that's the current working directory
 /// or an ancestor of it
-pub fn rust_path() -> Vec<Path> {
-    let mut env_rust_path: Vec<Path> = match get_rust_path() {
+pub fn rust_path() -> Vec<PathBuf> {
+    let mut env_rust_path: Vec<PathBuf> = match get_rust_path() {
         Some(env_path) => {
             let env_path_components =
                 env_path.split(PATH_ENTRY_SEPARATOR);
-            env_path_components.map(|s| Path::new(s)).collect()
+            env_path_components.map(|s| PathBuf::new(s)).collect()
         }
         None => Vec::new()
     };
-    let mut cwd = os::getcwd().unwrap();
+    let cwd = env::current_dir().unwrap();
     // now add in default entries
     let cwd_dot_rust = cwd.join(".rust");
     if !env_rust_path.contains(&cwd_dot_rust) {
@@ -234,17 +237,15 @@ pub fn rust_path() -> Vec<Path> {
     if !env_rust_path.contains(&cwd) {
         env_rust_path.push(cwd.clone());
     }
-    loop {
-        if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
-            break
-        }
-        cwd.set_filename(".rust");
-        if !env_rust_path.contains(&cwd) && cwd.exists() {
-            env_rust_path.push(cwd.clone());
+    let mut cur = &*cwd;
+    while let Some(parent) = cur.parent() {
+        let candidate = parent.join(".rust");
+        if !env_rust_path.contains(&candidate) && candidate.exists() {
+            env_rust_path.push(candidate.clone());
         }
-        cwd.pop();
+        cur = parent;
     }
-    if let Some(h) = os::homedir() {
+    if let Some(h) = env::home_dir() {
         let p = h.join(".rust");
         if !env_rust_path.contains(&p) && p.exists() {
             env_rust_path.push(p);
@@ -267,7 +268,7 @@ fn find_libdir(sysroot: &Path) -> String {
 
     match option_env!("CFG_LIBDIR_RELATIVE") {
         Some(libdir) if libdir != "lib" => return libdir.to_string(),
-        _ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
+        _ => if sysroot.join(&primary_libdir_name()).join(&rustlibdir()).exists() {
             return primary_libdir_name();
         } else {
             return secondary_libdir_name();
index 07082d818769c44ba1d2cf25e5528b396fe1f346..d83470354acb90c24cf5d00fc78259a3bc5c9a1c 100644 (file)
 use syntax::codemap::Span;
 use syntax::diagnostic::SpanHandler;
 use util::fs;
+use util::common;
 use rustc_back::target::Target;
 
-use std::ffi::CString;
 use std::cmp;
 use std::collections::HashMap;
-use std::old_io::fs::PathExtensions;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
+use std::path::{Path, PathBuf};
 use std::ptr;
 use std::slice;
 use std::time::Duration;
 use flate;
 
 pub struct CrateMismatch {
-    path: Path,
+    path: PathBuf,
     got: String,
 }
 
@@ -262,8 +263,8 @@ pub struct Context<'a> {
 }
 
 pub struct Library {
-    pub dylib: Option<(Path, PathKind)>,
-    pub rlib: Option<(Path, PathKind)>,
+    pub dylib: Option<(PathBuf, PathKind)>,
+    pub rlib: Option<(PathBuf, PathKind)>,
     pub metadata: MetadataBlob,
 }
 
@@ -275,12 +276,12 @@ pub struct ArchiveMetadata {
 
 pub struct CratePaths {
     pub ident: String,
-    pub dylib: Option<Path>,
-    pub rlib: Option<Path>
+    pub dylib: Option<PathBuf>,
+    pub rlib: Option<PathBuf>
 }
 
 impl CratePaths {
-    fn paths(&self) -> Vec<Path> {
+    fn paths(&self) -> Vec<PathBuf> {
         match (&self.dylib, &self.rlib) {
             (&None,    &None)              => vec!(),
             (&Some(ref p), &None) |
@@ -400,7 +401,7 @@ fn find_library_crate(&mut self) -> Option<Library> {
         //
         // The goal of this step is to look at as little metadata as possible.
         self.filesearch.search(|path, kind| {
-            let file = match path.filename_str() {
+            let file = match path.file_name().and_then(|s| s.to_str()) {
                 None => return FileDoesntMatch,
                 Some(file) => file,
             };
@@ -416,7 +417,7 @@ fn find_library_crate(&mut self) -> Option<Library> {
                 if file.starts_with(&staticlib_prefix[..]) &&
                    file.ends_with(".a") {
                     staticlibs.push(CrateMismatch {
-                        path: path.clone(),
+                        path: path.to_path_buf(),
                         got: "static".to_string()
                     });
                 }
@@ -506,9 +507,9 @@ fn find_library_crate(&mut self) -> Option<Library> {
     // read the metadata from it if `*slot` is `None`. If the metadata couldn't
     // be read, it is assumed that the file isn't a valid rust library (no
     // errors are emitted).
-    fn extract_one(&mut self, m: HashMap<Path, PathKind>, flavor: &str,
-                   slot: &mut Option<MetadataBlob>) -> Option<(Path, PathKind)> {
-        let mut ret = None::<(Path, PathKind)>;
+    fn extract_one(&mut self, m: HashMap<PathBuf, PathKind>, flavor: &str,
+                   slot: &mut Option<MetadataBlob>) -> Option<(PathBuf, PathKind)> {
+        let mut ret = None::<(PathBuf, PathKind)>;
         let mut error = 0;
 
         if slot.is_some() {
@@ -587,7 +588,7 @@ fn crate_matches(&mut self, crate_data: &[u8], libpath: &Path) -> bool {
         if triple != self.triple {
             info!("Rejecting via crate triple: expected {} got {}", self.triple, triple);
             self.rejected_via_triple.push(CrateMismatch {
-                path: libpath.clone(),
+                path: libpath.to_path_buf(),
                 got: triple.to_string()
             });
             return false;
@@ -599,7 +600,7 @@ fn crate_matches(&mut self, crate_data: &[u8], libpath: &Path) -> bool {
                 if *myhash != hash {
                     info!("Rejecting via hash: expected {} got {}", *myhash, hash);
                     self.rejected_via_hash.push(CrateMismatch {
-                        path: libpath.clone(),
+                        path: libpath.to_path_buf(),
                         got: myhash.as_str().to_string()
                     });
                     false
@@ -627,13 +628,13 @@ fn find_commandline_library(&mut self, locs: &[String]) -> Option<Library> {
         let mut rlibs = HashMap::new();
         let mut dylibs = HashMap::new();
         {
-            let locs = locs.iter().map(|l| Path::new(&l[..])).filter(|loc| {
+            let locs = locs.iter().map(|l| PathBuf::new(&l[..])).filter(|loc| {
                 if !loc.exists() {
                     sess.err(&format!("extern location for {} does not exist: {}",
                                      self.crate_name, loc.display()));
                     return false;
                 }
-                let file = match loc.filename_str() {
+                let file = match loc.file_name().and_then(|s| s.to_str()) {
                     Some(file) => file,
                     None => {
                         sess.err(&format!("extern location for {} is not a file: {}",
@@ -658,7 +659,7 @@ fn find_commandline_library(&mut self, locs: &[String]) -> Option<Library> {
             // Now that we have an iterator of good candidates, make sure
             // there's at most one rlib and at most one dylib.
             for loc in locs {
-                if loc.filename_str().unwrap().ends_with(".rlib") {
+                if loc.file_name().unwrap().to_str().unwrap().ends_with(".rlib") {
                     rlibs.insert(fs::realpath(&loc).unwrap(),
                                  PathKind::ExternFlag);
                 } else {
@@ -714,7 +715,7 @@ fn get_metadata_section(is_osx: bool, filename: &Path) -> Result<MetadataBlob, S
     let dur = Duration::span(|| {
         ret = Some(get_metadata_section_imp(is_osx, filename));
     });
-    info!("reading {} => {}ms", filename.filename_display(),
+    info!("reading {:?} => {}ms", filename.file_name().unwrap(),
           dur.num_milliseconds());
     return ret.unwrap();;
 }
@@ -723,7 +724,7 @@ fn get_metadata_section_imp(is_osx: bool, filename: &Path) -> Result<MetadataBlo
     if !filename.exists() {
         return Err(format!("no such file: '{}'", filename.display()));
     }
-    if filename.filename_str().unwrap().ends_with(".rlib") {
+    if filename.file_name().unwrap().to_str().unwrap().ends_with(".rlib") {
         // Use ArchiveRO for speed here, it's backed by LLVM and uses mmap
         // internally to read the file. We also avoid even using a memcpy by
         // just keeping the archive along while the metadata is in use.
@@ -742,7 +743,7 @@ fn get_metadata_section_imp(is_osx: bool, filename: &Path) -> Result<MetadataBlo
         };
     }
     unsafe {
-        let buf = CString::new(filename.as_vec()).unwrap();
+        let buf = common::path2cstr(filename);
         let mb = llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf.as_ptr());
         if mb as int == 0 {
             return Err(format!("error reading library: '{}'",
@@ -811,7 +812,7 @@ pub fn read_meta_section_name(is_osx: bool) -> &'static str {
 
 // A diagnostic function for dumping crate metadata to an output stream
 pub fn list_file_metadata(is_osx: bool, path: &Path,
-                          out: &mut old_io::Writer) -> old_io::IoResult<()> {
+                          out: &mut io::Write) -> io::Result<()> {
     match get_metadata_section(is_osx, path) {
         Ok(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out),
         Err(msg) => {
index 33c0fb8b031ef4e8c05a8c6c414b244fd1b8955d..9d712c7c0fcc800d2e60e61363eb7f9f08c39ae3 100644 (file)
@@ -42,6 +42,7 @@
 use std::old_io::Seek;
 use std::num::FromPrimitive;
 use std::rc::Rc;
+use std::cell::Cell;
 
 use rbml::reader;
 use rbml::writer::Encoder;
@@ -58,7 +59,9 @@ struct DecodeContext<'a, 'b, 'tcx: 'a> {
     tcx: &'a ty::ctxt<'tcx>,
     cdata: &'b cstore::crate_metadata,
     from_id_range: ast_util::IdRange,
-    to_id_range: ast_util::IdRange
+    to_id_range: ast_util::IdRange,
+    // Cache the last used filemap for translating spans as an optimization.
+    last_filemap_index: Cell<usize>,
 }
 
 trait tr {
@@ -120,6 +123,8 @@ fn new_span(&self, span: Span) -> Span {
     }
 }
 
+/// Decodes an item from its AST in the cdata's metadata and adds it to the
+/// ast-map.
 pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
                                  tcx: &ty::ctxt<'tcx>,
                                  path: Vec<ast_map::PathElem>,
@@ -143,7 +148,8 @@ pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
             cdata: cdata,
             tcx: tcx,
             from_id_range: from_id_range,
-            to_id_range: to_id_range
+            to_id_range: to_id_range,
+            last_filemap_index: Cell::new(0)
         };
         let raw_ii = decode_ast(ast_doc);
         let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, raw_ii, dcx);
@@ -234,8 +240,47 @@ pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId {
         assert_eq!(did.krate, ast::LOCAL_CRATE);
         ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
     }
-    pub fn tr_span(&self, _span: Span) -> Span {
-        codemap::DUMMY_SP // FIXME (#1972): handle span properly
+
+    /// Translates a `Span` from an extern crate to the corresponding `Span`
+    /// within the local crate's codemap. `creader::import_codemap()` will
+    /// already have allocated any additionally needed FileMaps in the local
+    /// codemap as a side-effect of creating the crate_metadata's
+    /// `codemap_import_info`.
+    pub fn tr_span(&self, span: Span) -> Span {
+        let imported_filemaps = &self.cdata.codemap_import_info[..];
+
+        let filemap_index = {
+            // Optimize for the case that most spans within a translated item
+            // originate from the same filemap.
+            let last_filemap_index = self.last_filemap_index.get();
+
+            if span.lo >= imported_filemaps[last_filemap_index].original_start_pos &&
+               span.hi <= imported_filemaps[last_filemap_index].original_end_pos {
+                last_filemap_index
+            } else {
+                let mut a = 0;
+                let mut b = imported_filemaps.len();
+
+                while b - a > 1 {
+                    let m = (a + b) / 2;
+                    if imported_filemaps[m].original_start_pos > span.lo {
+                        b = m;
+                    } else {
+                        a = m;
+                    }
+                }
+
+                self.last_filemap_index.set(a);
+                a
+            }
+        };
+
+        let lo = (span.lo - imported_filemaps[filemap_index].original_start_pos) +
+                  imported_filemaps[filemap_index].translated_filemap.start_pos;
+        let hi = (span.hi - imported_filemaps[filemap_index].original_start_pos) +
+                  imported_filemaps[filemap_index].translated_filemap.start_pos;
+
+        codemap::mk_sp(lo, hi)
     }
 }
 
index 9291f175777fa79c8be766b033cd33fcaf000fae..ae43738d471eb8dc8ac833473aa920f9f72544d3 100644 (file)
@@ -79,7 +79,7 @@ fn variant_expr<'a>(variants: &'a [P<ast::Variant>], id: ast::NodeId)
             None => {}
         }
         let expr_id = match csearch::maybe_get_item_ast(tcx, enum_def,
-            box |a, b, c, d| astencode::decode_inlined_item(a, b, c, d)) {
+            Box::new(|a, b, c, d| astencode::decode_inlined_item(a, b, c, d))) {
             csearch::FoundAst::Found(&ast::IIItem(ref item)) => match item.node {
                 ast::ItemEnum(ast::EnumDef { ref variants }, _) => {
                     // NOTE this doesn't do the right thing, it compares inlined
@@ -119,7 +119,7 @@ pub fn lookup_const_by_id<'a>(tcx: &'a ty::ctxt, def_id: ast::DefId)
             None => {}
         }
         let expr_id = match csearch::maybe_get_item_ast(tcx, def_id,
-            box |a, b, c, d| astencode::decode_inlined_item(a, b, c, d)) {
+            Box::new(|a, b, c, d| astencode::decode_inlined_item(a, b, c, d))) {
             csearch::FoundAst::Found(&ast::IIItem(ref item)) => match item.node {
                 ast::ItemConst(_, ref const_expr) => Some(const_expr.id),
                 _ => None
index faed3f5977fdcb01b67747b6867ac5d6ecf909dc..a1ce8d18184e3e47af087755ad6192fff48bc8c9 100644 (file)
@@ -19,7 +19,7 @@
 use middle::cfg;
 use middle::cfg::CFGIndex;
 use middle::ty;
-use std::old_io;
+use std::io;
 use std::usize;
 use std::iter::repeat;
 use syntax::ast;
@@ -103,7 +103,7 @@ fn has_bitset_for_nodeid(&self, n: ast::NodeId) -> bool {
 impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O> {
     fn pre(&self,
            ps: &mut pprust::State,
-           node: pprust::AnnNode) -> old_io::IoResult<()> {
+           node: pprust::AnnNode) -> io::Result<()> {
         let id = match node {
             pprust::NodeIdent(_) | pprust::NodeName(_) => 0,
             pprust::NodeExpr(expr) => expr.id,
@@ -485,13 +485,15 @@ pub fn propagate(&mut self, cfg: &cfg::CFG, blk: &ast::Block) {
 
         debug!("Dataflow result for {}:", self.analysis_name);
         debug!("{}", {
-            self.pretty_print_to(box old_io::stderr(), blk).unwrap();
+            let mut v = Vec::new();
+            self.pretty_print_to(box &mut v, blk).unwrap();
+            println!("{}", String::from_utf8(v).unwrap());
             ""
         });
     }
 
-    fn pretty_print_to(&self, wr: Box<old_io::Writer+'static>,
-                       blk: &ast::Block) -> old_io::IoResult<()> {
+    fn pretty_print_to<'b>(&self, wr: Box<io::Write + 'b>,
+                           blk: &ast::Block) -> io::Result<()> {
         let mut ps = pprust::rust_printer_annotated(wr, self);
         try!(ps.cbox(pprust::indent_unit));
         try!(ps.ibox(0));
index 43cd1fc8edbac83b87300390c0678087cb335dee..6211fde79198af387731e8c3840abedef50a42b3 100644 (file)
 
 use std::borrow::Cow;
 use std::collections::hash_map::Entry::Vacant;
-use std::old_io::{self, File};
 use std::env;
+use std::fs::File;
+use std::io;
+use std::io::prelude::*;
 use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT};
 use syntax::ast;
 
@@ -256,10 +258,11 @@ fn target(&self, edge: &Edge) -> Node {
 
 fn dump_region_constraints_to<'a, 'tcx:'a >(tcx: &'a ty::ctxt<'tcx>,
                                             map: &ConstraintMap<'tcx>,
-                                            path: &str) -> old_io::IoResult<()> {
+                                            path: &str) -> io::Result<()> {
     debug!("dump_region_constraints map (len: {}) path: {}", map.len(), path);
     let g = ConstraintGraph::new(tcx, format!("region_constraints"), map);
-    let mut f = File::create(&Path::new(path));
     debug!("dump_region_constraints calling render");
-    dot::render(&g, &mut f)
+    let mut v = Vec::new();
+    dot::render(&g, &mut v).unwrap();
+    File::create(path).and_then(|mut f| f.write_all(&v))
 }
index a419d4134b40e4677faba9b0355848ccc5e1b98a..8267b79ff9e7aee3432559ea0e18f621a5ecf317 100644 (file)
 use metadata::creader::CrateReader;
 use plugin::registry::Registry;
 
-use std::mem;
-use std::os;
-use std::dynamic_lib::DynamicLibrary;
 use std::borrow::ToOwned;
+use std::dynamic_lib::DynamicLibrary;
+use std::env;
+use std::mem;
+use std::old_path;
+use std::path::PathBuf;
 use syntax::ast;
 use syntax::codemap::{Span, COMMAND_LINE_SP};
 use syntax::ptr::P;
@@ -100,10 +102,11 @@ fn load_plugin(&mut self, span: Span, name: &str, args: Vec<P<ast::MetaItem>>) {
     // Dynamically link a registrar function into the compiler process.
     fn dylink_registrar(&mut self,
                         span: Span,
-                        path: Path,
+                        path: PathBuf,
                         symbol: String) -> PluginRegistrarFun {
         // Make sure the path contains a / or the linker will search for it.
-        let path = os::getcwd().unwrap().join(&path);
+        let path = env::current_dir().unwrap().join(&path);
+        let path = old_path::Path::new(path.to_str().unwrap());
 
         let lib = match DynamicLibrary::open(Some(&path)) {
             Ok(lib) => lib,
index 12634204f8b12f2bd31c02dc36d8ccf8b973c8c1..6f98b79e782c0bcd7841427fd7a0bd795fcb9e01 100644 (file)
@@ -99,7 +99,7 @@ pub fn register_syntax_extension(&mut self, name: ast::Name, extension: SyntaxEx
     /// It builds for you a `NormalTT` that calls `expander`,
     /// and also takes care of interning the macro's name.
     pub fn register_macro(&mut self, name: &str, expander: MacroExpanderFn) {
-        self.register_syntax_extension(token::intern(name), NormalTT(box expander, None));
+        self.register_syntax_extension(token::intern(name), NormalTT(Box::new(expander), None));
     }
 
     /// Register a compiler lint pass.
index 536caece21f841f3309b76a39b5ecf2725cd5e3e..a4355803f4a4e3bd79fd3f6223be46b1a8a0f664 100644 (file)
@@ -38,6 +38,7 @@
 use std::collections::hash_map::Entry::{Occupied, Vacant};
 use std::env;
 use std::fmt;
+use std::path::PathBuf;
 
 use llvm;
 
@@ -89,7 +90,7 @@ pub struct Options {
     // this.
     pub search_paths: SearchPaths,
     pub libs: Vec<(String, cstore::NativeLibraryKind)>,
-    pub maybe_sysroot: Option<Path>,
+    pub maybe_sysroot: Option<PathBuf>,
     pub target_triple: String,
     // User-specified cfg meta items. The compiler itself will add additional
     // items to the crate config, and during parsing the entire crate config
@@ -103,7 +104,7 @@ pub struct Options {
     pub no_analysis: bool,
     pub debugging_opts: DebuggingOptions,
     /// Whether to write dependency files. It's (enabled, optional filename).
-    pub write_dependency_info: (bool, Option<Path>),
+    pub write_dependency_info: (bool, Option<PathBuf>),
     pub prints: Vec<PrintRequest>,
     pub cg: CodegenOptions,
     pub color: ColorConfig,
@@ -142,7 +143,7 @@ pub enum PrintRequest {
 
 pub enum Input {
     /// Load source from file
-    File(Path),
+    File(PathBuf),
     /// The string is the source
     Str(String)
 }
@@ -150,7 +151,8 @@ pub enum Input {
 impl Input {
     pub fn filestem(&self) -> String {
         match *self {
-            Input::File(ref ifile) => ifile.filestem_str().unwrap().to_string(),
+            Input::File(ref ifile) => ifile.file_stem().unwrap()
+                                           .to_str().unwrap().to_string(),
             Input::Str(_) => "rust_out".to_string(),
         }
     }
@@ -158,14 +160,14 @@ pub fn filestem(&self) -> String {
 
 #[derive(Clone)]
 pub struct OutputFilenames {
-    pub out_directory: Path,
+    pub out_directory: PathBuf,
     pub out_filestem: String,
-    pub single_output_file: Option<Path>,
+    pub single_output_file: Option<PathBuf>,
     pub extra: String,
 }
 
 impl OutputFilenames {
-    pub fn path(&self, flavor: OutputType) -> Path {
+    pub fn path(&self, flavor: OutputType) -> PathBuf {
         match self.single_output_file {
             Some(ref path) => return path.clone(),
             None => {}
@@ -173,8 +175,8 @@ pub fn path(&self, flavor: OutputType) -> Path {
         self.temp_path(flavor)
     }
 
-    pub fn temp_path(&self, flavor: OutputType) -> Path {
-        let base = self.out_directory.join(self.filestem());
+    pub fn temp_path(&self, flavor: OutputType) -> PathBuf {
+        let base = self.out_directory.join(&self.filestem());
         match flavor {
             OutputTypeBitcode => base.with_extension("bc"),
             OutputTypeAssembly => base.with_extension("s"),
@@ -185,8 +187,8 @@ pub fn temp_path(&self, flavor: OutputType) -> Path {
         }
     }
 
-    pub fn with_extension(&self, extension: &str) -> Path {
-        self.out_directory.join(self.filestem()).with_extension(extension)
+    pub fn with_extension(&self, extension: &str) -> PathBuf {
+        self.out_directory.join(&self.filestem()).with_extension(extension)
     }
 
     pub fn filestem(&self) -> String {
@@ -897,7 +899,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
 
     let cg = build_codegen_options(matches);
 
-    let sysroot_opt = matches.opt_str("sysroot").map(|m| Path::new(m));
+    let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::new(&m));
     let target = matches.opt_str("target").unwrap_or(
         host_triple().to_string());
     let opt_level = {
index 67c39bcca81f9a963fd8d863d57dc562675de040..a478cb79796aa7a015481e3c936926602a36fd03 100644 (file)
@@ -26,8 +26,9 @@
 
 use rustc_back::target::Target;
 
+use std::path::{Path, PathBuf};
 use std::cell::{Cell, RefCell};
-use std::os;
+use std::env;
 
 pub mod config;
 pub mod search_paths;
@@ -44,11 +45,11 @@ pub struct Session {
     pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
     pub entry_type: Cell<Option<config::EntryFnType>>,
     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
-    pub default_sysroot: Option<Path>,
+    pub default_sysroot: Option<PathBuf>,
     // The name of the root source file of the crate, in the local file system. The path is always
     // expected to be absolute. `None` means that there is no source file.
-    pub local_crate_source_file: Option<Path>,
-    pub working_dir: Path,
+    pub local_crate_source_file: Option<PathBuf>,
+    pub working_dir: PathBuf,
     pub lint_store: RefCell<lint::LintStore>,
     pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
     pub crate_types: RefCell<Vec<config::CrateType>>,
@@ -310,7 +311,7 @@ fn split_msg_into_multilines(msg: &str) -> Option<String> {
 }
 
 pub fn build_session(sopts: config::Options,
-                     local_crate_source_file: Option<Path>,
+                     local_crate_source_file: Option<PathBuf>,
                      registry: diagnostics::registry::Registry)
                      -> Session {
     // FIXME: This is not general enough to make the warning lint completely override
@@ -333,7 +334,7 @@ pub fn build_session(sopts: config::Options,
 }
 
 pub fn build_session_(sopts: config::Options,
-                      local_crate_source_file: Option<Path>,
+                      local_crate_source_file: Option<PathBuf>,
                       span_diagnostic: diagnostic::SpanHandler)
                       -> Session {
     let host = match Target::search(config::host_triple()) {
@@ -355,7 +356,7 @@ pub fn build_session_(sopts: config::Options,
         if path.is_absolute() {
             path.clone()
         } else {
-            os::getcwd().unwrap().join(&path)
+            env::current_dir().unwrap().join(&path)
         }
     );
 
@@ -378,7 +379,7 @@ pub fn build_session_(sopts: config::Options,
         plugin_registrar_fn: Cell::new(None),
         default_sysroot: default_sysroot,
         local_crate_source_file: local_crate_source_file,
-        working_dir: os::getcwd().unwrap(),
+        working_dir: env::current_dir().unwrap(),
         lint_store: RefCell::new(lint::LintStore::new()),
         lints: RefCell::new(NodeMap()),
         crate_types: RefCell::new(Vec::new()),
index c314a999f246119cf1ca7d340b5c8586f0a245e3..f85fb3039102e9eb300c9160352ab4c6ac7f24c7 100644 (file)
@@ -9,15 +9,16 @@
 // except according to those terms.
 
 use std::slice;
+use std::path::{Path, PathBuf};
 
 #[derive(Clone, Debug)]
 pub struct SearchPaths {
-    paths: Vec<(PathKind, Path)>,
+    paths: Vec<(PathKind, PathBuf)>,
 }
 
 pub struct Iter<'a> {
     kind: PathKind,
-    iter: slice::Iter<'a, (PathKind, Path)>,
+    iter: slice::Iter<'a, (PathKind, PathBuf)>,
 }
 
 #[derive(Eq, PartialEq, Clone, Copy, Debug)]
@@ -49,7 +50,7 @@ pub fn add_path(&mut self, path: &str) {
         } else {
             (PathKind::All, path)
         };
-        self.paths.push((kind, Path::new(path)));
+        self.paths.push((kind, PathBuf::new(path)));
     }
 
     pub fn iter(&self, kind: PathKind) -> Iter {
index ca740f53782192de205ca915ea630785cd62bc1d..0b32f7f69eb448234f93f89756c22a8bf13389da 100644 (file)
 
 use std::cell::{RefCell, Cell};
 use std::collections::HashMap;
+use std::collections::hash_state::HashState;
+use std::ffi::CString;
 use std::fmt::Debug;
 use std::hash::Hash;
 use std::iter::repeat;
+use std::path::Path;
 use std::time::Duration;
-use std::collections::hash_state::HashState;
 
 use syntax::ast;
 use syntax::visit;
@@ -222,3 +224,14 @@ pub fn memoized<T, U, S, F>(cache: &RefCell<HashMap<T, U, S>>, arg: T, f: F) ->
         }
     }
 }
+
+#[cfg(unix)]
+pub fn path2cstr(p: &Path) -> CString {
+    use std::os::unix::prelude::*;
+    use std::ffi::AsOsStr;
+    CString::new(p.as_os_str().as_bytes()).unwrap()
+}
+#[cfg(windows)]
+pub fn path2cstr(p: &Path) -> CString {
+    CString::new(p.to_str().unwrap()).unwrap()
+}
index 97b1a8aaaba0304d7a0f5ced6e103d84646d4801..a6994387f8d6a27234eae257afe7106f182b0a00 100644 (file)
 
 //! A helper class for dealing with static archives
 
-use std::old_io::fs::PathExtensions;
-use std::old_io::process::{Command, ProcessOutput};
-use std::old_io::{fs, TempDir};
-use std::old_io;
-use std::os;
+use std::env;
+use std::fs::{self, TempDir};
+use std::io::prelude::*;
+use std::io;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output, Stdio};
 use std::str;
 use syntax::diagnostic::Handler as ErrorHandler;
 
@@ -22,8 +23,8 @@
 
 pub struct ArchiveConfig<'a> {
     pub handler: &'a ErrorHandler,
-    pub dst: Path,
-    pub lib_search_paths: Vec<Path>,
+    pub dst: PathBuf,
+    pub lib_search_paths: Vec<PathBuf>,
     pub slib_prefix: String,
     pub slib_suffix: String,
     pub maybe_ar_prog: Option<String>
@@ -31,8 +32,8 @@ pub struct ArchiveConfig<'a> {
 
 pub struct Archive<'a> {
     handler: &'a ErrorHandler,
-    dst: Path,
-    lib_search_paths: Vec<Path>,
+    dst: PathBuf,
+    lib_search_paths: Vec<PathBuf>,
     slib_prefix: String,
     slib_suffix: String,
     maybe_ar_prog: Option<String>
@@ -45,25 +46,25 @@ pub struct ArchiveBuilder<'a> {
     archive: Archive<'a>,
     work_dir: TempDir,
     /// Filename of each member that should be added to the archive.
-    members: Vec<Path>,
+    members: Vec<PathBuf>,
     should_update_symbols: bool,
 }
 
 fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
           args: &str, cwd: Option<&Path>,
-          paths: &[&Path]) -> ProcessOutput {
+          paths: &[&Path]) -> Output {
     let ar = match *maybe_ar_prog {
         Some(ref ar) => &ar[..],
         None => "ar"
     };
     let mut cmd = Command::new(ar);
 
-    cmd.arg(args).args(paths);
+    cmd.arg(args).args(paths).stdout(Stdio::piped()).stderr(Stdio::piped());
     debug!("{:?}", cmd);
 
     match cwd {
         Some(p) => {
-            cmd.cwd(p);
+            cmd.current_dir(p);
             debug!("inside {:?}", p.display());
         }
         None => {}
@@ -75,9 +76,9 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
             if !o.status.success() {
                 handler.err(&format!("{:?} failed with: {}", cmd, o.status));
                 handler.note(&format!("stdout ---\n{}",
-                                  str::from_utf8(&o.output).unwrap()));
+                                  str::from_utf8(&o.stdout).unwrap()));
                 handler.note(&format!("stderr ---\n{}",
-                                  str::from_utf8(&o.error).unwrap())
+                                  str::from_utf8(&o.stderr).unwrap())
                              );
                 handler.abort_if_errors();
             }
@@ -93,14 +94,15 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
 }
 
 pub fn find_library(name: &str, osprefix: &str, ossuffix: &str,
-                    search_paths: &[Path], handler: &ErrorHandler) -> Path {
+                    search_paths: &[PathBuf],
+                    handler: &ErrorHandler) -> PathBuf {
     // On Windows, static libraries sometimes show up as libfoo.a and other
     // times show up as foo.lib
     let oslibname = format!("{}{}{}", osprefix, name, ossuffix);
     let unixlibname = format!("lib{}.a", name);
 
     for path in search_paths {
-        debug!("looking for {} inside {:?}", name, path.display());
+        debug!("looking for {} inside {:?}", name, path);
         let test = path.join(&oslibname[..]);
         if test.exists() { return test }
         if oslibname != unixlibname {
@@ -142,7 +144,7 @@ pub fn remove_file(&mut self, file: &str) {
     /// Lists all files in an archive
     pub fn files(&self) -> Vec<String> {
         let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, &[&self.dst]);
-        let output = str::from_utf8(&output.output).unwrap();
+        let output = str::from_utf8(&output.stdout).unwrap();
         // use lines_any because windows delimits output with `\r\n` instead of
         // just `\n`
         output.lines_any().map(|s| s.to_string()).collect()
@@ -172,7 +174,7 @@ pub fn create(config: ArchiveConfig<'a>) -> ArchiveBuilder<'a> {
 
     /// Adds all of the contents of a native library to this archive. This will
     /// search in the relevant locations for a library named `name`.
-    pub fn add_native_library(&mut self, name: &str) -> old_io::IoResult<()> {
+    pub fn add_native_library(&mut self, name: &str) -> io::Result<()> {
         let location = find_library(name,
                                     &self.archive.slib_prefix,
                                     &self.archive.slib_suffix,
@@ -187,7 +189,7 @@ pub fn add_native_library(&mut self, name: &str) -> old_io::IoResult<()> {
     /// This ignores adding the bytecode from the rlib, and if LTO is enabled
     /// then the object file also isn't added.
     pub fn add_rlib(&mut self, rlib: &Path, name: &str,
-                    lto: bool) -> old_io::IoResult<()> {
+                    lto: bool) -> io::Result<()> {
         // Ignoring obj file starting with the crate name
         // as simple comparison is not enough - there
         // might be also an extra name suffix
@@ -205,11 +207,11 @@ pub fn add_rlib(&mut self, rlib: &Path, name: &str,
     }
 
     /// Adds an arbitrary file to this archive
-    pub fn add_file(&mut self, file: &Path) -> old_io::IoResult<()> {
-        let filename = Path::new(file.filename().unwrap());
+    pub fn add_file(&mut self, file: &Path) -> io::Result<()> {
+        let filename = Path::new(file.file_name().unwrap());
         let new_file = self.work_dir.path().join(&filename);
         try!(fs::copy(file, &new_file));
-        self.members.push(filename);
+        self.members.push(filename.to_path_buf());
         Ok(())
     }
 
@@ -224,10 +226,10 @@ pub fn update_symbols(&mut self) {
     pub fn build(self) -> Archive<'a> {
         // Get an absolute path to the destination, so `ar` will work even
         // though we run it from `self.work_dir`.
-        let abs_dst = os::getcwd().unwrap().join(&self.archive.dst);
+        let abs_dst = env::current_dir().unwrap().join(&self.archive.dst);
         assert!(!abs_dst.is_relative());
-        let mut args = vec![&abs_dst];
-        let mut total_len = abs_dst.as_vec().len();
+        let mut args = vec![&*abs_dst];
+        let mut total_len = abs_dst.to_string_lossy().len();
 
         if self.members.is_empty() {
             // OSX `ar` does not allow using `r` with no members, but it does
@@ -245,7 +247,7 @@ pub fn build(self) -> Archive<'a> {
         const ARG_LENGTH_LIMIT: uint = 32_000;
 
         for member_name in &self.members {
-            let len = member_name.as_vec().len();
+            let len = member_name.to_string_lossy().len();
 
             // `len + 1` to account for the space that's inserted before each
             // argument.  (Windows passes command-line arguments as a single
@@ -258,7 +260,7 @@ pub fn build(self) -> Archive<'a> {
 
                 args.clear();
                 args.push(&abs_dst);
-                total_len = abs_dst.as_vec().len();
+                total_len = abs_dst.to_string_lossy().len();
             }
 
             args.push(member_name);
@@ -275,7 +277,7 @@ pub fn build(self) -> Archive<'a> {
     }
 
     fn add_archive<F>(&mut self, archive: &Path, name: &str,
-                      mut skip: F) -> old_io::IoResult<()>
+                      mut skip: F) -> io::Result<()>
         where F: FnMut(&str) -> bool,
     {
         let loc = TempDir::new("rsar").unwrap();
@@ -283,7 +285,7 @@ fn add_archive<F>(&mut self, archive: &Path, name: &str,
         // First, extract the contents of the archive to a temporary directory.
         // We don't unpack directly into `self.work_dir` due to the possibility
         // of filename collisions.
-        let archive = os::getcwd().unwrap().join(archive);
+        let archive = env::current_dir().unwrap().join(archive);
         run_ar(self.archive.handler, &self.archive.maybe_ar_prog,
                "x", Some(loc.path()), &[&archive]);
 
@@ -296,9 +298,10 @@ fn add_archive<F>(&mut self, archive: &Path, name: &str,
         // We skip any files explicitly desired for skipping, and we also skip
         // all SYMDEF files as these are just magical placeholders which get
         // re-created when we make a new archive anyway.
-        let files = try!(fs::readdir(loc.path()));
-        for file in &files {
-            let filename = file.filename_str().unwrap();
+        let files = try!(fs::read_dir(loc.path()));
+        for file in files {
+            let file = try!(file).path();
+            let filename = file.file_name().unwrap().to_str().unwrap();
             if skip(filename) { continue }
             if filename.contains(".SYMDEF") { continue }
 
@@ -313,8 +316,8 @@ fn add_archive<F>(&mut self, archive: &Path, name: &str,
                 filename
             };
             let new_filename = self.work_dir.path().join(&filename[..]);
-            try!(fs::rename(file, &new_filename));
-            self.members.push(Path::new(filename));
+            try!(fs::rename(&file, &new_filename));
+            self.members.push(PathBuf::new(&filename));
         }
         Ok(())
     }
index 56d71820176b419b4d5a02ec145555a0c2c139f0..c00c33d4c2fed505ce680d72c1321777498a1141 100644 (file)
@@ -8,14 +8,29 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use std::old_io;
+use std::io;
 use std::old_io::fs;
+use std::old_io;
+use std::old_path;
 use std::os;
+use std::path::{Path, PathBuf};
 
 /// Returns an absolute path in the filesystem that `path` points to. The
 /// returned path does not contain any symlinks in its hierarchy.
-pub fn realpath(original: &Path) -> old_io::IoResult<Path> {
-    const MAX_LINKS_FOLLOWED: uint = 256;
+#[allow(deprecated)] // readlink is deprecated
+pub fn realpath(original: &Path) -> io::Result<PathBuf> {
+    let old = old_path::Path::new(original.to_str().unwrap());
+    match old_realpath(&old) {
+        Ok(p) => Ok(PathBuf::new(p.as_str().unwrap())),
+        Err(e) => Err(io::Error::new(io::ErrorKind::Other,
+                                     "realpath error",
+                                     Some(e.to_string())))
+    }
+}
+
+#[allow(deprecated)]
+fn old_realpath(original: &old_path::Path) -> old_io::IoResult<old_path::Path> {
+    const MAX_LINKS_FOLLOWED: usize = 256;
     let original = try!(os::getcwd()).join(original);
 
     // Right now lstat on windows doesn't work quite well
@@ -55,7 +70,7 @@ pub fn realpath(original: &Path) -> old_io::IoResult<Path> {
 mod test {
     use std::old_io;
     use std::old_io::fs::{File, symlink, mkdir, mkdir_recursive};
-    use super::realpath;
+    use super::old_realpath as realpath;
     use std::old_io::TempDir;
 
     #[test]
index 9005c666afbcdd254b1c3503b3796663e667a7e4..2b028a5c626234f63381d38f1672f01c14a9a72f 100644 (file)
 #![feature(box_syntax)]
 #![feature(collections)]
 #![feature(core)]
+#![feature(old_fs)]
+#![feature(fs)]
 #![feature(hash)]
 #![feature(int_uint)]
+#![feature(io)]
 #![feature(old_io)]
-#![feature(os)]
 #![feature(old_path)]
+#![feature(os)]
+#![feature(path)]
 #![feature(rustc_private)]
 #![feature(staged_api)]
-#![feature(path)]
+#![feature(tempdir)]
 
 extern crate syntax;
 extern crate serialize;
index 943ff52925a244545de15c4856f252db57bf7991..4f9f1447d8a731b918f765666306916435348de4 100644 (file)
 
 use std::collections::HashSet;
 use std::env;
-use std::old_io::IoError;
-use std::os;
+use std::io;
+use std::path::{Path, PathBuf};
 use syntax::ast;
 
-pub struct RPathConfig<F, G> where
-    F: FnOnce() -> Path,
-    G: FnMut(&Path) -> Result<Path, IoError>,
-{
-    pub used_crates: Vec<(ast::CrateNum, Option<Path>)>,
-    pub out_filename: Path,
+pub struct RPathConfig<'a> {
+    pub used_crates: Vec<(ast::CrateNum, Option<PathBuf>)>,
+    pub out_filename: PathBuf,
     pub is_like_osx: bool,
     pub has_rpath: bool,
-    pub get_install_prefix_lib_path: F,
-    pub realpath: G,
+    pub get_install_prefix_lib_path: &'a mut FnMut() -> PathBuf,
+    pub realpath: &'a mut FnMut(&Path) -> io::Result<PathBuf>,
 }
 
-pub fn get_rpath_flags<F, G>(config: RPathConfig<F, G>) -> Vec<String> where
-    F: FnOnce() -> Path,
-    G: FnMut(&Path) -> Result<Path, IoError>,
-{
+pub fn get_rpath_flags(config: &mut RPathConfig) -> Vec<String> {
     // No rpath on windows
     if !config.has_rpath {
         return Vec::new();
@@ -54,10 +48,7 @@ fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> {
     return ret;
 }
 
-fn get_rpaths<F, G>(mut config: RPathConfig<F, G>, libs: &[Path]) -> Vec<String> where
-    F: FnOnce() -> Path,
-    G: FnMut(&Path) -> Result<Path, IoError>,
-{
+fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec<String> {
     debug!("output: {:?}", config.out_filename.display());
     debug!("libs:");
     for libpath in libs {
@@ -67,7 +58,7 @@ fn get_rpaths<F, G>(mut config: RPathConfig<F, G>, libs: &[Path]) -> Vec<String>
     // Use relative paths to the libraries. Binaries can be moved
     // as long as they maintain the relative relationship to the
     // crates they depend on.
-    let rel_rpaths = get_rpaths_relative_to_output(&mut config, libs);
+    let rel_rpaths = get_rpaths_relative_to_output(config, libs);
 
     // And a final backup rpath to the global library location.
     let fallback_rpaths = vec!(get_install_prefix_rpath(config));
@@ -90,18 +81,12 @@ fn log_rpaths(desc: &str, rpaths: &[String]) {
     return rpaths;
 }
 
-fn get_rpaths_relative_to_output<F, G>(config: &mut RPathConfig<F, G>,
-                                       libs: &[Path]) -> Vec<String> where
-    F: FnOnce() -> Path,
-    G: FnMut(&Path) -> Result<Path, IoError>,
-{
+fn get_rpaths_relative_to_output(config: &mut RPathConfig,
+                                 libs: &[PathBuf]) -> Vec<String> {
     libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
 }
 
-fn get_rpath_relative_to_output<F, G>(config: &mut RPathConfig<F, G>, lib: &Path) -> String where
-    F: FnOnce() -> Path,
-    G: FnMut(&Path) -> Result<Path, IoError>,
-{
+fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String {
     // Mac doesn't appear to support $ORIGIN
     let prefix = if config.is_like_osx {
         "@loader_path"
@@ -109,23 +94,36 @@ fn get_rpath_relative_to_output<F, G>(config: &mut RPathConfig<F, G>, lib: &Path
         "$ORIGIN"
     };
 
-    let cwd = os::getcwd().unwrap();
+    let cwd = env::current_dir().unwrap();
     let mut lib = (config.realpath)(&cwd.join(lib)).unwrap();
     lib.pop();
     let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap();
     output.pop();
-    let relative = lib.path_relative_from(&output);
-    let relative = relative.expect("could not create rpath relative to output");
+    let relative = relativize(&lib, &output);
     // FIXME (#9639): This needs to handle non-utf8 paths
-    format!("{}/{}",
-            prefix,
-            relative.as_str().expect("non-utf8 component in path"))
+    format!("{}/{}", prefix,
+            relative.to_str().expect("non-utf8 component in path"))
 }
 
-fn get_install_prefix_rpath<F, G>(config: RPathConfig<F, G>) -> String where
-    F: FnOnce() -> Path,
-    G: FnMut(&Path) -> Result<Path, IoError>,
-{
+fn relativize(path: &Path, rel: &Path) -> PathBuf {
+    let mut res = PathBuf::new("");
+    let mut cur = rel;
+    while !path.starts_with(cur) {
+        res.push("..");
+        match cur.parent() {
+            Some(p) => cur = p,
+            None => panic!("can't create relative paths across filesystems"),
+        }
+    }
+    match path.relative_from(cur) {
+        Some(s) => { res.push(s); res }
+        None => panic!("couldn't create relative path from {:?} to {:?}",
+                       rel, path),
+    }
+
+}
+
+fn get_install_prefix_rpath(config: &mut RPathConfig) -> String {
     let path = (config.get_install_prefix_lib_path)();
     let path = env::current_dir().unwrap().join(&path);
     // FIXME (#9639): This needs to handle non-utf8 paths
@@ -147,6 +145,7 @@ fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
 mod test {
     use super::{RPathConfig};
     use super::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output};
+    use std::path::{Path, PathBuf};
 
     #[test]
     fn test_rpaths_to_flags() {
@@ -195,50 +194,31 @@ fn test_minimize2() {
     }
 
     #[test]
-    #[cfg(any(target_os = "linux", target_os = "android"))]
     fn test_rpath_relative() {
-        let config = &mut RPathConfig {
-            used_crates: Vec::new(),
-            out_filename: Path::new("bin/rustc"),
-            get_install_prefix_lib_path: || panic!(),
-            has_rpath: true,
-            is_like_osx: false,
-            realpath: |p| Ok(p.clone())
-        };
-        let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
-        assert_eq!(res, "$ORIGIN/../lib");
-    }
-
-    #[test]
-    #[cfg(any(target_os = "freebsd",
-              target_os = "dragonfly",
-              target_os = "bitrig",
-              target_os = "openbsd"))]
-    fn test_rpath_relative() {
-        let config = &mut RPathConfig {
-            used_crates: Vec::new(),
-            has_rpath: true,
-            is_like_osx: false,
-            out_filename: Path::new("bin/rustc"),
-            get_install_prefix_lib_path: || panic!(),
-            realpath: |p| Ok(p.clone())
-        };
-        let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
-        assert_eq!(res, "$ORIGIN/../lib");
-    }
-
-    #[test]
-    #[cfg(target_os = "macos")]
-    fn test_rpath_relative() {
-        let config = &mut RPathConfig {
-            used_crates: Vec::new(),
-            has_rpath: true,
-            is_like_osx: true,
-            out_filename: Path::new("bin/rustc"),
-            get_install_prefix_lib_path: || panic!(),
-            realpath: |p| Ok(p.clone())
-        };
-        let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
-        assert_eq!(res, "@loader_path/../lib");
+        if cfg!(target_os = "macos") {
+            let config = &mut RPathConfig {
+                used_crates: Vec::new(),
+                has_rpath: true,
+                is_like_osx: true,
+                out_filename: PathBuf::new("bin/rustc"),
+                get_install_prefix_lib_path: &mut || panic!(),
+                realpath: &mut |p| Ok(p.to_path_buf()),
+            };
+            let res = get_rpath_relative_to_output(config,
+                                                   Path::new("lib/libstd.so"));
+            assert_eq!(res, "@loader_path/../lib");
+        } else {
+            let config = &mut RPathConfig {
+                used_crates: Vec::new(),
+                out_filename: PathBuf::new("bin/rustc"),
+                get_install_prefix_lib_path: &mut || panic!(),
+                has_rpath: true,
+                is_like_osx: false,
+                realpath: &mut |p| Ok(p.to_path_buf()),
+            };
+            let res = get_rpath_relative_to_output(config,
+                                                   Path::new("lib/libstd.so"));
+            assert_eq!(res, "$ORIGIN/../lib");
+        }
     }
 }
index 8acb6851f111d752e4755a15afeb9267a6bff913..844920ad5ece1a8d7ec7731df38714ee054eebfd 100644 (file)
@@ -606,7 +606,7 @@ fn test_sha256() {
 
         let tests = wikipedia_tests;
 
-        let mut sh = box Sha256::new();
+        let mut sh: Box<_> = box Sha256::new();
 
         test_hash(&mut *sh, &tests);
     }
index d09a7c355d3e3c32ef00aa2d1f819f1d9d39ff26..4663901a7b4c1f84114586dc066bf05feecf5aac 100644 (file)
@@ -48,7 +48,7 @@
 use serialize::json::Json;
 use syntax::{diagnostic, abi};
 use std::default::Default;
-use std::old_io::fs::PathExtensions;
+use std::io::prelude::*;
 
 mod windows_base;
 mod linux_base;
@@ -302,23 +302,26 @@ macro_rules! key {
         base
     }
 
-    /// Search RUST_TARGET_PATH for a JSON file specifying the given target triple. Note that it
-    /// could also just be a bare filename already, so also check for that. If one of the hardcoded
-    /// targets we know about, just return it directly.
+    /// Search RUST_TARGET_PATH for a JSON file specifying the given target
+    /// triple. Note that it could also just be a bare filename already, so also
+    /// check for that. If one of the hardcoded targets we know about, just
+    /// return it directly.
     ///
-    /// The error string could come from any of the APIs called, including filesystem access and
-    /// JSON decoding.
+    /// The error string could come from any of the APIs called, including
+    /// filesystem access and JSON decoding.
     pub fn search(target: &str) -> Result<Target, String> {
         use std::env;
-        use std::os;
         use std::ffi::OsString;
-        use std::old_io::File;
-        use std::old_path::Path;
+        use std::fs::File;
+        use std::path::{Path, PathBuf};
         use serialize::json;
 
         fn load_file(path: &Path) -> Result<Target, String> {
-            let mut f = try!(File::open(path).map_err(|e| format!("{:?}", e)));
-            let obj = try!(json::from_reader(&mut f).map_err(|e| format!("{:?}", e)));
+            let mut f = try!(File::open(path).map_err(|e| e.to_string()));
+            let mut contents = Vec::new();
+            try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
+            let obj = try!(json::from_reader(&mut &contents[..])
+                                .map_err(|e| e.to_string()));
             Ok(Target::from_json(obj))
         }
 
@@ -390,15 +393,16 @@ macro_rules! load_specific {
         let path = {
             let mut target = target.to_string();
             target.push_str(".json");
-            Path::new(target)
+            PathBuf::new(&target)
         };
 
-        let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or(OsString::from_str(""));
+        let target_path = env::var_os("RUST_TARGET_PATH")
+                              .unwrap_or(OsString::from_str(""));
 
         // FIXME 16351: add a sane default search path?
 
-        for dir in os::split_paths(target_path.to_str().unwrap()).iter() {
-            let p =  dir.join(path.clone());
+        for dir in env::split_paths(&target_path) {
+            let p =  dir.join(&path);
             if p.is_file() {
                 return load_file(&p);
             }
index 425ec7ec452eecd4b2347c36a5d32257f7accf01..73682faf1a77b3ffccac90846ca5da07e52cea20 100644 (file)
 use serialize::json;
 
 use std::env;
-use std::os;
 use std::ffi::OsString;
-use std::old_io::fs;
-use std::old_io;
+use std::fs;
+use std::io::{self, Write};
+use std::path::{Path, PathBuf};
 use syntax::ast;
 use syntax::ast_map;
 use syntax::attr;
@@ -48,8 +48,8 @@
 pub fn compile_input(sess: Session,
                      cfg: ast::CrateConfig,
                      input: &Input,
-                     outdir: &Option<Path>,
-                     output: &Option<Path>,
+                     outdir: &Option<PathBuf>,
+                     output: &Option<PathBuf>,
                      addl_plugins: Option<Vec<String>>,
                      control: CompileController) {
     macro_rules! controller_entry_point{($point: ident, $make_state: expr) => ({
@@ -166,7 +166,7 @@ pub fn anon_src() -> String {
 pub fn source_name(input: &Input) -> String {
     match *input {
         // FIXME (#9639): This needs to handle non-utf8 paths
-        Input::File(ref ifile) => ifile.as_str().unwrap().to_string(),
+        Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
         Input::Str(_) => anon_src()
     }
 }
@@ -243,12 +243,12 @@ pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
     fn empty(input: &'a Input,
              session: &'a Session,
-             out_dir: &'a Option<Path>)
+             out_dir: &'a Option<PathBuf>)
              -> CompileState<'a, 'ast, 'tcx> {
         CompileState {
             input: input,
             session: session,
-            out_dir: out_dir.as_ref(),
+            out_dir: out_dir.as_ref().map(|s| &**s),
             cfg: None,
             krate: None,
             crate_name: None,
@@ -263,7 +263,7 @@ fn empty(input: &'a Input,
 
     fn state_after_parse(input: &'a Input,
                          session: &'a Session,
-                         out_dir: &'a Option<Path>,
+                         out_dir: &'a Option<PathBuf>,
                          krate: &'a ast::Crate)
                          -> CompileState<'a, 'ast, 'tcx> {
         CompileState {
@@ -274,7 +274,7 @@ fn state_after_parse(input: &'a Input,
 
     fn state_after_expand(input: &'a Input,
                           session: &'a Session,
-                          out_dir: &'a Option<Path>,
+                          out_dir: &'a Option<PathBuf>,
                           expanded_crate: &'a ast::Crate,
                           crate_name: &'a str)
                           -> CompileState<'a, 'ast, 'tcx> {
@@ -287,7 +287,7 @@ fn state_after_expand(input: &'a Input,
 
     fn state_after_write_deps(input: &'a Input,
                               session: &'a Session,
-                              out_dir: &'a Option<Path>,
+                              out_dir: &'a Option<PathBuf>,
                               ast_map: &'a ast_map::Map<'ast>,
                               expanded_crate: &'a ast::Crate,
                               crate_name: &'a str)
@@ -302,7 +302,7 @@ fn state_after_write_deps(input: &'a Input,
 
     fn state_after_analysis(input: &'a Input,
                             session: &'a Session,
-                            out_dir: &'a Option<Path>,
+                            out_dir: &'a Option<PathBuf>,
                             expanded_crate: &'a ast::Crate,
                             analysis: &'a ty::CrateAnalysis<'tcx>,
                             tcx: &'a ty::ctxt<'tcx>)
@@ -318,7 +318,7 @@ fn state_after_analysis(input: &'a Input,
 
     fn state_after_llvm(input: &'a Input,
                         session: &'a Session,
-                        out_dir: &'a Option<Path>,
+                        out_dir: &'a Option<PathBuf>,
                         trans: &'a trans::CrateTranslation)
                         -> CompileState<'a, 'ast, 'tcx> {
         CompileState {
@@ -472,7 +472,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
             if cfg!(windows) {
                 _old_path = env::var_os("PATH").unwrap_or(_old_path);
                 let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
-                new_path.extend(os::split_paths(_old_path.to_str().unwrap()).into_iter());
+                new_path.extend(env::split_paths(&_old_path));
                 env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
             }
             let features = sess.features.borrow();
@@ -717,7 +717,7 @@ pub fn phase_5_run_llvm_passes(sess: &Session,
 
         // Remove assembly source, unless --save-temps was specified
         if !sess.opts.cg.save_temps {
-            fs::unlink(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
+            fs::remove_file(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
         }
     } else {
         time(sess.time_passes(), "LLVM passes", (), |_|
@@ -737,7 +737,7 @@ pub fn phase_6_link_output(sess: &Session,
                            outputs: &OutputFilenames) {
     let old_path = env::var_os("PATH").unwrap_or(OsString::from_str(""));
     let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
-    new_path.extend(os::split_paths(old_path.to_str().unwrap()).into_iter());
+    new_path.extend(env::split_paths(&old_path));
     env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
 
     time(sess.time_passes(), "linking", (), |_|
@@ -793,17 +793,17 @@ fn write_out_deps(sess: &Session,
         _ => return,
     };
 
-    let result = (|| -> old_io::IoResult<()> {
+    let result = (|| -> io::Result<()> {
         // Build a list of files used to compile the output and
         // write Makefile-compatible dependency rules
         let files: Vec<String> = sess.codemap().files.borrow()
                                    .iter().filter(|fmap| fmap.is_real_file())
                                    .map(|fmap| escape_dep_filename(&fmap.name))
                                    .collect();
-        let mut file = try!(old_io::File::create(&deps_filename));
+        let mut file = try!(fs::File::create(&deps_filename));
         for path in &out_filenames {
-            try!(write!(&mut file as &mut Writer,
-                          "{}: {}\n\n", path.display(), files.connect(" ")));
+            try!(write!(&mut file,
+                        "{}: {}\n\n", path.display(), files.connect(" ")));
         }
         Ok(())
     })();
@@ -896,8 +896,8 @@ pub fn collect_crate_metadata(session: &Session,
 }
 
 pub fn build_output_filenames(input: &Input,
-                              odir: &Option<Path>,
-                              ofile: &Option<Path>,
+                              odir: &Option<PathBuf>,
+                              ofile: &Option<PathBuf>,
                               attrs: &[ast::Attribute],
                               sess: &Session)
                            -> OutputFilenames {
@@ -908,7 +908,7 @@ pub fn build_output_filenames(input: &Input,
             // We want to toss everything after the final '.'
             let dirpath = match *odir {
                 Some(ref d) => d.clone(),
-                None => Path::new(".")
+                None => PathBuf::new(".")
             };
 
             // If a crate name is present, we use it as the link name
@@ -936,8 +936,9 @@ pub fn build_output_filenames(input: &Input,
                 sess.warn("ignoring --out-dir flag due to -o flag.");
             }
             OutputFilenames {
-                out_directory: out_file.dir_path(),
-                out_filestem: out_file.filestem_str().unwrap().to_string(),
+                out_directory: out_file.parent().unwrap().to_path_buf(),
+                out_filestem: out_file.file_stem().unwrap()
+                                      .to_str().unwrap().to_string(),
                 single_output_file: ofile,
                 extra: sess.opts.cg.extra_filename.clone(),
             }
index 15fae351ddbf21d8b3fe2bf19038a34b1da71969..aa8b7c7785d204b6c61b64a3d22b4396d885229c 100644 (file)
@@ -30,7 +30,6 @@
 #![feature(old_io)]
 #![feature(libc)]
 #![feature(os)]
-#![feature(old_path)]
 #![feature(quote)]
 #![feature(rustc_diagnostic_macros)]
 #![feature(rustc_private)]
@@ -38,6 +37,9 @@
 #![feature(staged_api)]
 #![feature(unicode)]
 #![feature(exit_status)]
+#![feature(path)]
+#![feature(io)]
+#![feature(fs)]
 
 extern crate arena;
 extern crate flate;
 use rustc::util::common::time;
 
 use std::cmp::Ordering::Equal;
-use std::old_io::{self, stdio};
-use std::iter::repeat;
 use std::env;
+use std::iter::repeat;
+use std::old_io::{self, stdio};
+use std::path::PathBuf;
 use std::sync::mpsc::channel;
 use std::thread;
 
@@ -159,14 +162,14 @@ macro_rules! do_or_return {($expr: expr) => {
 }
 
 // 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));
+fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
+    let odir = matches.opt_str("out-dir").map(|o| PathBuf::new(&o));
+    let ofile = matches.opt_str("o").map(|o| PathBuf::new(&o));
     (odir, ofile)
 }
 
 // Extract input (string or file and optional path) from matches.
-fn make_input(free_matches: &[String]) -> Option<(Input, Option<Path>)> {
+fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
     if free_matches.len() == 1 {
         let ifile = &free_matches[0][..];
         if ifile == "-" {
@@ -174,7 +177,7 @@ fn make_input(free_matches: &[String]) -> Option<(Input, Option<Path>)> {
             let src = String::from_utf8(contents).unwrap();
             Some((Input::Str(src), None))
         } else {
-            Some((Input::File(Path::new(ifile)), Some(Path::new(ifile))))
+            Some((Input::File(PathBuf::new(ifile)), Some(PathBuf::new(ifile))))
         }
     } else {
         None
@@ -215,14 +218,15 @@ fn late_callback(&mut self,
                      &getopts::Matches,
                      &Session,
                      &Input,
-                     &Option<Path>,
-                     &Option<Path>)
+                     &Option<PathBuf>,
+                     &Option<PathBuf>)
                      -> 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>) {
+    fn some_input(&mut self, input: Input, input_path: Option<PathBuf>)
+                  -> (Input, Option<PathBuf>) {
         (input, input_path)
     }
 
@@ -234,10 +238,10 @@ fn some_input(&mut self, input: Input, input_path: Option<Path>) -> (Input, Opti
     fn no_input(&mut self,
                 &getopts::Matches,
                 &config::Options,
-                &Option<Path>,
-                &Option<Path>,
+                &Option<PathBuf>,
+                &Option<PathBuf>,
                 &diagnostics::registry::Registry)
-                -> Option<(Input, Option<Path>)>;
+                -> Option<(Input, Option<PathBuf>)>;
 
     // Parse pretty printing information from the arguments. The implementer can
     // choose to ignore this (the default will return None) which will skip pretty
@@ -293,10 +297,10 @@ fn early_callback(&mut self,
     fn no_input(&mut self,
                 matches: &getopts::Matches,
                 sopts: &config::Options,
-                odir: &Option<Path>,
-                ofile: &Option<Path>,
+                odir: &Option<PathBuf>,
+                ofile: &Option<PathBuf>,
                 descriptions: &diagnostics::registry::Registry)
-                -> Option<(Input, Option<Path>)> {
+                -> Option<(Input, Option<PathBuf>)> {
         match matches.free.len() {
             0 => {
                 if sopts.describe_lints {
@@ -346,8 +350,8 @@ fn late_callback(&mut self,
                      matches: &getopts::Matches,
                      sess: &Session,
                      input: &Input,
-                     odir: &Option<Path>,
-                     ofile: &Option<Path>)
+                     odir: &Option<PathBuf>,
+                     ofile: &Option<PathBuf>)
                      -> Compilation {
         RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile).and_then(
             || RustcDefaultCalls::list_metadata(sess, matches, input))
@@ -400,11 +404,12 @@ pub fn list_metadata(sess: &Session,
         if r.contains(&("ls".to_string())) {
             match input {
                 &Input::File(ref ifile) => {
-                    let mut stdout = old_io::stdout();
                     let path = &(*ifile);
+                    let mut v = Vec::new();
                     metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx,
                                                          path,
-                                                         &mut stdout).unwrap();
+                                                         &mut v).unwrap();
+                    println!("{}", String::from_utf8(v).unwrap());
                 }
                 &Input::Str(_) => {
                     early_error("cannot list metadata for stdin");
@@ -419,8 +424,8 @@ pub fn list_metadata(sess: &Session,
 
     fn print_crate_info(sess: &Session,
                         input: Option<&Input>,
-                        odir: &Option<Path>,
-                        ofile: &Option<Path>)
+                        odir: &Option<PathBuf>,
+                        ofile: &Option<PathBuf>)
                         -> Compilation {
         if sess.opts.prints.len() == 0 {
             return Compilation::Continue;
@@ -457,7 +462,8 @@ fn print_crate_info(sess: &Session,
                                                              style,
                                                              &id,
                                                              &t_outputs.with_extension(""));
-                        println!("{}", fname.filename_display());
+                        println!("{}", fname.file_name().unwrap()
+                                            .to_string_lossy());
                     }
                 }
             }
index 22473099baf60311fbe59b6e505a56a84e4ad35d..ffb2a05e4374920caea984151cfd91c1b135aa00 100644 (file)
 
 use graphviz as dot;
 
-use std::old_io::{self, MemReader};
+use std::fs::File;
+use std::io::{self, Write};
+use std::old_io;
 use std::option;
+use std::path::PathBuf;
 use std::str::FromStr;
 
 #[derive(Copy, PartialEq, Debug)]
@@ -208,7 +211,7 @@ fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
     fn pre(&self,
            s: &mut pprust::State,
-           node: pprust::AnnNode) -> old_io::IoResult<()> {
+           node: pprust::AnnNode) -> io::Result<()> {
         match node {
             pprust::NodeExpr(_) => s.popen(),
             _ => Ok(())
@@ -216,7 +219,7 @@ fn pre(&self,
     }
     fn post(&self,
             s: &mut pprust::State,
-            node: pprust::AnnNode) -> old_io::IoResult<()> {
+            node: pprust::AnnNode) -> io::Result<()> {
         match node {
             pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
 
@@ -259,7 +262,7 @@ fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
     fn post(&self,
             s: &mut pprust::State,
-            node: pprust::AnnNode) -> old_io::IoResult<()> {
+            node: pprust::AnnNode) -> io::Result<()> {
         match node {
             pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
                 try!(pp::space(&mut s.s));
@@ -294,7 +297,7 @@ fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
 impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
     fn pre(&self,
            s: &mut pprust::State,
-           node: pprust::AnnNode) -> old_io::IoResult<()> {
+           node: pprust::AnnNode) -> io::Result<()> {
         match node {
             pprust::NodeExpr(_) => s.popen(),
             _ => Ok(())
@@ -302,7 +305,7 @@ fn pre(&self,
     }
     fn post(&self,
             s: &mut pprust::State,
-            node: pprust::AnnNode) -> old_io::IoResult<()> {
+            node: pprust::AnnNode) -> io::Result<()> {
         let tcx = &self.analysis.ty_cx;
         match node {
             pprust::NodeExpr(expr) => {
@@ -507,7 +510,7 @@ pub fn pretty_print_input(sess: Session,
                           input: &Input,
                           ppm: PpMode,
                           opt_uii: Option<UserIdentifiedItem>,
-                          ofile: Option<Path>) {
+                          ofile: Option<PathBuf>) {
     let krate = driver::phase_1_parse_input(&sess, cfg, input);
 
     let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
@@ -542,25 +545,20 @@ pub fn pretty_print_input(sess: Session,
 
     let src_name = driver::source_name(input);
     let src = sess.codemap().get_filemap(&src_name[..])
-                            .src.as_bytes().to_vec();
-    let mut rdr = MemReader::new(src);
+                            .src
+                            .as_ref()
+                            .unwrap()
+                            .as_bytes()
+                            .to_vec();
+    let mut rdr = &src[..];
 
-    let out = match ofile {
-        None => box old_io::stdout() as Box<Writer+'static>,
-        Some(p) => {
-            let r = old_io::File::create(&p);
-            match r {
-                Ok(w) => box w as Box<Writer+'static>,
-                Err(e) => panic!("print-print failed to open {} due to {}",
-                                p.display(), e),
-            }
-        }
-    };
+    let mut out = Vec::new();
 
     match (ppm, opt_uii) {
-        (PpmSource(s), None) =>
+        (PpmSource(s), None) => {
+            let out: &mut Write = &mut out;
             s.call_with_pp_support(
-                sess, ast_map, &arenas, id, out, |annotation, out| {
+                sess, ast_map, &arenas, id, box out, |annotation, out| {
                     debug!("pretty printing source code {:?}", s);
                     let sess = annotation.sess();
                     pprust::print_crate(sess.codemap(),
@@ -571,9 +569,11 @@ pub fn pretty_print_input(sess: Session,
                                         out,
                                         annotation.pp_ann(),
                                         is_expanded)
-                }),
+            })
+        }
 
-        (PpmSource(s), Some(uii)) =>
+        (PpmSource(s), Some(uii)) => {
+            let out: &mut Write = &mut out;
             s.call_with_pp_support(
                 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
                     debug!("pretty printing source code {:?}", s);
@@ -585,7 +585,7 @@ pub fn pretty_print_input(sess: Session,
                                                       sess.diagnostic(),
                                                       src_name.to_string(),
                                                       &mut rdr,
-                                                      out,
+                                                      box out,
                                                       annotation.pp_ann(),
                                                       is_expanded);
                     for node_id in uii.all_matching_node_ids(ast_map) {
@@ -596,7 +596,8 @@ pub fn pretty_print_input(sess: Session,
                         try!(pp::hardbreak(&mut pp_state.s));
                     }
                     pp::eof(&mut pp_state.s)
-                }),
+                })
+        }
 
         (PpmFlowGraph(mode), opt_uii) => {
             debug!("pretty printing flow graph for {:?}", opt_uii);
@@ -614,6 +615,7 @@ pub fn pretty_print_input(sess: Session,
             });
 
             let code = blocks::Code::from_node(node);
+            let out: &mut Writer = &mut out;
             match code {
                 Some(code) => {
                     let variants = gather_flowgraph_variants(&sess);
@@ -638,14 +640,25 @@ pub fn pretty_print_input(sess: Session,
                 }
             }
         }
-    }.unwrap()
+    }.unwrap();
+
+    match ofile {
+        None => print!("{}", String::from_utf8(out).unwrap()),
+        Some(p) => {
+            match File::create(&p) {
+                Ok(mut w) => w.write_all(&out).unwrap(),
+                Err(e) => panic!("print-print failed to open {} due to {}",
+                                p.display(), e),
+            }
+        }
+    }
 }
 
 fn print_flowgraph<W:old_io::Writer>(variants: Vec<borrowck_dot::Variant>,
                                  analysis: ty::CrateAnalysis,
                                  code: blocks::Code,
                                  mode: PpFlowGraphMode,
-                                 mut out: W) -> old_io::IoResult<()> {
+                                 mut out: W) -> io::Result<()> {
     let ty_cx = &analysis.ty_cx;
     let cfg = match code {
         blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
@@ -685,17 +698,10 @@ fn print_flowgraph<W:old_io::Writer>(variants: Vec<borrowck_dot::Variant>,
         }
     }
 
-    fn expand_err_details(r: old_io::IoResult<()>) -> old_io::IoResult<()> {
+    fn expand_err_details(r: old_io::IoResult<()>) -> io::Result<()> {
         r.map_err(|ioerr| {
-            let orig_detail = ioerr.detail.clone();
-            let m = "graphviz::render failed";
-            old_io::IoError {
-                detail: Some(match orig_detail {
-                    None => m.to_string(),
-                    Some(d) => format!("{}: {}", m, d)
-                }),
-                ..ioerr
-            }
+            io::Error::new(io::ErrorKind::Other, "graphviz::render failed",
+                           Some(ioerr.to_string()))
         })
     }
 }
index 14a99026aac8ac18c8e06b377e68981ca534f52b..f54480e3e523c156554aaee021f3f70622930bb6 100644 (file)
@@ -16,6 +16,7 @@
 use std::ffi::CString;
 use std::mem;
 use std::raw;
+use std::path::Path;
 
 pub struct ArchiveRO {
     ptr: ArchiveRef,
@@ -29,14 +30,25 @@ impl ArchiveRO {
     /// If this archive is used with a mutable method, then an error will be
     /// raised.
     pub fn open(dst: &Path) -> Option<ArchiveRO> {
-        unsafe {
-            let s = CString::new(dst.as_vec()).unwrap();
+        return unsafe {
+            let s = path2cstr(dst);
             let ar = ::LLVMRustOpenArchive(s.as_ptr());
             if ar.is_null() {
                 None
             } else {
                 Some(ArchiveRO { ptr: ar })
             }
+        };
+
+        #[cfg(unix)]
+        fn path2cstr(p: &Path) -> CString {
+            use std::os::unix::prelude::*;
+            use std::ffi::AsOsStr;
+            CString::new(p.as_os_str().as_bytes()).unwrap()
+        }
+        #[cfg(windows)]
+        fn path2cstr(p: &Path) -> CString {
+            CString::new(p.to_str().unwrap()).unwrap()
         }
     }
 
index 09a187befb2130ec01ccb05fb84f16265d300e86..0a1416ff5664a02bcaec4445ec246da9cb708637 100644 (file)
@@ -28,9 +28,9 @@
 #![feature(int_uint)]
 #![feature(libc)]
 #![feature(link_args)]
-#![feature(old_path)]
 #![feature(staged_api)]
 #![feature(std_misc)]
+#![feature(path)]
 
 extern crate libc;
 #[macro_use] #[no_link] extern crate rustc_bitflags;
index 7b377ac3611b68131c002c8e235e77f530369571..1e84bc4b8e0bb197d8b2ae7cc0989c3829743a78 100644 (file)
 use util::ppaux;
 use util::sha2::{Digest, Sha256};
 
-use std::old_io::fs::PathExtensions;
-use std::old_io::{fs, TempDir, Command};
-use std::old_io;
+use std::ffi::{AsOsStr, OsString};
+use std::fs::{self, TempDir, PathExt};
+use std::io::{self, Read, Write};
 use std::mem;
+use std::path::{Path, PathBuf};
+use std::process::Command;
 use std::str;
-use std::string::String;
 use flate;
 use serialize::hex::ToHex;
 use syntax::ast;
@@ -156,7 +157,7 @@ pub fn find_crate_name(sess: Option<&Session>,
         return validate(s.to_string(), Some(attr.span));
     }
     if let Input::File(ref path) = *input {
-        if let Some(s) = path.filestem_str() {
+        if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
             return validate(s.to_string(), None);
         }
     }
@@ -356,7 +357,7 @@ pub fn get_cc_prog(sess: &Session) -> String {
 }
 
 pub fn remove(sess: &Session, path: &Path) {
-    match fs::unlink(path) {
+    match fs::remove_file(path) {
         Ok(..) => {}
         Err(e) => {
             sess.err(&format!("failed to remove {}: {}",
@@ -371,7 +372,7 @@ pub fn remove(sess: &Session, path: &Path) {
 pub fn link_binary(sess: &Session,
                    trans: &CrateTranslation,
                    outputs: &OutputFilenames,
-                   crate_name: &str) -> Vec<Path> {
+                   crate_name: &str) -> Vec<PathBuf> {
     let mut out_filenames = Vec::new();
     for &crate_type in &*sess.crate_types.borrow() {
         if invalid_output_for_target(sess, crate_type) {
@@ -425,35 +426,35 @@ pub fn invalid_output_for_target(sess: &Session,
 }
 
 fn is_writeable(p: &Path) -> bool {
-    match p.stat() {
+    match p.metadata() {
         Err(..) => true,
-        Ok(m) => m.perm & old_io::USER_WRITE == old_io::USER_WRITE
+        Ok(m) => !m.permissions().readonly()
     }
 }
 
 pub fn filename_for_input(sess: &Session,
                           crate_type: config::CrateType,
                           name: &str,
-                          out_filename: &Path) -> Path {
+                          out_filename: &Path) -> PathBuf {
     let libname = format!("{}{}", name, sess.opts.cg.extra_filename);
     match crate_type {
         config::CrateTypeRlib => {
-            out_filename.with_filename(format!("lib{}.rlib", libname))
+            out_filename.with_file_name(&format!("lib{}.rlib", libname))
         }
         config::CrateTypeDylib => {
             let (prefix, suffix) = (&sess.target.target.options.dll_prefix,
                                     &sess.target.target.options.dll_suffix);
-            out_filename.with_filename(format!("{}{}{}",
-                                               prefix,
-                                               libname,
-                                               suffix))
+            out_filename.with_file_name(&format!("{}{}{}",
+                                                  prefix,
+                                                 libname,
+                                                 suffix))
         }
         config::CrateTypeStaticlib => {
-            out_filename.with_filename(format!("lib{}.a", libname))
+            out_filename.with_file_name(&format!("lib{}.a", libname))
         }
         config::CrateTypeExecutable => {
             let suffix = &sess.target.target.options.exe_suffix;
-            out_filename.with_filename(format!("{}{}", libname, suffix))
+            out_filename.with_file_name(&format!("{}{}", libname, suffix))
         }
     }
 }
@@ -462,7 +463,7 @@ fn link_binary_output(sess: &Session,
                       trans: &CrateTranslation,
                       crate_type: config::CrateType,
                       outputs: &OutputFilenames,
-                      crate_name: &str) -> Path {
+                      crate_name: &str) -> PathBuf {
     let obj_filename = outputs.temp_path(OutputTypeObject);
     let out_filename = match outputs.single_output_file {
         Some(ref file) => file.clone(),
@@ -507,10 +508,10 @@ fn link_binary_output(sess: &Session,
     out_filename
 }
 
-fn archive_search_paths(sess: &Session) -> Vec<Path> {
+fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
     let mut search = Vec::new();
     sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
-        search.push(path.clone());
+        search.push(path.to_path_buf());
         FileDoesntMatch
     });
     return search;
@@ -529,7 +530,7 @@ fn link_rlib<'a>(sess: &'a Session,
     let handler = &sess.diagnostic().handler;
     let config = ArchiveConfig {
         handler: handler,
-        dst: out_filename.clone(),
+        dst: out_filename.to_path_buf(),
         lib_search_paths: archive_search_paths(sess),
         slib_prefix: sess.target.target.options.staticlib_prefix.clone(),
         slib_suffix: sess.target.target.options.staticlib_suffix.clone(),
@@ -588,7 +589,9 @@ fn link_rlib<'a>(sess: &'a Session,
             // the same filename for metadata (stomping over one another)
             let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
             let metadata = tmpdir.path().join(METADATA_FILENAME);
-            match fs::File::create(&metadata).write_all(&trans.metadata) {
+            match fs::File::create(&metadata).and_then(|mut f| {
+                f.write_all(&trans.metadata)
+            }) {
                 Ok(..) => {}
                 Err(e) => {
                     sess.err(&format!("failed to write {}: {}",
@@ -613,28 +616,32 @@ fn link_rlib<'a>(sess: &'a Session,
                 let bc_deflated_filename = obj_filename.with_extension(
                     &format!("{}.bytecode.deflate", i));
 
-                let bc_data = match fs::File::open(&bc_filename).read_to_end() {
-                    Ok(buffer) => buffer,
+                let mut bc_data = Vec::new();
+                match fs::File::open(&bc_filename).and_then(|mut f| {
+                    f.read_to_end(&mut bc_data)
+                }) {
+                    Ok(..) => {}
                     Err(e) => sess.fatal(&format!("failed to read bytecode: {}",
                                                  e))
-                };
+                }
 
                 let bc_data_deflated = match flate::deflate_bytes(&bc_data[..]) {
                     Some(compressed) => compressed,
-                    None => sess.fatal(&format!("failed to compress bytecode from {}",
-                                               bc_filename.display()))
+                    None => sess.fatal(&format!("failed to compress bytecode \
+                                                 from {}",
+                                                 bc_filename.display()))
                 };
 
                 let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) {
                     Ok(file) => file,
                     Err(e) => {
-                        sess.fatal(&format!("failed to create compressed bytecode \
-                                            file: {}", e))
+                        sess.fatal(&format!("failed to create compressed \
+                                             bytecode file: {}", e))
                     }
                 };
 
                 match write_rlib_bytecode_object_v1(&mut bc_file_deflated,
-                                                    bc_data_deflated.as_slice()) {
+                                                    &bc_data_deflated) {
                     Ok(()) => {}
                     Err(e) => {
                         sess.err(&format!("failed to write compressed bytecode: \
@@ -670,15 +677,23 @@ fn link_rlib<'a>(sess: &'a Session,
     ab
 }
 
-fn write_rlib_bytecode_object_v1<T: Writer>(writer: &mut T,
-                                            bc_data_deflated: &[u8])
-                                         -> ::std::old_io::IoResult<()> {
+fn write_rlib_bytecode_object_v1(writer: &mut Write,
+                                 bc_data_deflated: &[u8]) -> io::Result<()> {
     let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
 
-    try! { writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC) };
-    try! { writer.write_le_u32(1) };
-    try! { writer.write_le_u64(bc_data_deflated_size) };
-    try! { writer.write_all(&bc_data_deflated[..]) };
+    try!(writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC));
+    try!(writer.write_all(&[1, 0, 0, 0]));
+    try!(writer.write_all(&[
+        (bc_data_deflated_size >>  0) as u8,
+        (bc_data_deflated_size >>  8) as u8,
+        (bc_data_deflated_size >> 16) as u8,
+        (bc_data_deflated_size >> 24) as u8,
+        (bc_data_deflated_size >> 32) as u8,
+        (bc_data_deflated_size >> 40) as u8,
+        (bc_data_deflated_size >> 48) as u8,
+        (bc_data_deflated_size >> 56) as u8,
+    ]));
+    try!(writer.write_all(&bc_data_deflated));
 
     let number_of_bytes_written_so_far =
         RLIB_BYTECODE_OBJECT_MAGIC.len() +                // magic id
@@ -690,7 +705,7 @@ fn write_rlib_bytecode_object_v1<T: Writer>(writer: &mut T,
     // padding byte to make it even. This works around a crash bug in LLDB
     // (see issue #15950)
     if number_of_bytes_written_so_far % 2 == 1 {
-        try! { writer.write_u8(0) };
+        try!(writer.write_all(&[0]));
     }
 
     return Ok(());
@@ -796,13 +811,13 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
                                  pname,
                                  prog.status));
                 sess.note(&format!("{:?}", &cmd));
-                let mut output = prog.error.clone();
-                output.push_all(&prog.output);
+                let mut output = prog.stderr.clone();
+                output.push_all(&prog.stdout);
                 sess.note(str::from_utf8(&output[..]).unwrap());
                 sess.abort_if_errors();
             }
-            debug!("linker stderr:\n{}", String::from_utf8(prog.error).unwrap());
-            debug!("linker stdout:\n{}", String::from_utf8(prog.output).unwrap());
+            debug!("linker stderr:\n{}", String::from_utf8(prog.stderr).unwrap());
+            debug!("linker stdout:\n{}", String::from_utf8(prog.stdout).unwrap());
         },
         Err(e) => {
             sess.err(&format!("could not exec the linker `{}`: {}",
@@ -866,9 +881,9 @@ fn link_args(cmd: &mut Command,
         if t.options.is_like_osx {
             let morestack = lib_path.join("libmorestack.a");
 
-            let mut v = b"-Wl,-force_load,".to_vec();
-            v.push_all(morestack.as_vec());
-            cmd.arg(&v[..]);
+            let mut v = OsString::from_str("-Wl,-force_load,");
+            v.push_os_str(morestack.as_os_str());
+            cmd.arg(&v);
         } else {
             cmd.args(&["-Wl,--whole-archive", "-lmorestack", "-Wl,--no-whole-archive"]);
         }
@@ -878,7 +893,7 @@ fn link_args(cmd: &mut Command,
     // executable. This metadata is in a separate object file from the main
     // object file, so we link that in here.
     if dylib {
-        cmd.arg(obj_filename.with_extension("metadata.o"));
+        cmd.arg(&obj_filename.with_extension("metadata.o"));
     }
 
     if t.options.is_like_osx {
@@ -991,9 +1006,9 @@ fn link_args(cmd: &mut Command,
             cmd.args(&["-dynamiclib", "-Wl,-dylib"]);
 
             if sess.opts.cg.rpath {
-                let mut v = "-Wl,-install_name,@rpath/".as_bytes().to_vec();
-                v.push_all(out_filename.filename().unwrap());
-                cmd.arg(&v[..]);
+                let mut v = OsString::from_str("-Wl,-install_name,@rpath/");
+                v.push_os_str(out_filename.file_name().unwrap());
+                cmd.arg(&v);
             }
         } else {
             cmd.arg("-shared");
@@ -1006,23 +1021,23 @@ 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 mut get_install_prefix_lib_path = || {
             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
             let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
-            let mut path = Path::new(install_prefix);
+            let mut path = PathBuf::new(install_prefix);
             path.push(&tlib);
 
             path
         };
-        let rpath_config = RPathConfig {
+        let mut rpath_config = RPathConfig {
             used_crates: sess.cstore.get_used_crates(cstore::RequireDynamic),
-            out_filename: out_filename.clone(),
+            out_filename: out_filename.to_path_buf(),
             has_rpath: sess.target.target.options.has_rpath,
             is_like_osx: sess.target.target.options.is_like_osx,
-            get_install_prefix_lib_path: get_install_prefix_lib_path,
-            realpath: ::util::fs::realpath
+            get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
+            realpath: &mut ::util::fs::realpath
         };
-        cmd.args(&rpath::get_rpath_flags(rpath_config));
+        cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
     }
 
     // Finally add all the linker arguments provided on the command line along
@@ -1082,7 +1097,7 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
     let search_path = archive_search_paths(sess);
     for l in staticlibs {
         if takes_hints {
-            cmd.arg(format!("-l{}", l));
+            cmd.arg(&format!("-l{}", l));
         } else {
             // -force_load is the OSX equivalent of --whole-archive, but it
             // involves passing the full path to the library to link.
@@ -1091,9 +1106,9 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
                                             &sess.target.target.options.staticlib_suffix,
                                             &search_path[..],
                                             &sess.diagnostic().handler);
-            let mut v = b"-Wl,-force_load,".to_vec();
-            v.push_all(lib.as_vec());
-            cmd.arg(&v[..]);
+            let mut v = OsString::from_str("-Wl,-force_load,");
+            v.push_os_str(lib.as_os_str());
+            cmd.arg(&v);
         }
     }
     if takes_hints {
@@ -1103,7 +1118,7 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
     for &(ref l, kind) in others {
         match kind {
             cstore::NativeUnknown => {
-                cmd.arg(format!("-l{}", l));
+                cmd.arg(&format!("-l{}", l));
             }
             cstore::NativeFramework => {
                 cmd.arg("-framework").arg(&l[..]);
@@ -1150,18 +1165,18 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
         let src = sess.cstore.get_used_crate_source(cnum).unwrap();
         match kind {
             cstore::RequireDynamic => {
-                add_dynamic_crate(cmd, sess, src.dylib.unwrap().0)
+                add_dynamic_crate(cmd, sess, &src.dylib.unwrap().0)
             }
             cstore::RequireStatic => {
-                add_static_crate(cmd, sess, tmpdir, src.rlib.unwrap().0)
+                add_static_crate(cmd, sess, tmpdir, &src.rlib.unwrap().0)
             }
         }
 
     }
 
     // Converts a library file-stem into a cc -l argument
-    fn unlib<'a>(config: &config::Config, stem: &'a [u8]) -> &'a [u8] {
-        if stem.starts_with("lib".as_bytes()) && !config.target.options.is_like_windows {
+    fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
+        if stem.starts_with("lib") && !config.target.options.is_like_windows {
             &stem[3..]
         } else {
             stem
@@ -1170,7 +1185,7 @@ fn unlib<'a>(config: &config::Config, stem: &'a [u8]) -> &'a [u8] {
 
     // Adds the static "rlib" versions of all crates to the command line.
     fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
-                        cratepath: Path) {
+                        cratepath: &Path) {
         // When performing LTO on an executable output, all of the
         // bytecode from the upstream libraries has already been
         // included in our object file output. We need to modify all of
@@ -1186,12 +1201,12 @@ fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
         // If we're not doing LTO, then our job is simply to just link
         // against the archive.
         if sess.lto() {
-            let name = cratepath.filename_str().unwrap();
+            let name = cratepath.file_name().unwrap().to_str().unwrap();
             let name = &name[3..name.len() - 5]; // chop off lib/.rlib
             time(sess.time_passes(),
                  &format!("altering {}.rlib", name),
                  (), |()| {
-                let dst = tmpdir.join(cratepath.filename().unwrap());
+                let dst = tmpdir.join(cratepath.file_name().unwrap());
                 match fs::copy(&cratepath, &dst) {
                     Ok(..) => {}
                     Err(e) => {
@@ -1205,7 +1220,11 @@ fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
                 // Fix up permissions of the copy, as fs::copy() preserves
                 // permissions, but the original file may have been installed
                 // by a package manager and may be read-only.
-                match fs::chmod(&dst, old_io::USER_READ | old_io::USER_WRITE) {
+                match fs::metadata(&dst).and_then(|m| {
+                    let mut perms = m.permissions();
+                    perms.set_readonly(false);
+                    fs::set_permissions(&dst, perms)
+                }) {
                     Ok(..) => {}
                     Err(e) => {
                         sess.err(&format!("failed to chmod {} when preparing \
@@ -1227,7 +1246,7 @@ fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
                 archive.remove_file(&format!("{}.o", name));
                 let files = archive.files();
                 if files.iter().any(|s| s.ends_with(".o")) {
-                    cmd.arg(dst);
+                    cmd.arg(&dst);
                 }
             });
         } else {
@@ -1236,19 +1255,18 @@ fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
     }
 
     // Same thing as above, but for dynamic crates instead of static crates.
-    fn add_dynamic_crate(cmd: &mut Command, sess: &Session, cratepath: Path) {
+    fn add_dynamic_crate(cmd: &mut Command, sess: &Session, cratepath: &Path) {
         // If we're performing LTO, then it should have been previously required
         // that all upstream rust dependencies were available in an rlib format.
         assert!(!sess.lto());
 
         // Just need to tell the linker about where the library lives and
         // what its name is
-        let dir = cratepath.dirname();
-        if !dir.is_empty() { cmd.arg("-L").arg(dir); }
-
-        let mut v = "-l".as_bytes().to_vec();
-        v.push_all(unlib(&sess.target, cratepath.filestem().unwrap()));
-        cmd.arg(&v[..]);
+        if let Some(dir) = cratepath.parent() {
+            cmd.arg("-L").arg(dir);
+        }
+        let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
+        cmd.arg(&format!("-l{}", unlib(&sess.target, filestem)));
     }
 }
 
@@ -1286,7 +1304,7 @@ fn add_upstream_native_libraries(cmd: &mut Command, sess: &Session) {
         for &(kind, ref lib) in &libs {
             match kind {
                 cstore::NativeUnknown => {
-                    cmd.arg(format!("-l{}", *lib));
+                    cmd.arg(&format!("-l{}", *lib));
                 }
                 cstore::NativeFramework => {
                     cmd.arg("-framework");
index d8a296bf0410cdde29e5c64362037ecc5b009937..db9966e05487d4466ab2ab5398fa0e0a9a9211a1 100644 (file)
@@ -59,7 +59,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
         };
 
         let archive = ArchiveRO::open(&path).expect("wanted an rlib");
-        let file = path.filename_str().unwrap();
+        let file = path.file_name().unwrap().to_str().unwrap();
         let file = &file[3..file.len() - 5]; // chop off lib/.rlib
         debug!("reading {}", file);
         for i in iter::count(0, 1) {
index cd14fe529b1a7b45453c19a141c7d168116b2b5a..156cfa6c4b23a852ebd6076da31617770f1b55a0 100644 (file)
 use llvm::SMDiagnosticRef;
 use trans::{CrateTranslation, ModuleTranslation};
 use util::common::time;
+use util::common::path2cstr;
 use syntax::codemap;
 use syntax::diagnostic;
 use syntax::diagnostic::{Emitter, Handler, Level, mk_handler};
 
 use std::ffi::{CStr, CString};
-use std::old_io::Command;
-use std::old_io::fs;
+use std::fs;
 use std::iter::Unfold;
+use std::mem;
+use std::path::Path;
+use std::process::{Command, Stdio};
 use std::ptr;
 use std::str;
-use std::mem;
 use std::sync::{Arc, Mutex};
 use std::sync::mpsc::channel;
 use std::thread;
@@ -67,7 +69,7 @@ pub fn write_output_file(
         output: &Path,
         file_type: llvm::FileType) {
     unsafe {
-        let output_c = CString::new(output.as_vec()).unwrap();
+        let output_c = path2cstr(output);
         let result = llvm::LLVMRustWriteOutputFile(
                 target, pm, m, output_c.as_ptr(), file_type);
         if !result {
@@ -424,7 +426,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);
-        let out = CString::new(out.as_vec()).unwrap();
+        let out = path2cstr(&out);
         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
     }
 
@@ -477,7 +479,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);
-                        let out = CString::new(out.as_vec()).unwrap();
+                        let out = path2cstr(&out);
                         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
                     }
                 },
@@ -511,7 +513,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);
-        let out = CString::new(out.as_vec()).unwrap();
+        let out = path2cstr(&out);
         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
     }
 
@@ -519,7 +521,7 @@ unsafe fn with_codegen<F>(tm: TargetMachineRef,
         if config.emit_ir {
             let ext = format!("{}.ll", name_extra);
             let out = output_names.with_extension(&ext);
-            let out = CString::new(out.as_vec()).unwrap();
+            let out = path2cstr(&out);
             with_codegen(tm, llmod, config.no_builtins, |cpm| {
                 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
             })
@@ -717,12 +719,11 @@ pub fn run_passes(sess: &Session,
         cmd.arg("-nostdlib");
 
         for index in 0..trans.modules.len() {
-            cmd.arg(crate_output.with_extension(&format!("{}.o", index)));
+            cmd.arg(&crate_output.with_extension(&format!("{}.o", index)));
         }
 
-        cmd.arg("-r")
-           .arg("-o")
-           .arg(windows_output_path.as_ref().unwrap_or(output_path));
+        cmd.arg("-r").arg("-o")
+           .arg(windows_output_path.as_ref().map(|s| &**s).unwrap_or(output_path));
 
         cmd.args(&sess.target.target.options.post_link_args);
 
@@ -730,9 +731,7 @@ pub fn run_passes(sess: &Session,
             println!("{:?}", &cmd);
         }
 
-        cmd.stdin(::std::old_io::process::Ignored)
-           .stdout(::std::old_io::process::InheritFd(1))
-           .stderr(::std::old_io::process::InheritFd(2));
+        cmd.stdin(Stdio::null());
         match cmd.status() {
             Ok(status) => {
                 if !status.success() {
@@ -964,9 +963,9 @@ pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
     let pname = get_cc_prog(sess);
     let mut cmd = Command::new(&pname[..]);
 
-    cmd.arg("-c").arg("-o").arg(outputs.path(config::OutputTypeObject))
-                           .arg(outputs.temp_path(config::OutputTypeAssembly));
-    debug!("{:?}", &cmd);
+    cmd.arg("-c").arg("-o").arg(&outputs.path(config::OutputTypeObject))
+                           .arg(&outputs.temp_path(config::OutputTypeAssembly));
+    debug!("{:?}", cmd);
 
     match cmd.output() {
         Ok(prog) => {
@@ -975,8 +974,8 @@ pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
                                  pname,
                                  prog.status));
                 sess.note(&format!("{:?}", &cmd));
-                let mut note = prog.error.clone();
-                note.push_all(&prog.output);
+                let mut note = prog.stderr.clone();
+                note.push_all(&prog.stdout);
                 sess.note(str::from_utf8(&note[..]).unwrap());
                 sess.abort_if_errors();
             }
index 71317d5875b84fcdb1d3351632dfd0fa0dae1c06..dcc79e90cc5722556f44c2bc140e363a1c53a581 100644 (file)
@@ -29,9 +29,7 @@
 #![feature(collections)]
 #![feature(core)]
 #![feature(int_uint)]
-#![feature(old_io)]
 #![feature(libc)]
-#![feature(old_path)]
 #![feature(quote)]
 #![feature(rustc_diagnostic_macros)]
 #![feature(rustc_private)]
 #![feature(staged_api)]
 #![feature(std_misc)]
 #![feature(unicode)]
+#![feature(io)]
+#![feature(fs)]
+#![feature(path)]
+#![feature(os)]
+#![feature(tempdir)]
 
 extern crate arena;
 extern crate flate;
index 371b9268fba0de800de32544ce97f95de7f9b707..3c6cb5f9de9892f6f040aaf47be27ce8bb8d3baa 100644 (file)
@@ -33,8 +33,9 @@
 use middle::ty::{self, Ty};
 
 use std::cell::Cell;
-use std::old_io::{self, File, fs};
 use std::env;
+use std::fs::{self, File};
+use std::path::{Path, PathBuf};
 
 use syntax::ast_util::{self, PostExpansionMethod};
 use syntax::ast::{self, NodeId, DefId};
@@ -1537,6 +1538,7 @@ fn visit_local(&mut self, l: &ast::Local) {
     }
 }
 
+#[allow(deprecated)]
 pub fn process_crate(sess: &Session,
                      krate: &ast::Crate,
                      analysis: &ty::CrateAnalysis,
@@ -1557,15 +1559,15 @@ pub fn process_crate(sess: &Session,
     info!("Dumping crate {}", cratename);
 
     // find a path to dump our data to
-    let mut root_path = match env::var("DXR_RUST_TEMP_FOLDER") {
-        Ok(val) => Path::new(val),
-        Err(..) => match odir {
+    let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
+        Some(val) => PathBuf::new(&val),
+        None => match odir {
             Some(val) => val.join("dxr"),
-            None => Path::new("dxr-temp"),
+            None => PathBuf::new("dxr-temp"),
         },
     };
 
-    match fs::mkdir_recursive(&root_path, old_io::USER_RWX) {
+    match fs::create_dir_all(&root_path) {
         Err(e) => sess.err(&format!("Could not create directory {}: {}",
                            root_path.display(), e)),
         _ => (),
@@ -1579,7 +1581,7 @@ pub fn process_crate(sess: &Session,
     // Create output file.
     let mut out_name = cratename.clone();
     out_name.push_str(".csv");
-    root_path.push(out_name);
+    root_path.push(&out_name);
     let output_file = match File::create(&root_path) {
         Ok(f) => box f,
         Err(e) => {
@@ -1595,7 +1597,7 @@ pub fn process_crate(sess: &Session,
         collected_paths: vec!(),
         collecting: false,
         fmt: FmtStrs::new(box Recorder {
-                            out: output_file as Box<Writer+'static>,
+                            out: output_file,
                             dump_spans: false,
                         },
                         SpanUtils {
index 937f2d07677aa790141757ee034ee08135735f5f..f7c0d6a983fb77899f9f9aef1e284b02bd13fd28 100644 (file)
@@ -13,7 +13,7 @@
 use super::escape;
 use super::span_utils::SpanUtils;
 
-use std::vec::Vec;
+use std::io::Write;
 
 use syntax::ast;
 use syntax::ast::{NodeId,DefId};
@@ -23,7 +23,7 @@
 
 pub struct Recorder {
     // output file
-    pub out: Box<Writer+'static>,
+    pub out: Box<Write+'static>,
     pub dump_spans: bool,
 }
 
index 2c92f11c4e7067cefb695fdce0be16be2abe550a..13f882bc36318c79d895c651c043158505afdb6b 100644 (file)
@@ -2969,7 +2969,7 @@ pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
     }
 
     let encode_inlined_item: encoder::EncodeInlinedItem =
-        box |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii);
+        Box::new(|ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii));
 
     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
     let metadata = encoder::encode_metadata(encode_parms, krate);
index f3b7058336b2fc350bf0a0257606a5a508976314..142262a25bd437982e5f299ec93ac7c240e43d36 100644 (file)
 use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
 use util::nodemap::{DefIdMap, NodeMap, FnvHashMap, FnvHashSet};
 use util::ppaux;
+use util::common::path2cstr;
 
 use libc::{c_uint, c_longlong};
-use std::ffi::CString;
 use std::cell::{Cell, RefCell};
+use std::ffi::CString;
+use std::path::Path;
 use std::ptr;
 use std::rc::{Rc, Weak};
 use syntax::util::interner::Interner;
@@ -1588,20 +1590,13 @@ fn compile_unit_metadata(cx: &CrateContext) -> DIDescriptor {
                 cx.sess().warn("debuginfo: Invalid path to crate's local root source file!");
                 fallback_path(cx)
             } else {
-                match abs_path.path_relative_from(work_dir) {
+                match abs_path.relative_from(work_dir) {
                     Some(ref p) if p.is_relative() => {
-                        // prepend "./" if necessary
-                        let dotdot = b"..";
-                        let prefix: &[u8] = &[dotdot[0], ::std::old_path::SEP_BYTE];
-                        let mut path_bytes = p.as_vec().to_vec();
-
-                        if &path_bytes[..2] != prefix &&
-                           &path_bytes[..2] != dotdot {
-                            path_bytes.insert(0, prefix[0]);
-                            path_bytes.insert(1, prefix[1]);
+                        if p.starts_with(Path::new("./")) {
+                            path2cstr(p)
+                        } else {
+                            path2cstr(&Path::new(".").join(p))
                         }
-
-                        CString::new(path_bytes).unwrap()
                     }
                     _ => fallback_path(cx)
                 }
@@ -1614,7 +1609,7 @@ fn compile_unit_metadata(cx: &CrateContext) -> DIDescriptor {
                            (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
 
     let compile_unit_name = compile_unit_name.as_ptr();
-    let work_dir = CString::new(work_dir.as_vec()).unwrap();
+    let work_dir = path2cstr(&work_dir);
     let producer = CString::new(producer).unwrap();
     let flags = "\0";
     let split_name = "\0";
@@ -1716,7 +1711,7 @@ fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile {
     debug!("file_metadata: {}", full_path);
 
     // FIXME (#9639): This needs to handle non-utf8 paths
-    let work_dir = cx.sess().working_dir.as_str().unwrap();
+    let work_dir = cx.sess().working_dir.to_str().unwrap();
     let file_name =
         if full_path.starts_with(work_dir) {
             &full_path[work_dir.len() + 1..full_path.len()]
index 56fda20e0e8dcdc79d666da21b94e4f10247fc32..14f92334073720d38d212e1d787cf1641408b517 100644 (file)
@@ -40,7 +40,7 @@ fn instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId)
     let csearch_result =
         csearch::maybe_get_item_ast(
             ccx.tcx(), fn_id,
-            box |a,b,c,d| astencode::decode_inlined_item(a, b, c, d));
+            Box::new(|a,b,c,d| astencode::decode_inlined_item(a, b, c, d)));
 
     let inline_def = match csearch_result {
         csearch::FoundAst::NotFound => {
index f9495af79c5b0c5969a5bba8a2d157ee272eb39d..f31dbf5138bb601ce6f6e13689cdec546055624b 100644 (file)
@@ -152,12 +152,12 @@ fn try_overloaded_call_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                                                                           &closure_ty.sig).0;
                 fcx.record_deferred_call_resolution(
                     def_id,
-                    box CallResolution {call_expr: call_expr,
-                                        callee_expr: callee_expr,
-                                        adjusted_ty: adjusted_ty,
-                                        autoderefref: autoderefref,
-                                        fn_sig: fn_sig.clone(),
-                                        closure_def_id: def_id});
+                    Box::new(CallResolution {call_expr: call_expr,
+                                         callee_expr: callee_expr,
+                                         adjusted_ty: adjusted_ty,
+                                         autoderefref: autoderefref,
+                                         fn_sig: fn_sig.clone(),
+                                         closure_def_id: def_id}));
                 return Some(CallStep::DeferredClosure(fn_sig));
             }
         }
index 36d39fa58ba7e5ec7e23a8bcc5cc2c595e59f341..c39451b15ada5c8334e9d93a50604008598caaca 100644 (file)
@@ -49,7 +49,7 @@
 
 use std::rc::Rc;
 use std::u32;
-use std::old_path::Path as FsPath; // Conflicts with Path struct
+use std::path::PathBuf;
 
 use core::DocContext;
 use doctree;
@@ -118,7 +118,7 @@ fn clean(&self, cx: &DocContext) -> Vec<U> {
 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
 pub struct Crate {
     pub name: String,
-    pub src: FsPath,
+    pub src: PathBuf,
     pub module: Option<Item>,
     pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
     pub primitives: Vec<PrimitiveType>,
@@ -191,7 +191,7 @@ fn clean(&self, cx: &DocContext) -> Crate {
 
         let src = match cx.input {
             Input::File(ref path) => path.clone(),
-            Input::Str(_) => FsPath::new("") // FIXME: this is wrong
+            Input::Str(_) => PathBuf::new("") // FIXME: this is wrong
         };
 
         Crate {
index 942aec7d22f2c0bff99a4faaab2fce803e7cb477..6cfe7a33dd4f366b285c4991f29f755dabec38d5 100644 (file)
@@ -8,7 +8,12 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use std::{old_io, str};
+use std::fs::File;
+use std::io::prelude::*;
+use std::io;
+use std::old_io;
+use std::path::{PathBuf, Path};
+use std::str;
 
 #[derive(Clone)]
 pub struct ExternalHtml{
@@ -33,16 +38,17 @@ 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());
+pub fn load_string(input: &Path) -> io::Result<Option<String>> {
+    let mut f = try!(File::open(input));
+    let mut d = Vec::new();
+    try!(f.read_to_end(&mut d));
     Ok(str::from_utf8(&d).map(|s| s.to_string()).ok())
 }
 
 macro_rules! load_or_return {
     ($input: expr, $cant_read: expr, $not_utf8: expr) => {
         {
-            let input = Path::new($input);
+            let input = PathBuf::new($input);
             match ::externalfiles::load_string(&input) {
                 Err(e) => {
                     let _ = writeln!(&mut old_io::stderr(),
index 79e348cb03e49296912d38208064c976db4d1c19..51c58861b4b252b66ea31d3b4d9a78de7a3e45ae 100644 (file)
@@ -20,7 +20,9 @@
 
 #[cfg(unix)]
 mod imp {
-    use std::ffi::CString;
+    use std::ffi::{AsOsStr, CString};
+    use std::os::unix::prelude::*;
+    use std::path::Path;
     use libc;
     use std::os as stdos;
 
@@ -114,7 +116,7 @@ pub struct Lock {
 
     impl Lock {
         pub fn new(p: &Path) -> Lock {
-            let buf = CString::new(p.as_vec()).unwrap();
+            let buf = CString::new(p.as_os_str().as_bytes()).unwrap();
             let fd = unsafe {
                 libc::open(buf.as_ptr(), libc::O_RDWR | libc::O_CREAT,
                            libc::S_IRWXU)
@@ -163,8 +165,11 @@ fn drop(&mut self) {
 #[cfg(windows)]
 mod imp {
     use libc;
+    use std::ffi::AsOsStr;
     use std::mem;
+    use std::os::windows::prelude::*;
     use std::os;
+    use std::path::Path;
     use std::ptr;
 
     const LOCKFILE_EXCLUSIVE_LOCK: libc::DWORD = 0x00000002;
@@ -190,7 +195,7 @@ pub struct Lock {
 
     impl Lock {
         pub fn new(p: &Path) -> Lock {
-            let mut p_16: Vec<u16> = p.as_str().unwrap().utf16_units().collect();
+            let mut p_16: Vec<_> = p.as_os_str().encode_wide().collect();
             p_16.push(0);
             let handle = unsafe {
                 libc::CreateFileW(p_16.as_ptr(),
index c537e370723d7ca2526e0fc2cbbac25c9f7eeb19..3acd17dedd59d986503814984c474860e70d2f78 100644 (file)
@@ -9,7 +9,8 @@
 // except according to those terms.
 
 use std::fmt;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
 
 use externalfiles::ExternalHtml;
 
@@ -31,8 +32,8 @@ pub struct Page<'a> {
 }
 
 pub fn render<T: fmt::Display, S: fmt::Display>(
-    dst: &mut old_io::Writer, layout: &Layout, page: &Page, sidebar: &S, t: &T)
-    -> old_io::IoResult<()>
+    dst: &mut io::Write, layout: &Layout, page: &Page, sidebar: &S, t: &T)
+    -> io::Result<()>
 {
     write!(dst,
 r##"<!DOCTYPE html>
@@ -159,7 +160,7 @@ pub fn render<T: fmt::Display, S: fmt::Display>(
     )
 }
 
-pub fn redirect(dst: &mut old_io::Writer, url: &str) -> old_io::IoResult<()> {
+pub fn redirect(dst: &mut io::Write, url: &str) -> io::Result<()> {
     // <script> triggers a redirect before refresh, so this is fine.
     write!(dst,
 r##"<!DOCTYPE html>
index 735487611dc50d522a13a2ae0ebf4b67e0fc50e6..add44769bab60fff1ca052786349c8670b4a85eb 100644 (file)
 use std::cmp::Ordering;
 use std::collections::{HashMap, HashSet};
 use std::default::Default;
+use std::ffi::OsStr;
 use std::fmt;
-use std::old_io::fs::PathExtensions;
-use std::old_io::{fs, File, BufferedWriter, BufferedReader};
-use std::old_io;
+use std::fs::{self, File};
+use std::io::prelude::*;
+use std::io::{self, BufWriter, BufReader};
 use std::iter::repeat;
+use std::path::{PathBuf, Path};
 use std::str;
 use std::sync::Arc;
 
@@ -89,10 +91,10 @@ pub struct Context {
     pub root_path: String,
     /// The path to the crate root source minus the file name.
     /// Used for simplifying paths to the highlighted source code files.
-    pub src_root: Path,
+    pub src_root: PathBuf,
     /// The current destination folder of where HTML artifacts should be placed.
     /// This changes as the context descends into the module hierarchy.
-    pub dst: Path,
+    pub dst: PathBuf,
     /// This describes the layout of each page, and is not modified after
     /// creation of the context (contains info like the favicon and added html).
     pub layout: layout::Layout,
@@ -220,7 +222,7 @@ struct SourceCollector<'a> {
     /// Processed source-file paths
     seen: HashSet<String>,
     /// Root destination to place all HTML output into
-    dst: Path,
+    dst: PathBuf,
 }
 
 /// Wrapper struct to render the source code of a file. This will do things like
@@ -257,11 +259,15 @@ struct IndexItem {
 /// Generates the documentation for `crate` into the directory `dst`
 pub fn run(mut krate: clean::Crate,
            external_html: &ExternalHtml,
-           dst: Path,
-           passes: HashSet<String>) -> old_io::IoResult<()> {
+           dst: PathBuf,
+           passes: HashSet<String>) -> io::Result<()> {
+    let src_root = match krate.src.parent() {
+        Some(p) => p.to_path_buf(),
+        None => PathBuf::new(""),
+    };
     let mut cx = Context {
         dst: dst,
-        src_root: krate.src.dir_path(),
+        src_root: src_root,
         passes: passes,
         current: Vec::new(),
         root_path: String::new(),
@@ -392,7 +398,7 @@ pub fn run(mut krate: clean::Crate,
     cx.krate(krate, summary)
 }
 
-fn build_index(krate: &clean::Crate, cache: &mut Cache) -> old_io::IoResult<String> {
+fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::Result<String> {
     // Build the search index from the collected metadata
     let mut nodeid_to_pathid = HashMap::new();
     let mut pathid_to_nodeid = Vec::new();
@@ -437,7 +443,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> old_io::IoResult<Stri
     }
 
     // Collect the index into a string
-    let mut w = Vec::new();
+    let mut w = io::Cursor::new(Vec::new());
     try!(write!(&mut w, r#"searchIndex['{}'] = {{"items":["#, krate.name));
 
     let mut lastpath = "".to_string();
@@ -480,13 +486,13 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> old_io::IoResult<Stri
 
     try!(write!(&mut w, "]}};"));
 
-    Ok(String::from_utf8(w).unwrap())
+    Ok(String::from_utf8(w.into_inner()).unwrap())
 }
 
 fn write_shared(cx: &Context,
                 krate: &clean::Crate,
                 cache: &Cache,
-                search_index: String) -> old_io::IoResult<()> {
+                search_index: String) -> io::Result<()> {
     // Write out the shared files. Note that these are shared among all rustdoc
     // docs placed in the output directory, so this needs to be a synchronized
     // operation with respect to all other rustdocs running around.
@@ -518,10 +524,10 @@ fn write_shared(cx: &Context,
                include_bytes!("static/SourceCodePro-Semibold.woff")));
 
     fn collect(path: &Path, krate: &str,
-               key: &str) -> old_io::IoResult<Vec<String>> {
+               key: &str) -> io::Result<Vec<String>> {
         let mut ret = Vec::new();
         if path.exists() {
-            for line in BufferedReader::new(File::open(path)).lines() {
+            for line in BufReader::new(try!(File::open(path))).lines() {
                 let line = try!(line);
                 if !line.starts_with(key) {
                     continue
@@ -567,14 +573,14 @@ fn collect(path: &Path, krate: &str,
             mydst.push(part);
             try!(mkdir(&mydst));
         }
-        mydst.push(format!("{}.{}.js",
-                           remote_item_type.to_static_str(),
-                           remote_path[remote_path.len() - 1]));
+        mydst.push(&format!("{}.{}.js",
+                            remote_item_type.to_static_str(),
+                            remote_path[remote_path.len() - 1]));
         let all_implementors = try!(collect(&mydst, &krate.name,
                                             "implementors"));
 
-        try!(mkdir(&mydst.dir_path()));
-        let mut f = BufferedWriter::new(try!(File::create(&mydst)));
+        try!(mkdir(mydst.parent().unwrap()));
+        let mut f = BufWriter::new(try!(File::create(&mydst)));
         try!(writeln!(&mut f, "(function() {{var implementors = {{}};"));
 
         for implementor in &all_implementors {
@@ -606,7 +612,7 @@ fn collect(path: &Path, krate: &str,
 }
 
 fn render_sources(cx: &mut Context,
-                  krate: clean::Crate) -> old_io::IoResult<clean::Crate> {
+                  krate: clean::Crate) -> io::Result<clean::Crate> {
     info!("emitting source files");
     let dst = cx.dst.join("src");
     try!(mkdir(&dst));
@@ -624,15 +630,15 @@ fn render_sources(cx: &mut Context,
 
 /// Writes the entire contents of a string to a destination, not attempting to
 /// catch any errors.
-fn write(dst: Path, contents: &[u8]) -> old_io::IoResult<()> {
-    File::create(&dst).write_all(contents)
+fn write(dst: PathBuf, contents: &[u8]) -> io::Result<()> {
+    try!(File::create(&dst)).write_all(contents)
 }
 
 /// Makes a directory on the filesystem, failing the task if an error occurs and
 /// skipping if the directory already exists.
-fn mkdir(path: &Path) -> old_io::IoResult<()> {
+fn mkdir(path: &Path) -> io::Result<()> {
     if !path.exists() {
-        fs::mkdir(path, old_io::USER_RWX)
+        fs::create_dir(path)
     } else {
         Ok(())
     }
@@ -648,21 +654,17 @@ fn shortty(item: &clean::Item) -> ItemType {
 /// static HTML tree.
 // FIXME (#9639): The closure should deal with &[u8] instead of &str
 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
-fn clean_srcpath<F>(src_root: &Path, src: &[u8], mut f: F) where
+fn clean_srcpath<F>(src_root: &Path, p: &Path, mut f: F) where
     F: FnMut(&str),
 {
-    let p = Path::new(src);
-
     // make it relative, if possible
-    let p = p.path_relative_from(src_root).unwrap_or(p);
+    let p = p.relative_from(src_root).unwrap_or(p);
 
-    if p.as_vec() != b"." {
-        for c in p.str_components().map(|x|x.unwrap()) {
-            if ".." == c {
-                f("up");
-            } else {
-                f(c)
-            }
+    for c in p.iter().map(|x| x.to_str().unwrap()) {
+        if ".." == c {
+            f("up");
+        } else {
+            f(c)
         }
     }
 }
@@ -733,13 +735,14 @@ fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
 
 impl<'a> SourceCollector<'a> {
     /// Renders the given filename into its corresponding HTML source file.
-    fn emit_source(&mut self, filename: &str) -> old_io::IoResult<()> {
-        let p = Path::new(filename);
+    fn emit_source(&mut self, filename: &str) -> io::Result<()> {
+        let p = PathBuf::new(filename);
 
         // If we couldn't open this file, then just returns because it
         // probably means that it's some standard library macro thing and we
         // can't have the source to it anyway.
-        let contents = match File::open(&p).read_to_end() {
+        let mut contents = Vec::new();
+        match File::open(&p).and_then(|mut f| f.read_to_end(&mut contents)) {
             Ok(r) => r,
             // macros from other libraries get special filenames which we can
             // safely ignore
@@ -759,18 +762,20 @@ fn emit_source(&mut self, filename: &str) -> old_io::IoResult<()> {
         // Create the intermediate directories
         let mut cur = self.dst.clone();
         let mut root_path = String::from_str("../../");
-        clean_srcpath(&self.cx.src_root, p.dirname(), |component| {
+        clean_srcpath(&self.cx.src_root, &p, |component| {
             cur.push(component);
             mkdir(&cur).unwrap();
             root_path.push_str("../");
         });
 
-        let mut fname = p.filename().expect("source has no filename").to_vec();
-        fname.extend(".html".bytes());
-        cur.push(fname);
-        let mut w = BufferedWriter::new(try!(File::create(&cur)));
+        let mut fname = p.file_name().expect("source has no filename")
+                         .to_os_string();
+        fname.push_os_str(OsStr::from_str(".html"));
+        cur.push(&fname);
+        let mut w = BufWriter::new(try!(File::create(&cur)));
 
-        let title = format!("{} -- source", cur.filename_display());
+        let title = format!("{} -- source", cur.file_name().unwrap()
+                                               .to_string_lossy());
         let desc = format!("Source to the Rust file `{}`.", filename);
         let page = layout::Page {
             title: &title,
@@ -779,7 +784,7 @@ fn emit_source(&mut self, filename: &str) -> old_io::IoResult<()> {
             description: &desc,
             keywords: get_basic_keywords(),
         };
-        try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
+        try!(layout::render(&mut w, &self.cx.layout,
                             &page, &(""), &Source(contents)));
         try!(w.flush());
         return Ok(());
@@ -1081,7 +1086,7 @@ fn recurse<T, F>(&mut self, s: String, f: F) -> T where
     /// This currently isn't parallelized, but it'd be pretty easy to add
     /// parallelization to this function.
     fn krate(mut self, mut krate: clean::Crate,
-             stability: stability_summary::ModuleSummary) -> old_io::IoResult<()> {
+             stability: stability_summary::ModuleSummary) -> io::Result<()> {
         let mut item = match krate.module.take() {
             Some(i) => i,
             None => return Ok(())
@@ -1091,7 +1096,7 @@ fn krate(mut self, mut krate: clean::Crate,
         // render stability dashboard
         try!(self.recurse(stability.name.clone(), |this| {
             let json_dst = &this.dst.join("stability.json");
-            let mut json_out = BufferedWriter::new(try!(File::create(json_dst)));
+            let mut json_out = BufWriter::new(try!(File::create(json_dst)));
             try!(write!(&mut json_out, "{}", json::as_json(&stability)));
 
             let mut title = stability.name.clone();
@@ -1106,7 +1111,7 @@ fn krate(mut self, mut krate: clean::Crate,
                 keywords: get_basic_keywords(),
             };
             let html_dst = &this.dst.join("stability.html");
-            let mut html_out = BufferedWriter::new(try!(File::create(html_dst)));
+            let mut html_out = BufWriter::new(try!(File::create(html_dst)));
             layout::render(&mut html_out, &this.layout, &page,
                            &Sidebar{ cx: this, item: &item },
                            &stability)
@@ -1131,12 +1136,12 @@ fn krate(mut self, mut krate: clean::Crate,
     /// all sub-items which need to be rendered.
     ///
     /// The rendering driver uses this closure to queue up more work.
-    fn item<F>(&mut self, item: clean::Item, mut f: F) -> old_io::IoResult<()> where
+    fn item<F>(&mut self, item: clean::Item, mut f: F) -> io::Result<()> where
         F: FnMut(&mut Context, clean::Item),
     {
-        fn render(w: old_io::File, cx: &Context, it: &clean::Item,
-                  pushname: bool) -> old_io::IoResult<()> {
-            info!("Rendering an item to {}", w.path().display());
+        fn render(w: File, cx: &Context, it: &clean::Item,
+                  pushname: bool) -> io::Result<()> {
+            info!("Rendering an item to {}", w.path().unwrap().display());
             // A little unfortunate that this is done like this, but it sure
             // does make formatting *a lot* nicer.
             CURRENT_LOCATION_KEY.with(|slot| {
@@ -1177,7 +1182,7 @@ fn render(w: old_io::File, cx: &Context, it: &clean::Item,
             // We have a huge number of calls to write, so try to alleviate some
             // of the pain by using a buffered writer instead of invoking the
             // write syscall all the time.
-            let mut writer = BufferedWriter::new(w);
+            let mut writer = BufWriter::new(w);
             if !cx.render_redirect_pages {
                 try!(layout::render(&mut writer, &cx.layout, &page,
                                     &Sidebar{ cx: cx, item: it },
@@ -1238,7 +1243,7 @@ fn render(w: old_io::File, cx: &Context, it: &clean::Item,
             // Things which don't have names (like impls) don't get special
             // pages dedicated to them.
             _ if item.name.is_some() => {
-                let dst = self.dst.join(item_path(&item));
+                let dst = self.dst.join(&item_path(&item));
                 let dst = try!(File::create(&dst));
                 render(dst, self, &item, true)
             }
@@ -1307,7 +1312,7 @@ fn href(&self, cx: &Context) -> Option<String> {
         // has anchors for the line numbers that we're linking to.
         if ast_util::is_local(self.item.def_id) {
             let mut path = Vec::new();
-            clean_srcpath(&cx.src_root, self.item.source.filename.as_bytes(),
+            clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename),
                           |component| {
                 path.push(component.to_string());
             });
index fc304884ec9d8e6e440bbfc72742206ce4186dac..b4522ad680b77a7e128ec2fded45729c007ad0d3 100644 (file)
 #![feature(test)]
 #![feature(unicode)]
 #![feature(str_words)]
+#![feature(io)]
+#![feature(fs)]
+#![feature(path)]
+#![feature(tempdir)]
 
 extern crate arena;
 extern crate getopts;
 use std::cell::RefCell;
 use std::collections::HashMap;
 use std::env;
-use std::old_io::File;
-use std::old_io;
+use std::fs::File;
+use std::io::{self, Read, Write};
+use std::path::PathBuf;
 use std::rc::Rc;
 use std::sync::mpsc::channel;
+
 use externalfiles::ExternalHtml;
 use serialize::Decodable;
 use serialize::json::{self, Json};
@@ -242,7 +248,7 @@ pub fn main_args(args: &[String]) -> int {
     let should_test = matches.opt_present("test");
     let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
 
-    let output = matches.opt_str("o").map(|s| Path::new(s));
+    let output = matches.opt_str("o").map(|s| PathBuf::new(&s));
     let cfgs = matches.opt_strs("cfg");
 
     let external_html = match ExternalHtml::load(
@@ -261,7 +267,8 @@ pub fn main_args(args: &[String]) -> int {
         (true, false) => {
             return test::run(input, cfgs, libs, externs, test_args, crate_name)
         }
-        (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
+        (false, true) => return markdown::render(input,
+                                                 output.unwrap_or(PathBuf::new("doc")),
                                                  &matches, &external_html,
                                                  !matches.opt_present("markdown-no-toc")),
         (false, false) => {}
@@ -278,7 +285,8 @@ pub fn main_args(args: &[String]) -> int {
     info!("going to format");
     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")),
+            match html::render::run(krate, &external_html,
+                                    output.unwrap_or(PathBuf::new("doc")),
                                     passes.into_iter().collect()) {
                 Ok(()) => {}
                 Err(e) => panic!("failed to generate documentation: {}", e),
@@ -286,7 +294,7 @@ pub fn main_args(args: &[String]) -> int {
         }
         Some("json") => {
             match json_output(krate, json_plugins,
-                              output.unwrap_or(Path::new("doc.json"))) {
+                              output.unwrap_or(PathBuf::new("doc.json"))) {
                 Ok(()) => {}
                 Err(e) => panic!("failed to write json: {}", e),
             }
@@ -364,15 +372,15 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche
     let cfgs = matches.opt_strs("cfg");
     let triple = matches.opt_str("target");
 
-    let cr = Path::new(cratefile);
+    let cr = PathBuf::new(cratefile);
     info!("starting to run rustc");
 
     let (tx, rx) = channel();
     std::thread::spawn(move || {
         use rustc::session::config::Input;
 
-        let cr = cr;
-        tx.send(core::run_core(paths, cfgs, externs, Input::File(cr), triple)).unwrap();
+        tx.send(core::run_core(paths, cfgs, externs, Input::File(cr),
+                               triple)).unwrap();
     }).join().map_err(|_| "rustc failed").unwrap();
     let (mut krate, analysis) = rx.recv().unwrap();
     info!("finished with rustc");
@@ -451,13 +459,12 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche
 /// This input format purely deserializes the json output file. No passes are
 /// run over the deserialized output.
 fn json_input(input: &str) -> Result<Output, String> {
-    let mut input = match File::open(&Path::new(input)) {
-        Ok(f) => f,
-        Err(e) => {
-            return Err(format!("couldn't open {}: {}", input, e))
-        }
+    let mut bytes = Vec::new();
+    match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
+        Ok(()) => {}
+        Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
     };
-    match json::from_reader(&mut input) {
+    match json::from_reader(&mut &bytes[..]) {
         Err(s) => Err(format!("{:?}", s)),
         Ok(Json::Object(obj)) => {
             let mut obj = obj;
@@ -495,7 +502,7 @@ fn json_input(input: &str) -> Result<Output, String> {
 /// Outputs the crate/plugin json as a giant json blob at the specified
 /// destination.
 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
-               dst: Path) -> old_io::IoResult<()> {
+               dst: PathBuf) -> io::Result<()> {
     // {
     //   "schema": version,
     //   "crate": { parsed crate ... },
index d64d9becc0c7c459f2ac2ebcb9e6132bc834bcb7..7d635c8b2327481f609130157e366566004403a5 100644 (file)
@@ -8,7 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+use std::fs::File;
+use std::io::Write;
 use std::old_io;
+use std::path::{PathBuf, Path};
 
 use core;
 use getopts;
@@ -40,10 +43,10 @@ fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) {
 
 /// Render `input` (e.g. "foo.md") into an HTML file in `output`
 /// (e.g. output = "bar" => "bar/foo.html").
-pub fn render(input: &str, mut output: Path, matches: &getopts::Matches,
+pub fn render(input: &str, mut output: PathBuf, matches: &getopts::Matches,
               external_html: &ExternalHtml, include_toc: bool) -> int {
     let input_p = Path::new(input);
-    output.push(input_p.filestem().unwrap());
+    output.push(input_p.file_stem().unwrap());
     output.set_extension("html");
 
     let mut css = String::new();
@@ -59,7 +62,7 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches,
     }
     let playground = playground.unwrap_or("".to_string());
 
-    let mut out = match old_io::File::create(&output) {
+    let mut out = match File::create(&output) {
         Err(e) => {
             let _ = writeln!(&mut old_io::stderr(),
                              "error opening `{}` for writing: {}",
index 43e8f44244e788c258b5f3a0d0b6873d2cd317ef..9fd38ecb13627f07ee721b931b80da2061ff7a07 100644 (file)
@@ -9,16 +9,20 @@
 // except according to those terms.
 
 use std::cell::RefCell;
-use std::sync::mpsc::channel;
+use std::collections::{HashSet, HashMap};
 use std::dynamic_lib::DynamicLibrary;
-use std::old_io::{Command, TempDir};
+use std::env;
+use std::ffi::OsString;
+use std::fs::TempDir;
 use std::old_io;
-use std::os;
+use std::io;
+use std::path::PathBuf;
+use std::process::Command;
 use std::str;
+use std::sync::mpsc::channel;
 use std::thread;
 use std::thunk::Thunk;
 
-use std::collections::{HashSet, HashMap};
 use testing;
 use rustc_lint;
 use rustc::session::{self, config};
@@ -43,11 +47,12 @@ pub fn run(input: &str,
            mut test_args: Vec<String>,
            crate_name: Option<String>)
            -> int {
-    let input_path = Path::new(input);
+    let input_path = PathBuf::new(input);
     let input = config::Input::File(input_path.clone());
 
     let sessopts = config::Options {
-        maybe_sysroot: Some(os::self_exe_name().unwrap().dir_path().dir_path()),
+        maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
+                                              .parent().unwrap().to_path_buf()),
         search_paths: libs.clone(),
         crate_types: vec!(config::CrateTypeDylib),
         externs: externs.clone(),
@@ -115,7 +120,8 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths,
     let input = config::Input::Str(test.to_string());
 
     let sessopts = config::Options {
-        maybe_sysroot: Some(os::self_exe_name().unwrap().dir_path().dir_path()),
+        maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
+                                              .parent().unwrap().to_path_buf()),
         search_paths: libs,
         crate_types: vec!(config::CrateTypeExecutable),
         output_types: vec!(config::OutputTypeExe),
@@ -170,7 +176,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths,
     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
 
     let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
-    let out = Some(outdir.path().clone());
+    let out = Some(outdir.path().to_path_buf());
     let cfg = config::build_configuration(&sess);
     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
     let mut control = driver::CompileController::basic();
@@ -187,17 +193,19 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths,
     // environment to ensure that the target loads the right libraries at
     // runtime. It would be a sad day if the *host* libraries were loaded as a
     // mistake.
-    let mut cmd = Command::new(outdir.path().join("rust-out"));
+    let mut cmd = Command::new(&outdir.path().join("rust-out"));
+    let var = DynamicLibrary::envvar();
     let newpath = {
-        let mut path = DynamicLibrary::search_path();
+        let path = env::var_os(var).unwrap_or(OsString::new());
+        let mut path = env::split_paths(&path).collect::<Vec<_>>();
         path.insert(0, libdir.clone());
-        DynamicLibrary::create_path(&path)
+        env::join_paths(path.iter()).unwrap()
     };
-    cmd.env(DynamicLibrary::envvar(), newpath);
+    cmd.env(var, &newpath);
 
     match cmd.output() {
         Err(e) => panic!("couldn't run the test: {}{}", e,
-                        if e.kind == old_io::PermissionDenied {
+                        if e.kind() == io::ErrorKind::PermissionDenied {
                             " - maybe your tempdir is mounted with noexec?"
                         } else { "" }),
         Ok(out) => {
@@ -205,7 +213,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));
+                      str::from_utf8(&out.stdout));
             }
         }
     }
index d476fd72abc3b03ea2f8cc8b729f8182fa78fad6..bfc6b1bf0ef13ba5729ae98c84b0ffcf2afcc092 100644 (file)
@@ -35,6 +35,7 @@
 #![feature(staged_api)]
 #![feature(std_misc)]
 #![feature(unicode)]
+#![feature(path)]
 #![cfg_attr(test, feature(test))]
 
 // test harness access
index 70f0ba4bb23af013d1429e4d5fcdb2e882a85bac..f287229e0830db19fc9a96a2e499fde9e6c3a9d8 100644 (file)
@@ -15,6 +15,7 @@
 */
 
 use std::old_path;
+use std::path;
 use std::rc::Rc;
 use std::cell::{Cell, RefCell};
 use std::sync::Arc;
@@ -564,6 +565,19 @@ fn decode<D: Decoder>(d: &mut D) -> Result<old_path::windows::Path, D::Error> {
     }
 }
 
+impl Encodable for path::PathBuf {
+    fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
+        self.to_str().unwrap().encode(e)
+    }
+}
+
+impl Decodable for path::PathBuf {
+    fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
+        let bytes: String = try!(Decodable::decode(d));
+        Ok(path::PathBuf::new(&bytes))
+    }
+}
+
 impl<T: Encodable + Copy> Encodable for Cell<T> {
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
         self.get().encode(s)
index 69bcc82f6827570f61226dc0e241a0b4de023d5c..c94edb9d2a1c52d53d773a9f68899d1316bb2f57 100644 (file)
@@ -422,15 +422,14 @@ mod tests {
     use prelude::v1::*;
     use super::*;
     use libc;
-    use mem;
 
     #[test]
     fn c_to_rust() {
         let data = b"123\0";
         let ptr = data.as_ptr() as *const libc::c_char;
         unsafe {
-            assert_eq!(c_str_to_bytes(&ptr), b"123");
-            assert_eq!(c_str_to_bytes_with_nul(&ptr), b"123\0");
+            assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
+            assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
         }
     }
 
index 5510c0203e6cff3c3af5e7c487cf2ad2112ba909..46547ac583637c808990357679c553c42cb04141 100644 (file)
@@ -975,7 +975,7 @@ fn take_eof() {
         struct R;
 
         impl Read for R {
-            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+            fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
                 Err(io::Error::new(io::ErrorKind::Other, "", None))
             }
         }
index c890af631f0a8b01be437ba1fcbf2a0da45d8bdb..569906047aab3523371fdf69ead368c4cd6ff5d9 100644 (file)
 #![feature(hash)]
 #![feature(int_uint)]
 #![feature(unique)]
-#![cfg_attr(test, feature(test, rustc_private, env))]
+#![cfg_attr(test, feature(test, rustc_private))]
 
 // Don't link to std. We are std.
 #![feature(no_std)]
index 4e9c1b360552c4ee21d69146e72cf6261ac2bd9e..9a34ec4b026398d2674a7d0279091e48cb659f77 100644 (file)
@@ -82,6 +82,8 @@
 /// attempted against it for which its underlying file descriptor was not
 /// configured at creation time, via the `FileAccess` parameter to
 /// `File::open_mode()`.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::File")]
+#[unstable(feature = "old_io")]
 pub struct File {
     fd: fs_imp::FileDesc,
     path: Path,
@@ -94,6 +96,8 @@ fn as_inner(&self) -> &fs_imp::FileDesc {
     }
 }
 
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+#[unstable(feature = "old_io")]
 impl File {
     /// Open a file at `path` in the mode specified by the `mode` and `access`
     /// arguments
@@ -133,6 +137,8 @@ impl File {
     /// * Attempting to open a file with a `FileAccess` that the user lacks
     ///   permissions for
     /// * Filesystem-level errors (full disk, etc)
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs::OpenOptions")]
+    #[unstable(feature = "old_io")]
     pub fn open_mode(path: &Path,
                      mode: FileMode,
                      access: FileAccess) -> IoResult<File> {
@@ -174,6 +180,8 @@ pub fn open_mode(path: &Path,
     ///
     /// let contents = File::open(&Path::new("foo.txt")).read_to_end();
     /// ```
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs::File::open")]
+    #[unstable(feature = "old_io")]
     pub fn open(path: &Path) -> IoResult<File> {
         File::open_mode(path, Open, Read)
     }
@@ -195,12 +203,16 @@ pub fn open(path: &Path) -> IoResult<File> {
     /// # drop(f);
     /// # ::std::old_io::fs::unlink(&Path::new("foo.txt"));
     /// ```
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs::File::create")]
+    #[unstable(feature = "old_io")]
     pub fn create(path: &Path) -> IoResult<File> {
         File::open_mode(path, Truncate, Write)
              .update_desc("couldn't create file")
     }
 
     /// Returns the original path that was used to open this file.
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+    #[unstable(feature = "old_io")]
     pub fn path<'a>(&'a self) -> &'a Path {
         &self.path
     }
@@ -208,6 +220,8 @@ pub fn path<'a>(&'a self) -> &'a Path {
     /// Synchronizes all modifications to this file to its permanent storage
     /// device. This will flush any internal buffers necessary to perform this
     /// operation.
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+    #[unstable(feature = "old_io")]
     pub fn fsync(&mut self) -> IoResult<()> {
         self.fd.fsync()
             .update_err("couldn't fsync file",
@@ -218,6 +232,8 @@ pub fn fsync(&mut self) -> IoResult<()> {
     /// 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.
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+    #[unstable(feature = "old_io")]
     pub fn datasync(&mut self) -> IoResult<()> {
         self.fd.datasync()
             .update_err("couldn't datasync file",
@@ -232,6 +248,8 @@ pub fn datasync(&mut self) -> IoResult<()> {
     /// 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.
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+    #[unstable(feature = "old_io")]
     pub fn truncate(&mut self, size: i64) -> IoResult<()> {
         self.fd.truncate(size)
             .update_err("couldn't truncate file", |e|
@@ -247,11 +265,15 @@ pub fn truncate(&mut self, size: i64) -> IoResult<()> {
     /// until you have attempted to read past the end of the file, so if
     /// you've read _exactly_ the number of bytes in the file, this will
     /// return `false`, not `true`.
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+    #[unstable(feature = "old_io")]
     pub fn eof(&self) -> bool {
         self.last_nread == 0
     }
 
     /// Queries information about the underlying file.
+    #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+    #[unstable(feature = "old_io")]
     pub fn stat(&self) -> IoResult<FileStat> {
         self.fd.fstat()
             .update_err("couldn't fstat file", |e|
@@ -280,6 +302,8 @@ pub fn stat(&self) -> IoResult<FileStat> {
 /// 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.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::remove_file")]
+#[unstable(feature = "old_io")]
 pub fn unlink(path: &Path) -> IoResult<()> {
     fs_imp::unlink(path)
            .update_err("couldn't unlink path", |e|
@@ -307,6 +331,8 @@ pub fn unlink(path: &Path) -> IoResult<()> {
 /// This function will return an error if the user lacks the requisite permissions
 /// to perform a `stat` call on the given `path` or if there is no entry in the
 /// filesystem at the provided path.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::metadata")]
+#[unstable(feature = "old_io")]
 pub fn stat(path: &Path) -> IoResult<FileStat> {
     fs_imp::stat(path)
            .update_err("couldn't stat path", |e|
@@ -321,6 +347,7 @@ pub fn stat(path: &Path) -> IoResult<FileStat> {
 /// # Error
 ///
 /// See `stat`
+#[unstable(feature = "old_fs")]
 pub fn lstat(path: &Path) -> IoResult<FileStat> {
     fs_imp::lstat(path)
            .update_err("couldn't lstat path", |e|
@@ -343,6 +370,8 @@ pub fn lstat(path: &Path) -> IoResult<FileStat> {
 /// This function will return an error if the provided `from` doesn't exist, if
 /// the process lacks permissions to view the contents, or if some other
 /// intermittent I/O error occurs.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::rename")]
+#[unstable(feature = "old_io")]
 pub fn rename(from: &Path, to: &Path) -> IoResult<()> {
     fs_imp::rename(from, to)
            .update_err("couldn't rename path", |e|
@@ -377,6 +406,8 @@ pub fn rename(from: &Path, to: &Path) -> IoResult<()> {
 /// Note that this copy is not atomic in that once the destination is
 /// ensured to not exist, there is nothing preventing the destination from
 /// being created and then destroyed by this operation.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::copy")]
+#[unstable(feature = "old_io")]
 pub fn copy(from: &Path, to: &Path) -> IoResult<()> {
     fn update_err<T>(result: IoResult<T>, from: &Path, to: &Path) -> IoResult<T> {
         result.update_err("couldn't copy path", |e| {
@@ -421,6 +452,8 @@ fn update_err<T>(result: IoResult<T>, from: &Path, to: &Path) -> IoResult<T> {
 /// 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.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::set_permissions")]
+#[unstable(feature = "old_io")]
 pub fn chmod(path: &Path, mode: old_io::FilePermission) -> IoResult<()> {
     fs_imp::chmod(path, mode.bits() as uint)
            .update_err("couldn't chmod path", |e|
@@ -428,6 +461,7 @@ pub fn chmod(path: &Path, mode: old_io::FilePermission) -> IoResult<()> {
 }
 
 /// Change the user and group owners of a file at the specified path.
+#[unstable(feature = "old_fs")]
 pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> {
     fs_imp::chown(path, uid, gid)
            .update_err("couldn't chown path", |e|
@@ -437,6 +471,8 @@ pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> {
 /// 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.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::hard_link")]
+#[unstable(feature = "old_io")]
 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
     fs_imp::link(src, dst)
            .update_err("couldn't link path", |e|
@@ -445,6 +481,8 @@ pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
 
 /// Creates a new symbolic link on the filesystem. The `dst` path will be a
 /// symlink pointing to the `src` path.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::soft_link")]
+#[unstable(feature = "old_io")]
 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
     fs_imp::symlink(src, dst)
            .update_err("couldn't symlink path", |e|
@@ -457,6 +495,8 @@ pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
 ///
 /// 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 symlink.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::read_link")]
+#[unstable(feature = "old_io")]
 pub fn readlink(path: &Path) -> IoResult<Path> {
     fs_imp::readlink(path)
            .update_err("couldn't resolve symlink for path", |e|
@@ -480,6 +520,7 @@ pub fn readlink(path: &Path) -> IoResult<Path> {
 ///
 /// This function will return an error if the user lacks permissions to make a
 /// new directory at the provided `path`, or if the directory already exists.
+#[unstable(feature = "old_fs")]
 pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> {
     fs_imp::mkdir(path, mode.bits() as uint)
            .update_err("couldn't create directory", |e|
@@ -502,6 +543,8 @@ pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> {
 ///
 /// 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.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::remove_dir")]
+#[unstable(feature = "old_io")]
 pub fn rmdir(path: &Path) -> IoResult<()> {
     fs_imp::rmdir(path)
            .update_err("couldn't remove directory", |e|
@@ -542,6 +585,8 @@ pub fn rmdir(path: &Path) -> IoResult<()> {
 /// 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
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::read_dir")]
+#[unstable(feature = "old_io")]
 pub fn readdir(path: &Path) -> IoResult<Vec<Path>> {
     fs_imp::readdir(path)
            .update_err("couldn't read directory",
@@ -552,6 +597,8 @@ pub fn readdir(path: &Path) -> IoResult<Vec<Path>> {
 /// 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.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::walk_dir")]
+#[unstable(feature = "old_io")]
 pub fn walk_dir(path: &Path) -> IoResult<Directories> {
     Ok(Directories {
         stack: try!(readdir(path).update_err("couldn't walk directory",
@@ -561,6 +608,8 @@ pub fn walk_dir(path: &Path) -> IoResult<Directories> {
 
 /// An iterator that walks over a directory
 #[derive(Clone)]
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::ReadDir")]
+#[unstable(feature = "old_io")]
 pub struct Directories {
     stack: Vec<Path>,
 }
@@ -590,6 +639,7 @@ fn next(&mut self) -> Option<Path> {
 /// # Error
 ///
 /// See `fs::mkdir`.
+#[unstable(feature = "old_fs")]
 pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> {
     // tjc: if directory exists but with different permissions,
     // should we return false?
@@ -627,6 +677,8 @@ pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> {
 /// # Error
 ///
 /// See `file::unlink` and `fs::readdir`
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::remove_dir_all")]
+#[unstable(feature = "old_io")]
 pub fn rmdir_recursive(path: &Path) -> IoResult<()> {
     let mut rm_stack = Vec::new();
     rm_stack.push(path.clone());
@@ -689,6 +741,8 @@ fn update_err<T>(err: IoResult<T>, path: &Path) -> IoResult<T> {
 /// `atime` and its modification time set to `mtime`. The times specified should
 /// be in milliseconds.
 // FIXME(#10301) these arguments should not be u64
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::set_file_times")]
+#[unstable(feature = "old_io")]
 pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> {
     fs_imp::utime(path, atime, mtime)
            .update_err("couldn't change_file_times", |e|
@@ -748,6 +802,8 @@ fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
 }
 
 /// Utility methods for paths.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::PathExt")]
+#[unstable(feature = "old_io")]
 pub trait PathExtensions {
     /// Get information on the file, directory, etc at this path.
     ///
index 9c89c943994630f46c1b7633ec24cabe5dc8fb6a..f1634cd422935db42c534236ab13e3abced87055 100644 (file)
@@ -323,22 +323,22 @@ fn read_ipv6_addr(&mut self) -> Option<IpAddr> {
     }
 
     fn read_ip_addr(&mut self) -> Option<IpAddr> {
-        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])
+        let ipv4_addr: Box<_> = box |p: &mut Parser| p.read_ipv4_addr();
+        let ipv6_addr: Box<_> = box |p: &mut Parser| p.read_ipv6_addr();
+        self.read_or(&mut [ipv4_addr, ipv6_addr])
     }
 
     fn read_socket_addr(&mut self) -> Option<SocketAddr> {
         let ip_addr = |p: &mut Parser| {
-            let ipv4_p = |p: &mut Parser| p.read_ip_addr();
-            let ipv6_p = |p: &mut Parser| {
+            let ipv4_p: Box<_> = box |p: &mut Parser| p.read_ip_addr();
+            let ipv6_p: Box<_> = box |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])
+            p.read_or(&mut [ipv4_p, 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);
index a5df21749e22e3023580e1ae8ef4b6a48a130c67..85bf4908f8397bf5ffe65c9835134109a8b4b84e 100644 (file)
@@ -547,8 +547,9 @@ fn capture_stdout() {
 
         let (tx, rx) = channel();
         let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx));
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
         let _t = thread::spawn(move|| {
-            set_stdout(box w);
+            set_stdout(Box::new(w));
             println!("hello!");
         });
         assert_eq!(r.read_to_string().unwrap(), "hello!\n");
@@ -560,8 +561,9 @@ fn capture_stderr() {
 
         let (tx, rx) = channel();
         let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx));
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
         let _t = thread::spawn(move || -> () {
-            set_stderr(box w);
+            set_stderr(Box::new(w));
             panic!("my special message");
         });
         let s = r.read_to_string().unwrap();
index 1f2ef50fcae453627b63568cf7e0b92697cac72b..de5f2141095f30705e99a467f9c5b16e746a04d6 100644 (file)
@@ -15,6 +15,7 @@
 
 // FIXME: These functions take Durations but only pass ms to the backend impls.
 
+use boxed::Box;
 use sync::mpsc::{Receiver, Sender, channel};
 use time::Duration;
 use old_io::IoResult;
@@ -143,7 +144,7 @@ pub fn oneshot(&mut self, duration: Duration) -> Receiver<()> {
         let (tx, rx) = channel();
         // Short-circuit the timer backend for 0 duration
         if in_ms_u64(duration) != 0 {
-            self.inner.oneshot(in_ms_u64(duration), box TimerCallback { tx: tx });
+            self.inner.oneshot(in_ms_u64(duration), Box::new(TimerCallback { tx: tx }));
         } else {
             tx.send(()).unwrap();
         }
@@ -204,7 +205,7 @@ pub fn periodic(&mut self, duration: Duration) -> Receiver<()> {
         // not clear what use a 0ms period is anyway...
         let ms = if ms == 0 { 1 } else { ms };
         let (tx, rx) = channel();
-        self.inner.period(ms, box TimerCallback { tx: tx });
+        self.inner.period(ms, Box::new(TimerCallback { tx: tx }));
         return rx
     }
 }
index b578b5e3d600a8b28467f05613d048e81b06d00d..79028f49e68bfa17efcc7009500550d02a9a865d 100644 (file)
@@ -803,14 +803,13 @@ pub fn env_cmd() -> Command {
     #[cfg(not(target_os="android"))]
     #[test]
     fn test_inherit_env() {
-        use os;
+        use std::env;
         if running_on_valgrind() { return; }
 
         let result = env_cmd().output().unwrap();
         let output = String::from_utf8(result.stdout).unwrap();
 
-        let r = os::env();
-        for &(ref k, ref v) in &r {
+        for (ref k, ref v) in env::vars() {
             // don't check windows magical empty-named variables
             assert!(k.is_empty() ||
                     output.contains(format!("{}={}", *k, *v).as_slice()),
index 4dda3ea8c998800e94cde11c237296ab2ee502da..ebb2a2e4827a10770098405b7c2b3e9d44c60c21 100644 (file)
@@ -166,7 +166,7 @@ fn rust_panic(cause: Box<Any + Send + 'static>) -> ! {
     rtdebug!("begin_unwind()");
 
     unsafe {
-        let exception = box Exception {
+        let exception: Box<_> = box Exception {
             uwe: uw::_Unwind_Exception {
                 exception_class: rust_exception_class(),
                 exception_cleanup: exception_cleanup,
@@ -506,7 +506,7 @@ pub fn begin_unwind_fmt(msg: fmt::Arguments, file_line: &(&'static str, uint)) -
 
     let mut s = String::new();
     let _ = write!(&mut s, "{}", msg);
-    begin_unwind_inner(box s, file_line)
+    begin_unwind_inner(Box::new(s), file_line)
 }
 
 /// This is the entry point of unwinding for panic!() and assert!().
@@ -521,7 +521,7 @@ pub fn begin_unwind<M: Any + Send>(msg: M, file_line: &(&'static str, uint)) ->
     // panicking.
 
     // see below for why we do the `Any` coercion here.
-    begin_unwind_inner(box msg, file_line)
+    begin_unwind_inner(Box::new(msg), file_line)
 }
 
 /// The core of the unwinding.
index ee8bef50d89991c9dc9cfc1d4e6ad80cb2f10042..1a1e9e69e71122eabe6254036f1e174fcb1a8aaa 100644 (file)
@@ -1044,13 +1044,13 @@ fn smoke() {
 
     #[test]
     fn drop_full() {
-        let (tx, _rx) = channel();
+        let (tx, _rx) = channel::<Box<int>>();
         tx.send(box 1).unwrap();
     }
 
     #[test]
     fn drop_full_shared() {
-        let (tx, _rx) = channel();
+        let (tx, _rx) = channel::<Box<int>>();
         drop(tx.clone());
         drop(tx.clone());
         tx.send(box 1).unwrap();
@@ -1389,7 +1389,7 @@ fn oneshot_multi_thread_recv_close_stress() {
     #[test]
     fn oneshot_multi_thread_send_recv_stress() {
         for _ in 0..stress_factor() {
-            let (tx, rx) = channel();
+            let (tx, rx) = channel::<Box<int>>();
             let _t = thread::spawn(move|| {
                 tx.send(box 10).unwrap();
             });
@@ -1566,7 +1566,7 @@ fn smoke() {
 
     #[test]
     fn drop_full() {
-        let (tx, _rx) = sync_channel(1);
+        let (tx, _rx) = sync_channel::<Box<int>>(1);
         tx.send(box 1).unwrap();
     }
 
index 59fa2e6bc9a91c31dc28cc60f8e3ad8b0dfd9861..14ed253d8e27ef8f056d7c1e62a4dd5edeb7be09 100644 (file)
@@ -164,7 +164,7 @@ mod tests {
 
     #[test]
     fn test_full() {
-        let q = Queue::new();
+        let q: Queue<Box<_>> = Queue::new();
         q.push(box 1);
         q.push(box 2);
     }
index ce40fa2672ab32555339aca56e87deed24dbf4a9..3fb13739aa75af4b0a4cc766791a73fc7b39da81 100644 (file)
@@ -289,7 +289,7 @@ fn peek() {
     #[test]
     fn drop_full() {
         unsafe {
-            let q = Queue::new(0);
+            let q: Queue<Box<_>> = Queue::new(0);
             q.push(box 1);
             q.push(box 2);
         }
index 3f9da6e3c51bb004fb6b1cf40a917825237136b5..45042d6f0325508cce167321e216e64f150d4597 100644 (file)
@@ -54,6 +54,7 @@ pub trait AsRawFd {
     fn as_raw_fd(&self) -> Fd;
 }
 
+#[allow(deprecated)]
 impl AsRawFd for old_io::fs::File {
     fn as_raw_fd(&self) -> Fd {
         self.as_inner().fd()
index ac1006e653f09dc7c76c1e423e8c536f54d93a81..df18b404f5fe9e06f4facee997626787e13cffab 100644 (file)
@@ -39,6 +39,7 @@ pub trait AsRawHandle {
     fn as_raw_handle(&self) -> Handle;
 }
 
+#[allow(deprecated)]
 impl AsRawHandle for old_io::fs::File {
     fn as_raw_handle(&self) -> Handle {
         self.as_inner().handle()
index 334cafd3eb1136767fa4cc355360e44aafa50183..53a037ef07e613a15f30a4e926567078359d4595 100644 (file)
@@ -17,7 +17,7 @@
 use libc::{pid_t, c_void};
 use libc;
 use mem;
-use old_io::fs::PathExtensions;
+#[allow(deprecated)] use old_io::fs::PathExtensions;
 use old_io::process::{ProcessExit, ExitStatus};
 use old_io::{IoResult, IoError};
 use old_io;
index e83308209062cc4660f748ad52887198422215d3..9be77e78ed1f3cb910a7fb5f542fba12b162e542 100644 (file)
@@ -804,7 +804,7 @@ fn test_spawn_sched_childs_on_default_sched() {
     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk<'static>) {
         let (tx, rx) = channel();
 
-        let x = box 1;
+        let x: Box<_> = box 1;
         let x_in_parent = (&*x) as *const i32 as usize;
 
         spawnfn(Thunk::new(move|| {
index 5bede984f13c7bc37bdb9bb00ccc443419664340..a9cb05b368f02a200acd64526b82dee685153639 100644 (file)
@@ -33,7 +33,7 @@ pub fn with_arg<F>(func: F) -> Thunk<'a,A,R>
         where F : FnOnce(A) -> R, F : Send + 'a
     {
         Thunk {
-            invoke: box func
+            invoke: Box::<F>::new(func)
         }
     }
 
index 6d6fdffa95095b25c6fd6b5684df59d12d8ae611..05348ee77e81f24d7f6c3cd45fb01d54ee2b4d1f 100644 (file)
 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
 use abi::Abi;
 use ast_util;
+use ext::base;
+use ext::tt::macro_parser;
 use owned_slice::OwnedSlice;
 use parse::token::{InternedString, str_to_ident};
 use parse::token;
+use parse::lexer;
 use ptr::P;
 
 use std::fmt;
@@ -960,6 +963,18 @@ pub fn get_span(&self) -> Span {
             TtSequence(span, _)  => span,
         }
     }
+
+    /// Use this token tree as a matcher to parse given tts.
+    pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
+                 -> macro_parser::NamedParseResult {
+        // `None` is because we're not interpolating
+        let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
+                                                         None,
+                                                         None,
+                                                         tts.iter().cloned().collect(),
+                                                         true);
+        macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
+    }
 }
 
 pub type Mac = Spanned<Mac_>;
index c33158193ce215a6c835df3798bed0694c5ce294..faa681c0255285ccab0a12e1f49f05d5d7e3cf34 100644 (file)
@@ -25,7 +25,7 @@
 use arena::TypedArena;
 use std::cell::RefCell;
 use std::fmt;
-use std::old_io::IoResult;
+use std::io;
 use std::iter::{self, repeat};
 use std::mem;
 use std::slice;
@@ -997,11 +997,11 @@ pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
 }
 
 pub trait NodePrinter {
-    fn print_node(&mut self, node: &Node) -> IoResult<()>;
+    fn print_node(&mut self, node: &Node) -> io::Result<()>;
 }
 
 impl<'a> NodePrinter for pprust::State<'a> {
-    fn print_node(&mut self, node: &Node) -> IoResult<()> {
+    fn print_node(&mut self, node: &Node) -> io::Result<()> {
         match *node {
             NodeItem(a)        => self.print_item(&*a),
             NodeForeignItem(a) => self.print_foreign_item(&*a),
index 099f646294235d175dcdf47b59ac0daa419f7024..162da2ac54c12ee111e380302ce5b430a60332a9 100644 (file)
 use libc::c_uint;
 use serialize::{Encodable, Decodable, Encoder, Decoder};
 
+
+// _____________________________________________________________________________
+// Pos, BytePos, CharPos
+//
+
 pub trait Pos {
     fn from_usize(n: usize) -> Self;
     fn to_usize(&self) -> usize;
@@ -69,6 +74,18 @@ fn sub(self, rhs: BytePos) -> BytePos {
     }
 }
 
+impl Encodable for BytePos {
+    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
+        s.emit_u32(self.0)
+    }
+}
+
+impl Decodable for BytePos {
+    fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
+        Ok(BytePos(try!{ d.read_u32() }))
+    }
+}
+
 impl Pos for CharPos {
     fn from_usize(n: usize) -> CharPos { CharPos(n) }
     fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
@@ -90,6 +107,10 @@ fn sub(self, rhs: CharPos) -> CharPos {
     }
 }
 
+// _____________________________________________________________________________
+// Span, Spanned
+//
+
 /// Spans represent a region of code, used for error reporting. Positions in spans
 /// are *absolute* positions from the beginning of the codemap, not positions
 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
@@ -126,15 +147,20 @@ fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
 impl Eq for Span {}
 
 impl Encodable for Span {
-    /* Note #1972 -- spans are encoded but not decoded */
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
-        s.emit_nil()
+        // Encode spans as a single u64 in order to cut down on tagging overhead
+        // added by the RBML metadata encoding. The should be solved differently
+        // altogether some time (FIXME #21482)
+        s.emit_u64( (self.lo.0 as u64) | ((self.hi.0 as u64) << 32) )
     }
 }
 
 impl Decodable for Span {
-    fn decode<D: Decoder>(_d: &mut D) -> Result<Span, D::Error> {
-        Ok(DUMMY_SP)
+    fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
+        let lo_hi: u64 = try! { d.read_u64() };
+        let lo = BytePos(lo_hi as u32);
+        let hi = BytePos((lo_hi >> 32) as u32);
+        Ok(mk_sp(lo, hi))
     }
 }
 
@@ -168,6 +194,10 @@ pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span {
     }
 }
 
+// _____________________________________________________________________________
+// Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
+//
+
 /// A source code location used for error reporting
 pub struct Loc {
     /// Information about the original source
@@ -192,6 +222,11 @@ pub struct LocWithOpt {
 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
 
+
+// _____________________________________________________________________________
+// MacroFormat, NameAndSpan, ExpnInfo, ExpnId
+//
+
 /// The syntax with which a macro was invoked.
 #[derive(Clone, Copy, Hash, Debug)]
 pub enum MacroFormat {
@@ -254,6 +289,10 @@ pub fn to_llvm_cookie(self) -> i32 {
     }
 }
 
+// _____________________________________________________________________________
+// FileMap, MultiByteChar, FileName, FileLines
+//
+
 pub type FileName = String;
 
 pub struct FileLines {
@@ -262,7 +301,7 @@ pub struct FileLines {
 }
 
 /// Identifies an offset of a multi-byte character in a FileMap
-#[derive(Copy)]
+#[derive(Copy, RustcEncodable, RustcDecodable, Eq, PartialEq)]
 pub struct MultiByteChar {
     /// The absolute offset of the character in the CodeMap
     pub pos: BytePos,
@@ -277,13 +316,134 @@ pub struct FileMap {
     /// e.g. `<anon>`
     pub name: FileName,
     /// The complete source code
-    pub src: String,
+    pub src: Option<Rc<String>>,
     /// The start position of this source in the CodeMap
     pub start_pos: BytePos,
+    /// The end position of this source in the CodeMap
+    pub end_pos: BytePos,
     /// Locations of lines beginnings in the source code
-    pub lines: RefCell<Vec<BytePos> >,
+    pub lines: RefCell<Vec<BytePos>>,
     /// Locations of multi-byte characters in the source code
-    pub multibyte_chars: RefCell<Vec<MultiByteChar> >,
+    pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
+}
+
+impl Encodable for FileMap {
+    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
+        s.emit_struct("FileMap", 5, |s| {
+            try! { s.emit_struct_field("name", 0, |s| self.name.encode(s)) };
+            try! { s.emit_struct_field("start_pos", 1, |s| self.start_pos.encode(s)) };
+            try! { s.emit_struct_field("end_pos", 2, |s| self.end_pos.encode(s)) };
+            try! { s.emit_struct_field("lines", 3, |s| {
+                    let lines = self.lines.borrow();
+                    // store the length
+                    try! { s.emit_u32(lines.len() as u32) };
+
+                    if lines.len() > 0 {
+                        // In order to preserve some space, we exploit the fact that
+                        // the lines list is sorted and individual lines are
+                        // probably not that long. Because of that we can store lines
+                        // as a difference list, using as little space as possible
+                        // for the differences.
+                        let max_line_length = if lines.len() == 1 {
+                            0
+                        } else {
+                            lines.as_slice()
+                                 .windows(2)
+                                 .map(|w| w[1] - w[0])
+                                 .map(|bp| bp.to_usize())
+                                 .max()
+                                 .unwrap()
+                        };
+
+                        let bytes_per_diff: u8 = match max_line_length {
+                            0 ... 0xFF => 1,
+                            0x100 ... 0xFFFF => 2,
+                            _ => 4
+                        };
+
+                        // Encode the number of bytes used per diff.
+                        try! { bytes_per_diff.encode(s) };
+
+                        // Encode the first element.
+                        try! { lines[0].encode(s) };
+
+                        let diff_iter = (&lines[..]).windows(2)
+                                                    .map(|w| (w[1] - w[0]));
+
+                        match bytes_per_diff {
+                            1 => for diff in diff_iter { try! { (diff.0 as u8).encode(s) } },
+                            2 => for diff in diff_iter { try! { (diff.0 as u16).encode(s) } },
+                            4 => for diff in diff_iter { try! { (diff.0 as u32).encode(s) } },
+                            _ => unreachable!()
+                        }
+                    }
+
+                    Ok(())
+                })
+            };
+            s.emit_struct_field("multibyte_chars", 4, |s| {
+                (*self.multibyte_chars.borrow()).encode(s)
+            })
+        })
+    }
+}
+
+impl Decodable for FileMap {
+    fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
+
+        d.read_struct("FileMap", 5, |d| {
+            let name: String = try! {
+                d.read_struct_field("name", 0, |d| Decodable::decode(d))
+            };
+            let start_pos: BytePos = try! {
+                d.read_struct_field("start_pos", 1, |d| Decodable::decode(d))
+            };
+            let end_pos: BytePos = try! {
+                d.read_struct_field("end_pos", 2, |d| Decodable::decode(d))
+            };
+            let lines: Vec<BytePos> = try! {
+                d.read_struct_field("lines", 3, |d| {
+                    let num_lines: u32 = try! { Decodable::decode(d) };
+                    let mut lines = Vec::with_capacity(num_lines as usize);
+
+                    if num_lines > 0 {
+                        // Read the number of bytes used per diff.
+                        let bytes_per_diff: u8 = try! { Decodable::decode(d) };
+
+                        // Read the first element.
+                        let mut line_start: BytePos = try! { Decodable::decode(d) };
+                        lines.push(line_start);
+
+                        for _ in 1..num_lines {
+                            let diff = match bytes_per_diff {
+                                1 => try! { d.read_u8() } as u32,
+                                2 => try! { d.read_u16() } as u32,
+                                4 => try! { d.read_u32() },
+                                _ => unreachable!()
+                            };
+
+                            line_start = line_start + BytePos(diff);
+
+                            lines.push(line_start);
+                        }
+                    }
+
+                    Ok(lines)
+                })
+            };
+            let multibyte_chars: Vec<MultiByteChar> = try! {
+                d.read_struct_field("multibyte_chars", 4, |d| Decodable::decode(d))
+            };
+            Ok(FileMap {
+                name: name,
+                start_pos: start_pos,
+                end_pos: end_pos,
+                src: None,
+                lines: RefCell::new(lines),
+                multibyte_chars: RefCell::new(multibyte_chars)
+            })
+        })
+    }
 }
 
 impl FileMap {
@@ -307,16 +467,21 @@ pub fn next_line(&self, pos: BytePos) {
     /// get a line from the list of pre-computed line-beginnings
     ///
     pub fn get_line(&self, line_number: usize) -> Option<String> {
-        let lines = self.lines.borrow();
-        lines.get(line_number).map(|&line| {
-            let begin: BytePos = line - self.start_pos;
-            let begin = begin.to_usize();
-            let slice = &self.src[begin..];
-            match slice.find('\n') {
-                Some(e) => &slice[..e],
-                None => slice
-            }.to_string()
-        })
+        match self.src {
+            Some(ref src) => {
+                let lines = self.lines.borrow();
+                lines.get(line_number).map(|&line| {
+                    let begin: BytePos = line - self.start_pos;
+                    let begin = begin.to_usize();
+                    let slice = &src[begin..];
+                    match slice.find('\n') {
+                        Some(e) => &slice[..e],
+                        None => slice
+                    }.to_string()
+                })
+            }
+            None => None
+        }
     }
 
     pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
@@ -332,8 +497,17 @@ pub fn is_real_file(&self) -> bool {
         !(self.name.starts_with("<") &&
           self.name.ends_with(">"))
     }
+
+    pub fn is_imported(&self) -> bool {
+        self.src.is_none()
+    }
 }
 
+
+// _____________________________________________________________________________
+// CodeMap
+//
+
 pub struct CodeMap {
     pub files: RefCell<Vec<Rc<FileMap>>>,
     expansions: RefCell<Vec<ExpnInfo>>
@@ -351,7 +525,7 @@ pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
         let mut files = self.files.borrow_mut();
         let start_pos = match files.last() {
             None => 0,
-            Some(last) => last.start_pos.to_usize() + last.src.len(),
+            Some(last) => last.end_pos.to_usize(),
         };
 
         // Remove utf-8 BOM if any.
@@ -372,10 +546,13 @@ pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
             src.push('\n');
         }
 
+        let end_pos = start_pos + src.len();
+
         let filemap = Rc::new(FileMap {
             name: filename,
-            src: src.to_string(),
+            src: Some(Rc::new(src)),
             start_pos: Pos::from_usize(start_pos),
+            end_pos: Pos::from_usize(end_pos),
             lines: RefCell::new(Vec::new()),
             multibyte_chars: RefCell::new(Vec::new()),
         });
@@ -385,6 +562,45 @@ pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
         filemap
     }
 
+    /// Allocates a new FileMap representing a source file from an external
+    /// crate. The source code of such an "imported filemap" is not available,
+    /// but we still know enough to generate accurate debuginfo location
+    /// information for things inlined from other crates.
+    pub fn new_imported_filemap(&self,
+                                filename: FileName,
+                                source_len: usize,
+                                file_local_lines: Vec<BytePos>,
+                                file_local_multibyte_chars: Vec<MultiByteChar>)
+                                -> Rc<FileMap> {
+        let mut files = self.files.borrow_mut();
+        let start_pos = match files.last() {
+            None => 0,
+            Some(last) => last.end_pos.to_usize(),
+        };
+
+        let end_pos = Pos::from_usize(start_pos + source_len);
+        let start_pos = Pos::from_usize(start_pos);
+
+        let lines = file_local_lines.map_in_place(|pos| pos + start_pos);
+        let multibyte_chars = file_local_multibyte_chars.map_in_place(|mbc| MultiByteChar {
+            pos: mbc.pos + start_pos,
+            bytes: mbc.bytes
+        });
+
+        let filemap = Rc::new(FileMap {
+            name: filename,
+            src: None,
+            start_pos: start_pos,
+            end_pos: end_pos,
+            lines: RefCell::new(lines),
+            multibyte_chars: RefCell::new(multibyte_chars),
+        });
+
+        files.push(filemap.clone());
+
+        filemap
+    }
+
     pub fn mk_substr_filename(&self, sp: Span) -> String {
         let pos = self.lookup_char_pos(sp.lo);
         (format!("<{}:{}:{}>",
@@ -442,30 +658,42 @@ pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
             return Err(SpanSnippetError::IllFormedSpan(sp));
         }
 
-        let begin = self.lookup_byte_offset(sp.lo);
-        let end = self.lookup_byte_offset(sp.hi);
+        let local_begin = self.lookup_byte_offset(sp.lo);
+        let local_end = self.lookup_byte_offset(sp.hi);
 
-        if begin.fm.start_pos != end.fm.start_pos {
+        if local_begin.fm.start_pos != local_end.fm.start_pos {
             return Err(SpanSnippetError::DistinctSources(DistinctSources {
-                begin: (begin.fm.name.clone(),
-                        begin.fm.start_pos),
-                end: (end.fm.name.clone(),
-                      end.fm.start_pos)
+                begin: (local_begin.fm.name.clone(),
+                        local_begin.fm.start_pos),
+                end: (local_end.fm.name.clone(),
+                      local_end.fm.start_pos)
             }));
         } else {
-            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,
-                    }));
-            }
+            match local_begin.fm.src {
+                Some(ref src) => {
+                    let start_index = local_begin.pos.to_usize();
+                    let end_index = local_end.pos.to_usize();
+                    let source_len = (local_begin.fm.end_pos -
+                                      local_begin.fm.start_pos).to_usize();
+
+                    if start_index > end_index || end_index > source_len {
+                        return Err(SpanSnippetError::MalformedForCodemap(
+                            MalformedCodemapPositions {
+                                name: local_begin.fm.name.clone(),
+                                source_len: source_len,
+                                begin_pos: local_begin.pos,
+                                end_pos: local_end.pos,
+                            }));
+                    }
 
-            return Ok((&begin.fm.src[start..limit]).to_string())
+                    return Ok((&src[start_index..end_index]).to_string())
+                }
+                None => {
+                    return Err(SpanSnippetError::SourceNotAvailable {
+                        filename: local_begin.fm.name.clone()
+                    });
+                }
+            }
         }
     }
 
@@ -478,6 +706,7 @@ pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
         panic!("asking for {} which we don't know about", filename);
     }
 
+    /// For a global BytePos compute the local offset within the containing FileMap
     pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
         let idx = self.lookup_filemap_idx(bpos);
         let fm = (*self.files.borrow())[idx].clone();
@@ -639,11 +868,16 @@ pub fn span_is_internal(&self, span: Span) -> bool {
     }
 }
 
+// _____________________________________________________________________________
+// SpanSnippetError, DistinctSources, MalformedCodemapPositions
+//
+
 #[derive(Clone, PartialEq, Eq, Debug)]
 pub enum SpanSnippetError {
     IllFormedSpan(Span),
     DistinctSources(DistinctSources),
     MalformedForCodemap(MalformedCodemapPositions),
+    SourceNotAvailable { filename: String }
 }
 
 #[derive(Clone, PartialEq, Eq, Debug)]
@@ -660,6 +894,11 @@ pub struct MalformedCodemapPositions {
     end_pos: BytePos
 }
 
+
+// _____________________________________________________________________________
+// Tests
+//
+
 #[cfg(test)]
 mod test {
     use super::*;
index a6f4974502c211e582b161e6b7e3f8bc2c74c28d..e094cbcac5378a8b3aa59ab8332e13057c12d596 100644 (file)
@@ -223,7 +223,7 @@ pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
 pub fn default_handler(color_config: ColorConfig,
                        registry: Option<diagnostics::registry::Registry>,
                        can_emit_warnings: bool) -> Handler {
-    mk_handler(can_emit_warnings, box EmitterWriter::stderr(color_config, registry))
+    mk_handler(can_emit_warnings, Box::new(EmitterWriter::stderr(color_config, registry)))
 }
 
 pub fn mk_handler(can_emit_warnings: bool, e: Box<Emitter + Send>) -> Handler {
@@ -352,11 +352,11 @@ pub fn stderr(color_config: ColorConfig,
         if use_color {
             let dst = match term::stderr() {
                 Some(t) => Terminal(t),
-                None    => Raw(box stderr),
+                None    => Raw(Box::new(stderr)),
             };
             EmitterWriter { dst: dst, registry: registry }
         } else {
-            EmitterWriter { dst: Raw(box stderr), registry: registry }
+            EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry }
         }
     }
 
index e5d1fe2388c50ee2f01937dfd09f8aa9d194097b..f6bdd693cfa219fea4bd23010f413a502f5bb0e0 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// 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.
 //
@@ -465,7 +465,7 @@ fn initial_syntax_expander_table<'feat>(ecfg: &expand::ExpansionConfig<'feat>)
                                         -> SyntaxEnv {
     // utility function to simplify creating NormalTT syntax extensions
     fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
-        NormalTT(box f, None)
+        NormalTT(Box::new(f), None)
     }
 
     let mut syntax_expanders = SyntaxEnv::new();
@@ -489,9 +489,9 @@ fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
                             builtin_normal_expander(
                                     ext::log_syntax::expand_syntax_ext));
     syntax_expanders.insert(intern("derive"),
-                            Decorator(box ext::deriving::expand_meta_derive));
+                            Decorator(Box::new(ext::deriving::expand_meta_derive)));
     syntax_expanders.insert(intern("deriving"),
-                            Decorator(box ext::deriving::expand_deprecated_deriving));
+                            Decorator(Box::new(ext::deriving::expand_deprecated_deriving)));
 
     if ecfg.enable_quotes() {
         // Quasi-quoting expanders
@@ -519,6 +519,12 @@ fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
         syntax_expanders.insert(intern("quote_stmt"),
                            builtin_normal_expander(
                                 ext::quote::expand_quote_stmt));
+        syntax_expanders.insert(intern("quote_matcher"),
+                           builtin_normal_expander(
+                                ext::quote::expand_quote_matcher));
+        syntax_expanders.insert(intern("quote_attr"),
+                           builtin_normal_expander(
+                                ext::quote::expand_quote_attr));
     }
 
     syntax_expanders.insert(intern("line"),
index 5f460264216a1567182a5c8b63f3d6bb44623455..f89f3ab55f3f90ec064847743f893c2143e4ebf5 100644 (file)
@@ -40,9 +40,9 @@ pub fn expand_deriving_clone<F>(cx: &mut ExtCtxt,
                 args: Vec::new(),
                 ret_ty: Self_,
                 attributes: attrs,
-                combine_substructure: combine_substructure(box |c, s, sub| {
+                combine_substructure: combine_substructure(Box::new(|c, s, sub| {
                     cs_clone("Clone", c, s, sub)
-                }),
+                })),
             }
         ),
         associated_types: Vec::new(),
index 80ef882745f878e152f3d24b29276bf6624db513..c02af437b1c7b987fdca37f696231b14740941bc 100644 (file)
@@ -40,7 +40,7 @@ fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
                 cx.expr_binary(span, ast::BiAnd, subexpr, eq)
             },
             cx.expr_bool(span, true),
-            box |cx, span, _, _| cx.expr_bool(span, false),
+            Box::new(|cx, span, _, _| cx.expr_bool(span, false)),
             cx, span, substr)
     }
     fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
@@ -57,7 +57,7 @@ fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
                 cx.expr_binary(span, ast::BiOr, subexpr, eq)
             },
             cx.expr_bool(span, false),
-            box |cx, span, _, _| cx.expr_bool(span, true),
+            Box::new(|cx, span, _, _| cx.expr_bool(span, true)),
             cx, span, substr)
     }
 
@@ -72,9 +72,9 @@ macro_rules! md {
                 args: vec!(borrowed_self()),
                 ret_ty: Literal(path_local!(bool)),
                 attributes: attrs,
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     $f(a, b, c)
-                })
+                }))
             }
         } }
     }
index be4a33002aa1c69e87f2227fa0e6490e6571c120..b2b2654801863daa9512e5f9d029332282f3ffbc 100644 (file)
@@ -38,9 +38,9 @@ macro_rules! md {
                 args: vec!(borrowed_self()),
                 ret_ty: Literal(path_local!(bool)),
                 attributes: attrs,
-                combine_substructure: combine_substructure(box |cx, span, substr| {
+                combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
                     cs_op($op, $equal, cx, span, substr)
-                })
+                }))
             }
         } }
     }
@@ -61,9 +61,9 @@ macro_rules! md {
         args: vec![borrowed_self()],
         ret_ty: ret_ty,
         attributes: attrs,
-        combine_substructure: combine_substructure(box |cx, span, substr| {
+        combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
             cs_partial_cmp(cx, span, substr)
-        })
+        }))
     };
 
     let trait_def = TraitDef {
@@ -175,13 +175,13 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span,
             cx.expr_block(cx.block(span, vec!(assign), Some(if_)))
         },
         equals_expr.clone(),
-        box |cx, span, (self_args, tag_tuple), _non_self_args| {
+        Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
             if self_args.len() != 2 {
                 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
             } else {
                 some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple)
             }
-        },
+        }),
         cx, span, substr)
 }
 
@@ -223,7 +223,7 @@ fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt,
             cx.expr_binary(span, ast::BiOr, cmp, and)
         },
         cx.expr_bool(span, equal),
-        box |cx, span, (self_args, tag_tuple), _non_self_args| {
+        Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
             if self_args.len() != 2 {
                 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
             } else {
@@ -233,6 +233,6 @@ fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt,
                 };
                 some_ordering_collapsed(cx, span, op, tag_tuple)
             }
-        },
+        }),
         cx, span, substr)
 }
index 31a754a1254bb486c88936b9674afe9c3d31f7c3..83164d242e8fbd730fdcc9784bc4a4bb104403f0 100644 (file)
@@ -32,7 +32,8 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<
             let block = cx.block(span, stmts, None);
             cx.expr_block(block)
         },
-                       box |cx, sp, _, _| cx.span_bug(sp, "non matching enums in derive(Eq)?"),
+                       Box::new(|cx, sp, _, _| {
+                           cx.span_bug(sp, "non matching enums in derive(Eq)?") }),
                        cx,
                        span,
                        substr)
@@ -57,9 +58,9 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<
                 args: vec!(),
                 ret_ty: nil_ty(),
                 attributes: attrs,
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     cs_total_eq_assert(a, b, c)
-                })
+                }))
             }
         ),
         associated_types: Vec::new(),
index 2f6f99bc1ee46211bf4959321e2b09ff43d064db..1de955856e712c208d5375574ccf3e7de76096c4 100644 (file)
@@ -41,9 +41,9 @@ pub fn expand_deriving_totalord<F>(cx: &mut ExtCtxt,
                 args: vec!(borrowed_self()),
                 ret_ty: Literal(path_std!(cx, core::cmp::Ordering)),
                 attributes: attrs,
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     cs_cmp(a, b, c)
-                }),
+                })),
             }
         ),
         associated_types: Vec::new(),
@@ -131,12 +131,12 @@ pub fn cs_cmp(cx: &mut ExtCtxt, span: Span,
             cx.expr_block(cx.block(span, vec!(assign), Some(if_)))
         },
         cx.expr_path(equals_path.clone()),
-        box |cx, span, (self_args, tag_tuple), _non_self_args| {
+        Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
             if self_args.len() != 2 {
                 cx.span_bug(span, "not exactly 2 arguments in `derives(Ord)`")
             } else {
                 ordering_collapsed(cx, span, tag_tuple)
             }
-        },
+        }),
         cx, span, substr)
 }
index f27bbc338e5704b05f89bb5573d3834c1ca01695..6ce68948e4b010615b338836b0e85b49cd853a8b 100644 (file)
@@ -82,9 +82,9 @@ fn expand_deriving_decodable_imp<F>(cx: &mut ExtCtxt,
                     true
                 )),
                 attributes: Vec::new(),
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     decodable_substructure(a, b, c, krate)
-                }),
+                })),
             }
         ),
         associated_types: Vec::new(),
index c10975a2d32eb94e370aa0271267a472b6e5048a..f9991a233547c9dbc24511005df9643b38f65802 100644 (file)
@@ -40,9 +40,9 @@ pub fn expand_deriving_default<F>(cx: &mut ExtCtxt,
                 args: Vec::new(),
                 ret_ty: Self_,
                 attributes: attrs,
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     default_substructure(a, b, c)
-                })
+                }))
             }
         ),
         associated_types: Vec::new(),
index 17687534d750ae81376d2f95effc99541e102344..d7961d7da00f1e2e296bfd2e1f04c0a2b4a18398 100644 (file)
@@ -158,9 +158,9 @@ fn expand_deriving_encodable_imp<F>(cx: &mut ExtCtxt,
                     true
                 )),
                 attributes: Vec::new(),
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     encodable_substructure(a, b, c)
-                }),
+                })),
             }
         ),
         associated_types: Vec::new(),
index 2149c7a7f77a7da72d86848fd952f24a415865ca..da80c7a0e6d15553f240e727654559bb33b71342 100644 (file)
@@ -45,9 +45,9 @@ pub fn expand_deriving_hash<F>(cx: &mut ExtCtxt,
                 args: vec!(Ptr(box Literal(arg), Borrowed(None, MutMutable))),
                 ret_ty: nil_ty(),
                 attributes: vec![],
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     hash_substructure(a, b, c)
-                })
+                }))
             }
         ),
         associated_types: Vec::new(),
index 3b96292323a95039ab6f17535c704ce75023138b..b2d0a9f6b51ad329a30b044332f2d32cbcc37880 100644 (file)
@@ -45,9 +45,9 @@ pub fn expand_deriving_from_primitive<F>(cx: &mut ExtCtxt,
                                            true)),
                 // #[inline] liable to cause code-bloat
                 attributes: attrs.clone(),
-                combine_substructure: combine_substructure(box |c, s, sub| {
+                combine_substructure: combine_substructure(Box::new(|c, s, sub| {
                     cs_from("i64", c, s, sub)
-                }),
+                })),
             },
             MethodDef {
                 name: "from_u64",
@@ -60,9 +60,9 @@ pub fn expand_deriving_from_primitive<F>(cx: &mut ExtCtxt,
                                            true)),
                 // #[inline] liable to cause code-bloat
                 attributes: attrs,
-                combine_substructure: combine_substructure(box |c, s, sub| {
+                combine_substructure: combine_substructure(Box::new(|c, s, sub| {
                     cs_from("u64", c, s, sub)
-                }),
+                })),
             }
         ),
         associated_types: Vec::new(),
index 029b65351081967166e2793c802ce152d16c8bab..8a764fded6fd9d3cf3aca73028cffb07146ae51f 100644 (file)
@@ -55,9 +55,9 @@ pub fn expand_deriving_rand<F>(cx: &mut ExtCtxt,
                 ),
                 ret_ty: Self_,
                 attributes: Vec::new(),
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     rand_substructure(a, b, c)
-                })
+                }))
             }
         ),
         associated_types: Vec::new(),
index 281f23f9e61e8b232d2c083348bdaa90b873b790..ce89c541fd44b89f6677d9193c266c834b80ac30 100644 (file)
@@ -46,9 +46,9 @@ pub fn expand_deriving_show<F>(cx: &mut ExtCtxt,
                 args: vec!(fmtr),
                 ret_ty: Literal(path_std!(cx, core::fmt::Result)),
                 attributes: Vec::new(),
-                combine_substructure: combine_substructure(box |a, b, c| {
+                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                     show_substructure(a, b, c)
-                })
+                }))
             }
         ],
         associated_types: Vec::new(),
index 544fb15dcde7b0a829963bb40cc694e4009d9b30..2599a53e313277cbc430699b5fc436a72121e690 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// 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.
 //
@@ -401,7 +401,7 @@ pub fn expand_quote_tokens<'cx>(cx: &'cx mut ExtCtxt,
                                 tts: &[ast::TokenTree])
                                 -> Box<base::MacResult+'cx> {
     let (cx_expr, expr) = expand_tts(cx, sp, tts);
-    let expanded = expand_wrapper(cx, sp, cx_expr, expr);
+    let expanded = expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]]);
     base::MacEager::expr(expanded)
 }
 
@@ -465,6 +465,32 @@ pub fn expand_quote_stmt(cx: &mut ExtCtxt,
     base::MacEager::expr(expanded)
 }
 
+pub fn expand_quote_attr(cx: &mut ExtCtxt,
+                         sp: Span,
+                         tts: &[ast::TokenTree])
+                         -> Box<base::MacResult+'static> {
+    let expanded = expand_parse_call(cx, sp, "parse_attribute",
+                                    vec!(cx.expr_bool(sp, true)), tts);
+
+    base::MacEager::expr(expanded)
+}
+
+pub fn expand_quote_matcher(cx: &mut ExtCtxt,
+                            sp: Span,
+                            tts: &[ast::TokenTree])
+                            -> Box<base::MacResult+'static> {
+    let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
+    let mut vector = mk_stmts_let(cx, sp);
+    vector.extend(statements_mk_tts(cx, &tts[..], true).into_iter());
+    let block = cx.expr_block(
+        cx.block_all(sp,
+                     vector,
+                     Some(cx.expr_ident(sp, id_ext("tt")))));
+
+    let expanded = expand_wrapper(cx, sp, cx_expr, block, &[&["syntax", "ext", "quote", "rt"]]);
+    base::MacEager::expr(expanded)
+}
+
 fn ids_ext(strs: Vec<String> ) -> Vec<ast::Ident> {
     strs.iter().map(|str| str_to_ident(&(*str))).collect()
 }
@@ -527,7 +553,7 @@ fn mk_delim(cx: &ExtCtxt, sp: Span, delim: token::DelimToken) -> P<ast::Expr> {
 }
 
 #[allow(non_upper_case_globals)]
-fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
+fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
     macro_rules! mk_lit {
         ($name: expr, $suffix: expr, $($args: expr),*) => {{
             let inner = cx.expr_call(sp, mk_token_path(cx, sp, $name), vec![$($args),*]);
@@ -606,6 +632,21 @@ macro_rules! mk_lit {
                                 vec!(mk_name(cx, sp, ident.ident())));
         }
 
+        token::MatchNt(name, kind, namep, kindp) => {
+            return cx.expr_call(sp,
+                                mk_token_path(cx, sp, "MatchNt"),
+                                vec!(mk_ident(cx, sp, name),
+                                     mk_ident(cx, sp, kind),
+                                     match namep {
+                                        ModName => mk_token_path(cx, sp, "ModName"),
+                                        Plain   => mk_token_path(cx, sp, "Plain"),
+                                     },
+                                     match kindp {
+                                        ModName => mk_token_path(cx, sp, "ModName"),
+                                        Plain   => mk_token_path(cx, sp, "Plain"),
+                                     }));
+        }
+
         token::Interpolated(_) => panic!("quote! with interpolated token"),
 
         _ => ()
@@ -642,7 +683,7 @@ macro_rules! mk_lit {
     mk_token_path(cx, sp, name)
 }
 
-fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec<P<ast::Stmt>> {
+fn statements_mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree, matcher: bool) -> Vec<P<ast::Stmt>> {
     match *tt {
         ast::TtToken(sp, SubstNt(ident, _)) => {
             // tt.extend($ident.to_tokens(ext_cx).into_iter())
@@ -663,18 +704,18 @@ fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec<P<ast::Stmt>> {
 
             vec!(cx.stmt_expr(e_push))
         }
-        ref tt @ ast::TtToken(_, MatchNt(..)) => {
+        ref tt @ ast::TtToken(_, MatchNt(..)) if !matcher => {
             let mut seq = vec![];
             for i in 0..tt.len() {
                 seq.push(tt.get_tt(i));
             }
-            mk_tts(cx, &seq[..])
+            statements_mk_tts(cx, &seq[..], matcher)
         }
         ast::TtToken(sp, ref tok) => {
             let e_sp = cx.expr_ident(sp, id_ext("_sp"));
             let e_tok = cx.expr_call(sp,
                                      mk_ast_path(cx, sp, "TtToken"),
-                                     vec!(e_sp, mk_token(cx, sp, tok)));
+                                     vec!(e_sp, expr_mk_token(cx, sp, tok)));
             let e_push =
                 cx.expr_method_call(sp,
                                     cx.expr_ident(sp, id_ext("tt")),
@@ -683,27 +724,61 @@ fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec<P<ast::Stmt>> {
             vec!(cx.stmt_expr(e_push))
         },
         ast::TtDelimited(_, ref delimed) => {
-            mk_tt(cx, &delimed.open_tt()).into_iter()
-                .chain(delimed.tts.iter().flat_map(|tt| mk_tt(cx, tt).into_iter()))
-                .chain(mk_tt(cx, &delimed.close_tt()).into_iter())
+            statements_mk_tt(cx, &delimed.open_tt(), matcher).into_iter()
+                .chain(delimed.tts.iter()
+                                  .flat_map(|tt| statements_mk_tt(cx, tt, matcher).into_iter()))
+                .chain(statements_mk_tt(cx, &delimed.close_tt(), matcher).into_iter())
                 .collect()
         },
-        ast::TtSequence(..) => panic!("TtSequence in quote!"),
-    }
-}
+        ast::TtSequence(sp, ref seq) => {
+            if !matcher {
+                panic!("TtSequence in quote!");
+            }
 
-fn mk_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Vec<P<ast::Stmt>> {
-    let mut ss = Vec::new();
-    for tt in tts {
-        ss.extend(mk_tt(cx, tt).into_iter());
+            let e_sp = cx.expr_ident(sp, id_ext("_sp"));
+
+            let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
+            let mut tts_stmts = vec![stmt_let_tt];
+            tts_stmts.extend(statements_mk_tts(cx, &seq.tts[..], matcher).into_iter());
+            let e_tts = cx.expr_block(cx.block(sp, tts_stmts,
+                                                   Some(cx.expr_ident(sp, id_ext("tt")))));
+            let e_separator = match seq.separator {
+                Some(ref sep) => cx.expr_some(sp, expr_mk_token(cx, sp, sep)),
+                None => cx.expr_none(sp),
+            };
+            let e_op = match seq.op {
+                ast::ZeroOrMore => mk_ast_path(cx, sp, "ZeroOrMore"),
+                ast::OneOrMore => mk_ast_path(cx, sp, "OneOrMore"),
+            };
+            let fields = vec![cx.field_imm(sp, id_ext("tts"), e_tts),
+                              cx.field_imm(sp, id_ext("separator"), e_separator),
+                              cx.field_imm(sp, id_ext("op"), e_op),
+                              cx.field_imm(sp, id_ext("num_captures"),
+                                               cx.expr_usize(sp, seq.num_captures))];
+            let seq_path = vec![id_ext("syntax"), id_ext("ast"), id_ext("SequenceRepetition")];
+            let e_seq_struct = cx.expr_struct(sp, cx.path_global(sp, seq_path), fields);
+            let e_rc_new = cx.expr_call_global(sp, vec![id_ext("std"),
+                                                        id_ext("rc"),
+                                                        id_ext("Rc"),
+                                                        id_ext("new")],
+                                                   vec![e_seq_struct]);
+            let e_tok = cx.expr_call(sp,
+                                     mk_ast_path(cx, sp, "TtSequence"),
+                                     vec!(e_sp, e_rc_new));
+            let e_push =
+                cx.expr_method_call(sp,
+                                    cx.expr_ident(sp, id_ext("tt")),
+                                    id_ext("push"),
+                                    vec!(e_tok));
+            vec!(cx.stmt_expr(e_push))
+        }
     }
-    ss
 }
 
-fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-              -> (P<ast::Expr>, P<ast::Expr>) {
+fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[ast::TokenTree])
+                            -> (P<ast::Expr>, Vec<ast::TokenTree>) {
     // NB: It appears that the main parser loses its mind if we consider
-    // $foo as a TtNonterminal during the main parse, so we have to re-parse
+    // $foo as a SubstNt during the main parse, so we have to re-parse
     // under quote_depth > 0. This is silly and should go away; the _guess_ is
     // it has to do with transition away from supporting old-style macros, so
     // try removing it when enough of them are gone.
@@ -719,6 +794,10 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
     let tts = p.parse_all_token_trees();
     p.abort_if_errors();
 
+    (cx_expr, tts)
+}
+
+fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<P<ast::Stmt>> {
     // We also bind a single value, sp, to ext_cx.call_site()
     //
     // This causes every span in a token-tree quote to be attributed to the
@@ -756,8 +835,23 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
 
     let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
 
-    let mut vector = vec!(stmt_let_sp, stmt_let_tt);
-    vector.extend(mk_tts(cx, &tts[..]).into_iter());
+    vec!(stmt_let_sp, stmt_let_tt)
+}
+
+fn statements_mk_tts(cx: &ExtCtxt, tts: &[ast::TokenTree], matcher: bool) -> Vec<P<ast::Stmt>> {
+    let mut ss = Vec::new();
+    for tt in tts {
+        ss.extend(statements_mk_tt(cx, tt, matcher).into_iter());
+    }
+    ss
+}
+
+fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
+              -> (P<ast::Expr>, P<ast::Expr>) {
+    let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
+
+    let mut vector = mk_stmts_let(cx, sp);
+    vector.extend(statements_mk_tts(cx, &tts[..], false).into_iter());
     let block = cx.expr_block(
         cx.block_all(sp,
                      vector,
@@ -769,14 +863,14 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
 fn expand_wrapper(cx: &ExtCtxt,
                   sp: Span,
                   cx_expr: P<ast::Expr>,
-                  expr: P<ast::Expr>) -> P<ast::Expr> {
+                  expr: P<ast::Expr>,
+                  imports: &[&[&str]]) -> P<ast::Expr> {
     // Explicitly borrow to avoid moving from the invoker (#16992)
     let cx_expr_borrow = cx.expr_addr_of(sp, cx.expr_deref(sp, cx_expr));
     let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr_borrow);
 
-    let stmts = [
-        &["syntax", "ext", "quote", "rt"],
-    ].iter().map(|path| {
+    let stmts = imports.iter().map(|path| {
+        // make item: `use ...;`
         let path = path.iter().map(|s| s.to_string()).collect();
         cx.stmt_item(sp, cx.item_use_glob(sp, ast::Inherited, ids_ext(path)))
     }).chain(Some(stmt_let_ext_cx).into_iter()).collect();
@@ -807,5 +901,10 @@ fn expand_parse_call(cx: &ExtCtxt,
     let expr = cx.expr_method_call(sp, new_parser_call, id_ext(parse_method),
                                    arg_exprs);
 
-    expand_wrapper(cx, sp, cx_expr, expr)
+    if parse_method == "parse_attribute" {
+        expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"],
+                                                &["syntax", "parse", "attr"]])
+    } else {
+        expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]])
+    }
 }
index ba3743cdb335bcf8855af674f06704c605c65aa8..62d98be8b8505e9bca2d0f7f9f64b815f0ef7672 100644 (file)
@@ -20,7 +20,9 @@
 use ptr::P;
 use util::small_vector::SmallVector;
 
-use std::old_io::File;
+use std::fs::File;
+use std::io::prelude::*;
+use std::path::{Path, PathBuf};
 use std::rc::Rc;
 
 // These macros all relate to the file system; they either return
@@ -97,7 +99,7 @@ pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree
                                         cx.cfg(),
                                         &res_rel_file(cx,
                                                       sp,
-                                                      &Path::new(file)),
+                                                      Path::new(&file)),
                                         true,
                                         None,
                                         sp);
@@ -136,8 +138,10 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
         Some(f) => f,
         None => return DummyResult::expr(sp)
     };
-    let file = res_rel_file(cx, sp, &Path::new(file));
-    let bytes = match File::open(&file).read_to_end() {
+    let file = res_rel_file(cx, sp, Path::new(&file));
+    let mut bytes = Vec::new();
+    match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) {
+        Ok(..) => {}
         Err(e) => {
             cx.span_err(sp,
                         &format!("couldn't read {}: {}",
@@ -145,7 +149,6 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
                                 e));
             return DummyResult::expr(sp);
         }
-        Ok(bytes) => bytes,
     };
     match String::from_utf8(bytes) {
         Ok(src) => {
@@ -172,15 +175,15 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
         Some(f) => f,
         None => return DummyResult::expr(sp)
     };
-    let file = res_rel_file(cx, sp, &Path::new(file));
-    match File::open(&file).read_to_end() {
+    let file = res_rel_file(cx, sp, Path::new(&file));
+    let mut bytes = Vec::new();
+    match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) {
         Err(e) => {
             cx.span_err(sp,
                         &format!("couldn't read {}: {}", file.display(), e));
             return DummyResult::expr(sp);
         }
-        Ok(bytes) => {
-            let bytes = bytes.iter().cloned().collect();
+        Ok(..) => {
             base::MacEager::expr(cx.expr_lit(sp, ast::LitBinary(Rc::new(bytes))))
         }
     }
@@ -188,14 +191,18 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
 
 // resolve a file-system path to an absolute file-system path (if it
 // isn't already)
-fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> Path {
+fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> PathBuf {
     // NB: relative paths are resolved relative to the compilation unit
     if !arg.is_absolute() {
-        let mut cu = Path::new(cx.codemap().span_to_filename(sp));
-        cu.pop();
+        let mut cu = PathBuf::new(&cx.codemap().span_to_filename(sp));
+        if cu.parent().is_some() {
+            cu.pop();
+        } else {
+            cu = PathBuf::new("");
+        }
         cu.push(arg);
         cu
     } else {
-        arg.clone()
+        arg.to_path_buf()
     }
 }
index ce513bc91f5a998fda321bb638b4a68bbd0d926c..eb15d708232a097c5572a8c92117601ce0e5ac03 100644 (file)
@@ -243,12 +243,15 @@ fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>],
     ret_val
 }
 
-pub enum ParseResult {
-    Success(HashMap<Ident, Rc<NamedMatch>>),
+pub enum ParseResult<T> {
+    Success(T),
     Failure(codemap::Span, String),
     Error(codemap::Span, String)
 }
 
+pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
+pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>;
+
 pub fn parse_or_else(sess: &ParseSess,
                      cfg: ast::CrateConfig,
                      rdr: TtReader,
@@ -280,7 +283,7 @@ pub fn parse(sess: &ParseSess,
              cfg: ast::CrateConfig,
              mut rdr: TtReader,
              ms: &[TokenTree])
-             -> ParseResult {
+             -> NamedParseResult {
     let mut cur_eis = Vec::new();
     cur_eis.push(initial_matcher_pos(Rc::new(ms.iter()
                                                 .cloned()
@@ -479,7 +482,7 @@ pub fn parse(sess: &ParseSess,
                 }
                 rdr.next_token();
             } else /* bb_eis.len() == 1 */ {
-                let mut rust_parser = Parser::new(sess, cfg.clone(), box rdr.clone());
+                let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone()));
 
                 let mut ei = bb_eis.pop().unwrap();
                 match ei.top_elts.get_tt(ei.idx) {
index 67011ad21a6dd8eec7111f7c07929e9664a0f7ce..d15eb3df6394bb089385369a5f6e71b8cb6e41d5 100644 (file)
@@ -15,7 +15,7 @@
 use ext::tt::macro_parser::{Success, Error, Failure};
 use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
 use ext::tt::macro_parser::{parse, parse_or_else};
-use parse::lexer::{new_tt_reader, new_tt_reader_with_doc_flag};
+use parse::lexer::new_tt_reader;
 use parse::parser::Parser;
 use parse::attr::ParserAttr;
 use parse::token::{self, special_idents, gensym_ident, NtTT, Token};
@@ -154,15 +154,8 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt,
                 TtDelimited(_, ref delim) => &delim.tts[..],
                 _ => cx.span_fatal(sp, "malformed macro lhs")
             };
-            // `None` is because we're not interpolating
-            let arg_rdr = new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
-                                                      None,
-                                                      None,
-                                                      arg.iter()
-                                                         .cloned()
-                                                         .collect(),
-                                                      true);
-            match parse(cx.parse_sess(), cx.cfg(), arg_rdr, lhs_tt) {
+
+            match TokenTree::parse(cx, lhs_tt, arg) {
               Success(named_matches) => {
                 let rhs = match *rhses[i] {
                     // okay, what's your transcriber?
@@ -180,7 +173,7 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt,
                                            Some(named_matches),
                                            imported_from,
                                            rhs);
-                let mut p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr);
+                let mut p = Parser::new(cx.parse_sess(), cx.cfg(), Box::new(trncbr));
                 p.check_unknown_macro_variable();
                 // Let the context choose how to interpret the result.
                 // Weird, but useful for X-macros.
@@ -267,7 +260,7 @@ pub fn compile<'cx>(cx: &'cx mut ExtCtxt,
         _ => cx.span_bug(def.span, "wrong-structured rhs")
     };
 
-    let exp = box MacroRulesMacroExpander {
+    let exp: Box<_> = box MacroRulesMacroExpander {
         name: def.ident,
         imported_from: def.imported_from,
         lhses: lhses,
index a556b2dfd2a99a88104844817f329d13a9f6669e..959e3bdb31476afab4b4065226d41b40d03cc4ca 100644 (file)
@@ -1432,7 +1432,7 @@ pub fn noop_fold_stmt<T: Folder>(Spanned {node, span}: Stmt, folder: &mut T)
 
 #[cfg(test)]
 mod test {
-    use std::old_io;
+    use std::io;
     use ast;
     use util::parser_testing::{string_to_crate, matches_codepattern};
     use parse::token;
@@ -1442,7 +1442,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<()> {
+                        krate: &ast::Crate) -> io::Result<()> {
         s.print_mod(&krate.module, &krate.attrs)
     }
 
index 7acbd10ef03d818476adbcde6be57f32121c134c..7bd9cc3b85515dfd733a9c70657848adb88f1f01 100644 (file)
@@ -36,6 +36,9 @@
 #![feature(staged_api)]
 #![feature(std_misc)]
 #![feature(unicode)]
+#![feature(path)]
+#![feature(fs)]
+#![feature(io)]
 
 extern crate arena;
 extern crate fmt_macros;
index f5201d4a8bc68f73ea9f46c07e6bca61330a561e..25f1f9b8480a1204d71129325688b6f1d43c72be 100644 (file)
@@ -30,7 +30,7 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
 
 impl<T> OwnedSlice<T> {
     pub fn empty() -> OwnedSlice<T> {
-        OwnedSlice  { data: box [] }
+        OwnedSlice  { data: Box::new([]) }
     }
 
     #[inline(never)]
index 3ad1d96a45da77f3edb63e837d8afc2abc83ff43..fb9e0480cebc8b8acdbfdf31691b6ac56bc1de3a 100644 (file)
@@ -19,9 +19,8 @@
 use parse::lexer;
 use print::pprust;
 
-use std::old_io;
+use std::io::Read;
 use std::str;
-use std::string::String;
 use std::usize;
 
 #[derive(Clone, Copy, PartialEq)]
@@ -337,9 +336,10 @@ pub struct Literal {
 // probably not a good thing.
 pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler,
                                     path: String,
-                                    srdr: &mut old_io::Reader)
+                                    srdr: &mut Read)
                                  -> (Vec<Comment>, Vec<Literal>) {
-    let src = srdr.read_to_end().unwrap();
+    let mut src = Vec::new();
+    srdr.read_to_end(&mut src).unwrap();
     let src = String::from_utf8(src).unwrap();
     let cm = CodeMap::new();
     let filemap = cm.new_filemap(path, src);
index 83d2bb0cc70a9b542572ab7ddd6f86a16e80f68c..8d3e93d35ddd1b87ea13ec8f577d392ae1981471 100644 (file)
@@ -76,6 +76,10 @@ pub struct StringReader<'a> {
     // are revised to go directly to token-trees.
     /// Is \x00<name>,<ctxt>\x00 is interpreted as encoded ast::Ident?
     read_embedded_ident: bool,
+
+    // cache a direct reference to the source text, so that we don't have to
+    // retrieve it via `self.filemap.src.as_ref().unwrap()` all the time.
+    source_text: Rc<String>
 }
 
 impl<'a> Reader for StringReader<'a> {
@@ -141,7 +145,14 @@ pub fn make_reader_with_embedded_idents<'b>(span_diagnostic: &'b SpanHandler,
 impl<'a> StringReader<'a> {
     /// For comments.rs, which hackily pokes into pos and curr
     pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
-                   filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
+                       filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
+        if filemap.src.is_none() {
+            span_diagnostic.handler.bug(&format!("Cannot lex filemap without source: {}",
+                                                 filemap.name)[..]);
+        }
+
+        let source_text = (*filemap.src.as_ref().unwrap()).clone();
+
         let mut sr = StringReader {
             span_diagnostic: span_diagnostic,
             pos: filemap.start_pos,
@@ -153,6 +164,7 @@ pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
             peek_tok: token::Eof,
             peek_span: codemap::DUMMY_SP,
             read_embedded_ident: false,
+            source_text: source_text
         };
         sr.bump();
         sr
@@ -213,7 +225,7 @@ fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String)
         m.push_str(": ");
         let from = self.byte_offset(from_pos).to_usize();
         let to = self.byte_offset(to_pos).to_usize();
-        m.push_str(&self.filemap.src[from..to]);
+        m.push_str(&self.source_text[from..to]);
         self.fatal_span_(from_pos, to_pos, &m[..]);
     }
 
@@ -270,9 +282,8 @@ pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
     fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T where
         F: FnOnce(&str) -> T,
     {
-        f(&self.filemap.src[
-                self.byte_offset(start).to_usize()..
-                self.byte_offset(end).to_usize()])
+        f(&self.source_text[self.byte_offset(start).to_usize()..
+                            self.byte_offset(end).to_usize()])
     }
 
     /// Converts CRLF to LF in the given string, raising an error on bare CR.
@@ -321,12 +332,10 @@ fn translate_crlf_(rdr: &StringReader, start: BytePos,
     pub fn bump(&mut self) {
         self.last_pos = self.pos;
         let current_byte_offset = self.byte_offset(self.pos).to_usize();
-        if current_byte_offset < self.filemap.src.len() {
+        if current_byte_offset < self.source_text.len() {
             assert!(self.curr.is_some());
             let last_char = self.curr.unwrap();
-            let next = self.filemap
-                          .src
-                          .char_range_at(current_byte_offset);
+            let next = self.source_text.char_range_at(current_byte_offset);
             let byte_offset_diff = next.next - current_byte_offset;
             self.pos = self.pos + Pos::from_usize(byte_offset_diff);
             self.curr = Some(next.ch);
@@ -346,8 +355,8 @@ pub fn bump(&mut self) {
 
     pub fn nextch(&self) -> Option<char> {
         let offset = self.byte_offset(self.pos).to_usize();
-        if offset < self.filemap.src.len() {
-            Some(self.filemap.src.char_at(offset))
+        if offset < self.source_text.len() {
+            Some(self.source_text.char_at(offset))
         } else {
             None
         }
@@ -359,7 +368,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;
+        let s = &self.source_text[..];
         if offset >= s.len() { return None }
         let str::CharRange { next, .. } = s.char_range_at(offset);
         if next < s.len() {
@@ -1484,8 +1493,9 @@ mod test {
     use std::old_io::util;
 
     fn mk_sh() -> diagnostic::SpanHandler {
-        let emitter = diagnostic::EmitterWriter::new(box util::NullWriter, None);
-        let handler = diagnostic::mk_handler(true, box emitter);
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        let emitter = diagnostic::EmitterWriter::new(Box::new(util::NullWriter), None);
+        let handler = diagnostic::mk_handler(true, Box::new(emitter));
         diagnostic::mk_span_handler(handler, CodeMap::new())
     }
 
index 4d099529cb49ae50439b15fe1b3a03142d419af8..def5963e6f4e961ac28e281e1c85838fdcd70c6a 100644 (file)
 use ptr::P;
 
 use std::cell::{Cell, RefCell};
-use std::old_io::File;
-use std::rc::Rc;
+use std::fs::File;
+use std::io::Read;
+use std::iter;
 use std::num::Int;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
 use std::str;
-use std::iter;
 
 #[macro_use]
 pub mod parser;
@@ -39,7 +41,7 @@
 pub struct ParseSess {
     pub span_diagnostic: SpanHandler, // better be the same as the one in the reader!
     /// Used to determine and report recursive mod inclusions
-    included_mod_stack: RefCell<Vec<Path>>,
+    included_mod_stack: RefCell<Vec<PathBuf>>,
     pub node_id: Cell<ast::NodeId>,
 }
 
@@ -250,24 +252,24 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
             None => sess.span_diagnostic.handler().fatal(msg),
         }
     };
-    let bytes = match File::open(path).read_to_end() {
-        Ok(bytes) => bytes,
+    let mut bytes = Vec::new();
+    match File::open(path).and_then(|mut f| f.read_to_end(&mut bytes)) {
+        Ok(..) => {}
         Err(e) => {
-            err(&format!("couldn't read {:?}: {}",
-                        path.display(), e));
-            unreachable!()
+            err(&format!("couldn't read {:?}: {}", path.display(), e));
+            unreachable!();
         }
     };
     match str::from_utf8(&bytes[..]).ok() {
         Some(s) => {
-            return string_to_filemap(sess, s.to_string(),
-                                     path.as_str().unwrap().to_string())
+            string_to_filemap(sess, s.to_string(),
+                              path.to_str().unwrap().to_string())
         }
         None => {
-            err(&format!("{:?} is not UTF-8 encoded", path.display()))
+            err(&format!("{:?} is not UTF-8 encoded", path.display()));
+            unreachable!();
         }
     }
-    unreachable!()
 }
 
 /// Given a session and a string, add the string to
@@ -751,6 +753,7 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) ->
 #[cfg(test)]
 mod test {
     use super::*;
+    use std::rc::Rc;
     use serialize::json;
     use codemap::{Span, BytePos, Pos, Spanned, NO_EXPANSION};
     use owned_slice::OwnedSlice;
@@ -855,117 +858,50 @@ fn string_to_tts_macro () {
     }
 
     #[test]
-    fn string_to_tts_1 () {
+    fn string_to_tts_1() {
         let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
-        assert_eq!(json::encode(&tts).unwrap(),
-        "[\
-    {\
-        \"variant\":\"TtToken\",\
-        \"fields\":[\
-            null,\
-            {\
-                \"variant\":\"Ident\",\
-                \"fields\":[\
-                    \"fn\",\
-                    \"Plain\"\
-                ]\
-            }\
-        ]\
-    },\
-    {\
-        \"variant\":\"TtToken\",\
-        \"fields\":[\
-            null,\
-            {\
-                \"variant\":\"Ident\",\
-                \"fields\":[\
-                    \"a\",\
-                    \"Plain\"\
-                ]\
-            }\
-        ]\
-    },\
-    {\
-        \"variant\":\"TtDelimited\",\
-        \"fields\":[\
-            null,\
-            {\
-                \"delim\":\"Paren\",\
-                \"open_span\":null,\
-                \"tts\":[\
-                    {\
-                        \"variant\":\"TtToken\",\
-                        \"fields\":[\
-                            null,\
-                            {\
-                                \"variant\":\"Ident\",\
-                                \"fields\":[\
-                                    \"b\",\
-                                    \"Plain\"\
-                                ]\
-                            }\
-                        ]\
-                    },\
-                    {\
-                        \"variant\":\"TtToken\",\
-                        \"fields\":[\
-                            null,\
-                            \"Colon\"\
-                        ]\
-                    },\
-                    {\
-                        \"variant\":\"TtToken\",\
-                        \"fields\":[\
-                            null,\
-                            {\
-                                \"variant\":\"Ident\",\
-                                \"fields\":[\
-                                    \"i32\",\
-                                    \"Plain\"\
-                                ]\
-                            }\
-                        ]\
-                    }\
-                ],\
-                \"close_span\":null\
-            }\
-        ]\
-    },\
-    {\
-        \"variant\":\"TtDelimited\",\
-        \"fields\":[\
-            null,\
-            {\
-                \"delim\":\"Brace\",\
-                \"open_span\":null,\
-                \"tts\":[\
-                    {\
-                        \"variant\":\"TtToken\",\
-                        \"fields\":[\
-                            null,\
-                            {\
-                                \"variant\":\"Ident\",\
-                                \"fields\":[\
-                                    \"b\",\
-                                    \"Plain\"\
-                                ]\
-                            }\
-                        ]\
-                    },\
-                    {\
-                        \"variant\":\"TtToken\",\
-                        \"fields\":[\
-                            null,\
-                            \"Semi\"\
-                        ]\
-                    }\
-                ],\
-                \"close_span\":null\
-            }\
-        ]\
-    }\
-]"
-        );
+
+        let expected = vec![
+            ast::TtToken(sp(0, 2),
+                         token::Ident(str_to_ident("fn"),
+                         token::IdentStyle::Plain)),
+            ast::TtToken(sp(3, 4),
+                         token::Ident(str_to_ident("a"),
+                         token::IdentStyle::Plain)),
+            ast::TtDelimited(
+                sp(5, 14),
+                Rc::new(ast::Delimited {
+                    delim: token::DelimToken::Paren,
+                    open_span: sp(5, 6),
+                    tts: vec![
+                        ast::TtToken(sp(6, 7),
+                                     token::Ident(str_to_ident("b"),
+                                     token::IdentStyle::Plain)),
+                        ast::TtToken(sp(8, 9),
+                                     token::Colon),
+                        ast::TtToken(sp(10, 13),
+                                     token::Ident(str_to_ident("i32"),
+                                     token::IdentStyle::Plain)),
+                    ],
+                    close_span: sp(13, 14),
+                })),
+            ast::TtDelimited(
+                sp(15, 21),
+                Rc::new(ast::Delimited {
+                    delim: token::DelimToken::Brace,
+                    open_span: sp(15, 16),
+                    tts: vec![
+                        ast::TtToken(sp(17, 18),
+                                     token::Ident(str_to_ident("b"),
+                                     token::IdentStyle::Plain)),
+                        ast::TtToken(sp(18, 19),
+                                     token::Semi)
+                    ],
+                    close_span: sp(20, 21),
+                }))
+        ];
+
+        assert_eq!(tts, expected);
     }
 
     #[test] fn ret_expr() {
index c1acee57cf806805630d305e085a29e01589f00f..88df6d6d4cd2fb2bfbf675544be1666dc5de08c9 100644 (file)
 use owned_slice::OwnedSlice;
 
 use std::collections::HashSet;
-use std::old_io::fs::PathExtensions;
+use std::io::prelude::*;
 use std::iter;
 use std::mem;
 use std::num::Float;
+use std::path::{Path, PathBuf};
 use std::rc::Rc;
 use std::slice;
 
@@ -5248,14 +5249,23 @@ fn eval_src_mod(&mut self,
                     outer_attrs: &[ast::Attribute],
                     id_sp: Span)
                     -> (ast::Item_, Vec<ast::Attribute> ) {
-        let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
-        prefix.pop();
-        let mod_path = Path::new(".").join_many(&self.mod_path_stack);
-        let dir_path = prefix.join(&mod_path);
+        let mut prefix = PathBuf::new(&self.sess.span_diagnostic.cm
+                                           .span_to_filename(self.span));
+        // FIXME(acrichto): right now "a".pop() == "a", but need to confirm with
+        //                  aturon whether this is expected or not.
+        if prefix.parent().is_some() {
+            prefix.pop();
+        } else {
+            prefix = PathBuf::new("");
+        }
+        let mut dir_path = prefix;
+        for part in &self.mod_path_stack {
+            dir_path.push(&**part);
+        }
         let mod_string = token::get_ident(id);
         let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
                 outer_attrs, "path") {
-            Some(d) => (dir_path.join(d), true),
+            Some(d) => (dir_path.join(&*d), true),
             None => {
                 let mod_name = mod_string.to_string();
                 let default_path_str = format!("{}.rs", mod_name);
@@ -5319,7 +5329,7 @@ fn eval_src_mod(&mut self,
     }
 
     fn eval_src_mod_from_path(&mut self,
-                              path: Path,
+                              path: PathBuf,
                               owns_directory: bool,
                               name: String,
                               id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
@@ -5329,10 +5339,10 @@ fn eval_src_mod_from_path(&mut self,
                 let mut err = String::from_str("circular modules: ");
                 let len = included_mod_stack.len();
                 for p in &included_mod_stack[i.. len] {
-                    err.push_str(&p.display().as_cow());
+                    err.push_str(&p.to_string_lossy());
                     err.push_str(" -> ");
                 }
-                err.push_str(&path.display().as_cow());
+                err.push_str(&path.to_string_lossy());
                 self.span_fatal(id_sp, &err[..]);
             }
             None => ()
index 4cef7ed469faf794fa99504b878b34f43525f570..640b7d1c91d503db577ccd3b1bed78392452f759 100644 (file)
@@ -59,7 +59,7 @@
 //! line (which it can't) and so naturally place the content on its own line to
 //! avoid combining it with other lines and making matters even worse.
 
-use std::old_io;
+use std::io;
 use std::string;
 use std::iter::repeat;
 
@@ -161,7 +161,7 @@ pub struct PrintStackElem {
 
 const SIZE_INFINITY: isize = 0xffff;
 
-pub fn mk_printer(out: Box<old_io::Writer+'static>, linewidth: usize) -> Printer {
+pub fn mk_printer<'a>(out: Box<io::Write+'a>, linewidth: usize) -> Printer<'a> {
     // Yes 3, it makes the ring buffers big enough to never
     // fall behind.
     let n: usize = 3 * linewidth;
@@ -265,8 +265,8 @@ pub fn mk_printer(out: Box<old_io::Writer+'static>, linewidth: usize) -> Printer
 /// In this implementation (following the paper, again) the SCAN process is
 /// the method called 'pretty_print', and the 'PRINT' process is the method
 /// called 'print'.
-pub struct Printer {
-    pub out: Box<old_io::Writer+'static>,
+pub struct Printer<'a> {
+    pub out: Box<io::Write+'a>,
     buf_len: usize,
     /// Width of lines we're constrained to
     margin: isize,
@@ -303,7 +303,7 @@ pub struct Printer {
     pending_indentation: isize,
 }
 
-impl Printer {
+impl<'a> Printer<'a> {
     pub fn last_token(&mut self) -> Token {
         self.token[self.right].clone()
     }
@@ -311,7 +311,7 @@ pub fn last_token(&mut self) -> Token {
     pub fn replace_last_token(&mut self, t: Token) {
         self.token[self.right] = t;
     }
-    pub fn pretty_print(&mut self, token: Token) -> old_io::IoResult<()> {
+    pub fn pretty_print(&mut self, token: Token) -> io::Result<()> {
         debug!("pp ~[{},{}]", self.left, self.right);
         match token {
           Token::Eof => {
@@ -385,7 +385,7 @@ pub fn pretty_print(&mut self, token: Token) -> old_io::IoResult<()> {
           }
         }
     }
-    pub fn check_stream(&mut self) -> old_io::IoResult<()> {
+    pub fn check_stream(&mut self) -> io::Result<()> {
         debug!("check_stream ~[{}, {}] with left_total={}, right_total={}",
                self.left, self.right, self.left_total, self.right_total);
         if self.right_total - self.left_total > self.space {
@@ -445,7 +445,7 @@ pub fn advance_right(&mut self) {
         self.right %= self.buf_len;
         assert!((self.right != self.left));
     }
-    pub fn advance_left(&mut self) -> old_io::IoResult<()> {
+    pub fn advance_left(&mut self) -> io::Result<()> {
         debug!("advance_left ~[{},{}], sizeof({})={}", self.left, self.right,
                self.left, self.size[self.left]);
 
@@ -506,7 +506,7 @@ pub fn check_stack(&mut self, k: isize) {
             }
         }
     }
-    pub fn print_newline(&mut self, amount: isize) -> old_io::IoResult<()> {
+    pub fn print_newline(&mut self, amount: isize) -> io::Result<()> {
         debug!("NEWLINE {}", amount);
         let ret = write!(self.out, "\n");
         self.pending_indentation = 0;
@@ -529,14 +529,14 @@ pub fn get_top(&mut self) -> PrintStackElem {
             }
         }
     }
-    pub fn print_str(&mut self, s: &str) -> old_io::IoResult<()> {
+    pub fn print_str(&mut self, s: &str) -> io::Result<()> {
         while self.pending_indentation > 0 {
             try!(write!(self.out, " "));
             self.pending_indentation -= 1;
         }
         write!(self.out, "{}", s)
     }
-    pub fn print(&mut self, token: Token, l: isize) -> old_io::IoResult<()> {
+    pub fn print(&mut self, token: Token, l: isize) -> io::Result<()> {
         debug!("print {} {} (remaining line space={})", tok_str(&token), l,
                self.space);
         debug!("{}", buf_str(&self.token,
@@ -620,61 +620,61 @@ pub fn print(&mut self, token: Token, l: isize) -> old_io::IoResult<()> {
 // Convenience functions to talk to the printer.
 //
 // "raw box"
-pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> old_io::IoResult<()> {
+pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> io::Result<()> {
     p.pretty_print(Token::Begin(BeginToken {
         offset: indent as isize,
         breaks: b
     }))
 }
 
-pub fn ibox(p: &mut Printer, indent: usize) -> old_io::IoResult<()> {
+pub fn ibox(p: &mut Printer, indent: usize) -> io::Result<()> {
     rbox(p, indent, Breaks::Inconsistent)
 }
 
-pub fn cbox(p: &mut Printer, indent: usize) -> old_io::IoResult<()> {
+pub fn cbox(p: &mut Printer, indent: usize) -> io::Result<()> {
     rbox(p, indent, Breaks::Consistent)
 }
 
-pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> old_io::IoResult<()> {
+pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> io::Result<()> {
     p.pretty_print(Token::Break(BreakToken {
         offset: off,
         blank_space: n as isize
     }))
 }
 
-pub fn end(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn end(p: &mut Printer) -> io::Result<()> {
     p.pretty_print(Token::End)
 }
 
-pub fn eof(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn eof(p: &mut Printer) -> io::Result<()> {
     p.pretty_print(Token::Eof)
 }
 
-pub fn word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> {
+pub fn word(p: &mut Printer, wrd: &str) -> io::Result<()> {
     p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as isize))
 }
 
-pub fn huge_word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> {
+pub fn huge_word(p: &mut Printer, wrd: &str) -> io::Result<()> {
     p.pretty_print(Token::String(/* bad */ wrd.to_string(), SIZE_INFINITY))
 }
 
-pub fn zero_word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> {
+pub fn zero_word(p: &mut Printer, wrd: &str) -> io::Result<()> {
     p.pretty_print(Token::String(/* bad */ wrd.to_string(), 0))
 }
 
-pub fn spaces(p: &mut Printer, n: usize) -> old_io::IoResult<()> {
+pub fn spaces(p: &mut Printer, n: usize) -> io::Result<()> {
     break_offset(p, n, 0)
 }
 
-pub fn zerobreak(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn zerobreak(p: &mut Printer) -> io::Result<()> {
     spaces(p, 0)
 }
 
-pub fn space(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn space(p: &mut Printer) -> io::Result<()> {
     spaces(p, 1)
 }
 
-pub fn hardbreak(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn hardbreak(p: &mut Printer) -> io::Result<()> {
     spaces(p, SIZE_INFINITY as usize)
 }
 
index af16e19c9f034a1c33399045ef009407cdbf09c1..883c2295a3655340107d9a644e70cf7bf4b01d0d 100644 (file)
@@ -30,7 +30,7 @@
 use std_inject;
 
 use std::{ascii, mem};
-use std::old_io::{self, IoResult};
+use std::io::{self, Write, Read};
 use std::iter;
 
 pub enum AnnNode<'a> {
@@ -43,8 +43,8 @@ pub enum AnnNode<'a> {
 }
 
 pub trait PpAnn {
-    fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
-    fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
+    fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
+    fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
 }
 
 #[derive(Copy)]
@@ -59,7 +59,7 @@ pub struct CurrentCommentAndLiteral {
 }
 
 pub struct State<'a> {
-    pub s: pp::Printer,
+    pub s: pp::Printer<'a>,
     cm: Option<&'a CodeMap>,
     comments: Option<Vec<comments::Comment> >,
     literals: Option<Vec<comments::Literal> >,
@@ -69,12 +69,12 @@ pub struct State<'a> {
     encode_idents_with_hygiene: bool,
 }
 
-pub fn rust_printer(writer: Box<old_io::Writer+'static>) -> State<'static> {
+pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
     static NO_ANN: NoAnn = NoAnn;
     rust_printer_annotated(writer, &NO_ANN)
 }
 
-pub fn rust_printer_annotated<'a>(writer: Box<old_io::Writer+'static>,
+pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
                                   ann: &'a PpAnn) -> State<'a> {
     State {
         s: pp::mk_printer(writer, default_columns),
@@ -104,10 +104,10 @@ pub fn print_crate<'a>(cm: &'a CodeMap,
                        span_diagnostic: &diagnostic::SpanHandler,
                        krate: &ast::Crate,
                        filename: String,
-                       input: &mut old_io::Reader,
-                       out: Box<old_io::Writer+'static>,
+                       input: &mut Read,
+                       out: Box<Write+'a>,
                        ann: &'a PpAnn,
-                       is_expanded: bool) -> IoResult<()> {
+                       is_expanded: bool) -> io::Result<()> {
     let mut s = State::new_from_input(cm,
                                       span_diagnostic,
                                       filename,
@@ -143,8 +143,8 @@ impl<'a> State<'a> {
     pub fn new_from_input(cm: &'a CodeMap,
                           span_diagnostic: &diagnostic::SpanHandler,
                           filename: String,
-                          input: &mut old_io::Reader,
-                          out: Box<old_io::Writer+'static>,
+                          input: &mut Read,
+                          out: Box<Write+'a>,
                           ann: &'a PpAnn,
                           is_expanded: bool) -> State<'a> {
         let (cmnts, lits) = comments::gather_comments_and_literals(
@@ -164,7 +164,7 @@ pub fn new_from_input(cm: &'a CodeMap,
     }
 
     pub fn new(cm: &'a CodeMap,
-               out: Box<old_io::Writer+'static>,
+               out: Box<Write+'a>,
                ann: &'a PpAnn,
                comments: Option<Vec<comments::Comment>>,
                literals: Option<Vec<comments::Literal>>) -> State<'a> {
@@ -185,14 +185,14 @@ pub fn new(cm: &'a CodeMap,
 }
 
 pub fn to_string<F>(f: F) -> String where
-    F: FnOnce(&mut State) -> IoResult<()>,
+    F: FnOnce(&mut State) -> io::Result<()>,
 {
     use std::raw::TraitObject;
     let mut s = rust_printer(box Vec::new());
     f(&mut s).unwrap();
     eof(&mut s.s).unwrap();
     let wr = unsafe {
-        // FIXME(pcwalton): A nasty function to extract the string from an `old_io::Writer`
+        // FIXME(pcwalton): A nasty function to extract the string from an `Write`
         // that we "know" to be a `Vec<u8>` that works around the lack of checked
         // downcasts.
         let obj: &TraitObject = mem::transmute(&s.s.out);
@@ -440,13 +440,13 @@ pub fn mac_to_string(arg: &ast::Mac) -> String {
 pub mod with_hygiene {
     use abi;
     use ast;
-    use std::old_io::IoResult;
+    use std::io;
     use super::indent_unit;
 
     // This function is the trick that all the rest of the routines
     // hang on.
     pub fn to_string_hyg<F>(f: F) -> String where
-        F: FnOnce(&mut super::State) -> IoResult<()>,
+        F: FnOnce(&mut super::State) -> io::Result<()>,
     {
         super::to_string(move |s| {
             s.encode_idents_with_hygiene = true;
@@ -474,44 +474,44 @@ fn needs_parentheses(expr: &ast::Expr) -> bool {
 }
 
 impl<'a> State<'a> {
-    pub fn ibox(&mut self, u: usize) -> IoResult<()> {
+    pub fn ibox(&mut self, u: usize) -> io::Result<()> {
         self.boxes.push(pp::Breaks::Inconsistent);
         pp::ibox(&mut self.s, u)
     }
 
-    pub fn end(&mut self) -> IoResult<()> {
+    pub fn end(&mut self) -> io::Result<()> {
         self.boxes.pop().unwrap();
         pp::end(&mut self.s)
     }
 
-    pub fn cbox(&mut self, u: usize) -> IoResult<()> {
+    pub fn cbox(&mut self, u: usize) -> io::Result<()> {
         self.boxes.push(pp::Breaks::Consistent);
         pp::cbox(&mut self.s, u)
     }
 
     // "raw box"
-    pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> IoResult<()> {
+    pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
         self.boxes.push(b);
         pp::rbox(&mut self.s, u, b)
     }
 
-    pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
+    pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
 
-    pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
+    pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
         try!(word(&mut self.s, w));
         self.nbsp()
     }
 
-    pub fn word_space(&mut self, w: &str) -> IoResult<()> {
+    pub fn word_space(&mut self, w: &str) -> io::Result<()> {
         try!(word(&mut self.s, w));
         space(&mut self.s)
     }
 
-    pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
+    pub fn popen(&mut self) -> io::Result<()> { word(&mut self.s, "(") }
 
-    pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
+    pub fn pclose(&mut self) -> io::Result<()> { word(&mut self.s, ")") }
 
-    pub fn head(&mut self, w: &str) -> IoResult<()> {
+    pub fn head(&mut self, w: &str) -> io::Result<()> {
         // outer-box is consistent
         try!(self.cbox(indent_unit));
         // head-box is inconsistent
@@ -523,17 +523,17 @@ pub fn head(&mut self, w: &str) -> IoResult<()> {
         Ok(())
     }
 
-    pub fn bopen(&mut self) -> IoResult<()> {
+    pub fn bopen(&mut self) -> io::Result<()> {
         try!(word(&mut self.s, "{"));
         self.end() // close the head-box
     }
 
     pub fn bclose_(&mut self, span: codemap::Span,
-                   indented: usize) -> IoResult<()> {
+                   indented: usize) -> io::Result<()> {
         self.bclose_maybe_open(span, indented, true)
     }
     pub fn bclose_maybe_open (&mut self, span: codemap::Span,
-                              indented: usize, close_box: bool) -> IoResult<()> {
+                              indented: usize, close_box: bool) -> io::Result<()> {
         try!(self.maybe_print_comment(span.hi));
         try!(self.break_offset_if_not_bol(1, -(indented as isize)));
         try!(word(&mut self.s, "}"));
@@ -542,7 +542,7 @@ pub fn bclose_maybe_open (&mut self, span: codemap::Span,
         }
         Ok(())
     }
-    pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
+    pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
         self.bclose_(span, indent_unit)
     }
 
@@ -572,18 +572,18 @@ pub fn in_cbox(&self) -> bool {
         }
     }
 
-    pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
+    pub fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
         if !self.is_bol() {
             try!(hardbreak(&mut self.s))
         }
         Ok(())
     }
-    pub fn space_if_not_bol(&mut self) -> IoResult<()> {
+    pub fn space_if_not_bol(&mut self) -> io::Result<()> {
         if !self.is_bol() { try!(space(&mut self.s)); }
         Ok(())
     }
     pub fn break_offset_if_not_bol(&mut self, n: usize,
-                                   off: isize) -> IoResult<()> {
+                                   off: isize) -> io::Result<()> {
         if !self.is_bol() {
             break_offset(&mut self.s, n, off)
         } else {
@@ -599,7 +599,7 @@ pub fn break_offset_if_not_bol(&mut self, n: usize,
 
     // Synthesizes a comment that was not textually present in the original source
     // file.
-    pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
+    pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
         try!(word(&mut self.s, "/*"));
         try!(space(&mut self.s));
         try!(word(&mut self.s, &text[..]));
@@ -607,8 +607,8 @@ pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
         word(&mut self.s, "*/")
     }
 
-    pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> IoResult<()> where
-        F: FnMut(&mut State, &T) -> IoResult<()>,
+    pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> where
+        F: FnMut(&mut State, &T) -> io::Result<()>,
     {
         try!(self.rbox(0, b));
         let mut first = true;
@@ -624,8 +624,8 @@ pub fn commasep_cmnt<T, F, G>(&mut self,
                                   b: Breaks,
                                   elts: &[T],
                                   mut op: F,
-                                  mut get_span: G) -> IoResult<()> where
-        F: FnMut(&mut State, &T) -> IoResult<()>,
+                                  mut get_span: G) -> io::Result<()> where
+        F: FnMut(&mut State, &T) -> io::Result<()>,
         G: FnMut(&T) -> codemap::Span,
     {
         try!(self.rbox(0, b));
@@ -646,12 +646,12 @@ pub fn commasep_cmnt<T, F, G>(&mut self,
     }
 
     pub fn commasep_exprs(&mut self, b: Breaks,
-                          exprs: &[P<ast::Expr>]) -> IoResult<()> {
+                          exprs: &[P<ast::Expr>]) -> io::Result<()> {
         self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
     }
 
     pub fn print_mod(&mut self, _mod: &ast::Mod,
-                     attrs: &[ast::Attribute]) -> IoResult<()> {
+                     attrs: &[ast::Attribute]) -> io::Result<()> {
         try!(self.print_inner_attributes(attrs));
         for item in &_mod.items {
             try!(self.print_item(&**item));
@@ -660,7 +660,7 @@ pub fn print_mod(&mut self, _mod: &ast::Mod,
     }
 
     pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
-                             attrs: &[ast::Attribute]) -> IoResult<()> {
+                             attrs: &[ast::Attribute]) -> io::Result<()> {
         try!(self.print_inner_attributes(attrs));
         for item in &nmod.items {
             try!(self.print_foreign_item(&**item));
@@ -669,7 +669,7 @@ pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
     }
 
     pub fn print_opt_lifetime(&mut self,
-                              lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
+                              lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
         if let Some(l) = *lifetime {
             try!(self.print_lifetime(&l));
             try!(self.nbsp());
@@ -677,7 +677,7 @@ pub fn print_opt_lifetime(&mut self,
         Ok(())
     }
 
-    pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
+    pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
         try!(self.maybe_print_comment(ty.span.lo));
         try!(self.ibox(0));
         match ty.node {
@@ -762,7 +762,7 @@ pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
     }
 
     pub fn print_foreign_item(&mut self,
-                              item: &ast::ForeignItem) -> IoResult<()> {
+                              item: &ast::ForeignItem) -> io::Result<()> {
         try!(self.hardbreak_if_not_bol());
         try!(self.maybe_print_comment(item.span.lo));
         try!(self.print_outer_attributes(&item.attrs));
@@ -791,7 +791,7 @@ pub fn print_foreign_item(&mut self,
     }
 
     fn print_associated_type(&mut self, typedef: &ast::AssociatedType)
-                             -> IoResult<()>
+                             -> io::Result<()>
     {
         try!(self.print_outer_attributes(&typedef.attrs));
         try!(self.word_space("type"));
@@ -799,7 +799,7 @@ fn print_associated_type(&mut self, typedef: &ast::AssociatedType)
         word(&mut self.s, ";")
     }
 
-    fn print_typedef(&mut self, typedef: &ast::Typedef) -> IoResult<()> {
+    fn print_typedef(&mut self, typedef: &ast::Typedef) -> io::Result<()> {
         try!(self.word_space("type"));
         try!(self.print_ident(typedef.ident));
         try!(space(&mut self.s));
@@ -809,7 +809,7 @@ fn print_typedef(&mut self, typedef: &ast::Typedef) -> IoResult<()> {
     }
 
     /// Pretty-print an item
-    pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
+    pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
         try!(self.hardbreak_if_not_bol());
         try!(self.maybe_print_comment(item.span.lo));
         try!(self.print_outer_attributes(&item.attrs));
@@ -1032,11 +1032,11 @@ pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
         self.ann.post(self, NodeItem(item))
     }
 
-    fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
+    fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
         self.print_path(&t.path, false, 0)
     }
 
-    fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> IoResult<()> {
+    fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
         if !lifetimes.is_empty() {
             try!(word(&mut self.s, "for<"));
             let mut comma = false;
@@ -1052,7 +1052,7 @@ fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> IoRe
         Ok(())
     }
 
-    fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
+    fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
         try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
         self.print_trait_ref(&t.trait_ref)
     }
@@ -1060,7 +1060,7 @@ fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
     pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
                           generics: &ast::Generics, ident: ast::Ident,
                           span: codemap::Span,
-                          visibility: ast::Visibility) -> IoResult<()> {
+                          visibility: ast::Visibility) -> io::Result<()> {
         try!(self.head(&visibility_qualified(visibility, "enum")));
         try!(self.print_ident(ident));
         try!(self.print_generics(generics));
@@ -1071,7 +1071,7 @@ pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
 
     pub fn print_variants(&mut self,
                           variants: &[P<ast::Variant>],
-                          span: codemap::Span) -> IoResult<()> {
+                          span: codemap::Span) -> io::Result<()> {
         try!(self.bopen());
         for v in variants {
             try!(self.space_if_not_bol());
@@ -1086,7 +1086,7 @@ pub fn print_variants(&mut self,
         self.bclose(span)
     }
 
-    pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
+    pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
         match vis {
             ast::Public => self.word_nbsp("pub"),
             ast::Inherited => Ok(())
@@ -1097,7 +1097,7 @@ pub fn print_struct(&mut self,
                         struct_def: &ast::StructDef,
                         generics: &ast::Generics,
                         ident: ast::Ident,
-                        span: codemap::Span) -> IoResult<()> {
+                        span: codemap::Span) -> io::Result<()> {
         try!(self.print_ident(ident));
         try!(self.print_generics(generics));
         if ast_util::struct_def_is_tuple_like(struct_def) {
@@ -1155,7 +1155,7 @@ pub fn print_struct(&mut self,
     /// appropriate macro, transcribe back into the grammar we just parsed from,
     /// and then pretty-print the resulting AST nodes (so, e.g., we print
     /// expression arguments as expressions). It can be done! I think.
-    pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
+    pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
         match *tt {
             ast::TtToken(_, ref tk) => {
                 try!(word(&mut self.s, &token_to_string(tk)));
@@ -1193,7 +1193,7 @@ pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
         }
     }
 
-    pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
+    pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
         try!(self.ibox(0));
         let mut suppress_space = false;
         for (i, tt) in tts.iter().enumerate() {
@@ -1213,7 +1213,7 @@ pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
         self.end()
     }
 
-    pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
+    pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
         try!(self.print_visibility(v.node.vis));
         match v.node.kind {
             ast::TupleVariantKind(ref args) => {
@@ -1242,7 +1242,7 @@ pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
         }
     }
 
-    pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
+    pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> io::Result<()> {
         try!(self.hardbreak_if_not_bol());
         try!(self.maybe_print_comment(m.span.lo));
         try!(self.print_outer_attributes(&m.attrs));
@@ -1256,7 +1256,7 @@ pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
     }
 
     pub fn print_trait_method(&mut self,
-                              m: &ast::TraitItem) -> IoResult<()> {
+                              m: &ast::TraitItem) -> io::Result<()> {
         match *m {
             RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
             ProvidedMethod(ref m) => self.print_method(&**m),
@@ -1264,14 +1264,14 @@ pub fn print_trait_method(&mut self,
         }
     }
 
-    pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
+    pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
         match *ii {
             MethodImplItem(ref m) => self.print_method(&**m),
             TypeImplItem(ref td) => self.print_typedef(&**td),
         }
     }
 
-    pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
+    pub fn print_method(&mut self, meth: &ast::Method) -> io::Result<()> {
         try!(self.hardbreak_if_not_bol());
         try!(self.maybe_print_comment(meth.span.lo));
         try!(self.print_outer_attributes(&meth.attrs));
@@ -1310,7 +1310,7 @@ pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
     }
 
     pub fn print_outer_attributes(&mut self,
-                                  attrs: &[ast::Attribute]) -> IoResult<()> {
+                                  attrs: &[ast::Attribute]) -> io::Result<()> {
         let mut count = 0;
         for attr in attrs {
             match attr.node.style {
@@ -1328,7 +1328,7 @@ pub fn print_outer_attributes(&mut self,
     }
 
     pub fn print_inner_attributes(&mut self,
-                                  attrs: &[ast::Attribute]) -> IoResult<()> {
+                                  attrs: &[ast::Attribute]) -> io::Result<()> {
         let mut count = 0;
         for attr in attrs {
             match attr.node.style {
@@ -1345,7 +1345,7 @@ pub fn print_inner_attributes(&mut self,
         Ok(())
     }
 
-    pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
+    pub fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
         try!(self.hardbreak_if_not_bol());
         try!(self.maybe_print_comment(attr.span.lo));
         if attr.node.is_sugared_doc {
@@ -1361,7 +1361,7 @@ pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
     }
 
 
-    pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
+    pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
         try!(self.maybe_print_comment(st.span.lo));
         match st.node {
             ast::StmtDecl(ref decl, _) => {
@@ -1395,22 +1395,22 @@ pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
         self.maybe_print_trailing_comment(st.span, None)
     }
 
-    pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
+    pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
         self.print_block_with_attrs(blk, &[])
     }
 
-    pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
+    pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
         self.print_block_unclosed_indent(blk, indent_unit)
     }
 
     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
-                                       indented: usize) -> IoResult<()> {
+                                       indented: usize) -> io::Result<()> {
         self.print_block_maybe_unclosed(blk, indented, &[], false)
     }
 
     pub fn print_block_with_attrs(&mut self,
                                   blk: &ast::Block,
-                                  attrs: &[ast::Attribute]) -> IoResult<()> {
+                                  attrs: &[ast::Attribute]) -> io::Result<()> {
         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
     }
 
@@ -1418,7 +1418,7 @@ pub fn print_block_maybe_unclosed(&mut self,
                                       blk: &ast::Block,
                                       indented: usize,
                                       attrs: &[ast::Attribute],
-                                      close_box: bool) -> IoResult<()> {
+                                      close_box: bool) -> io::Result<()> {
         match blk.rules {
             ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
             ast::DefaultBlock => ()
@@ -1444,7 +1444,7 @@ pub fn print_block_maybe_unclosed(&mut self,
         self.ann.post(self, NodeBlock(blk))
     }
 
-    fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
+    fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
         match els {
             Some(_else) => {
                 match _else.node {
@@ -1489,7 +1489,7 @@ fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
     }
 
     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
-                    elseopt: Option<&ast::Expr>) -> IoResult<()> {
+                    elseopt: Option<&ast::Expr>) -> io::Result<()> {
         try!(self.head("if"));
         try!(self.print_expr(test));
         try!(space(&mut self.s));
@@ -1498,7 +1498,7 @@ pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
     }
 
     pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
-                        elseopt: Option<&ast::Expr>) -> IoResult<()> {
+                        elseopt: Option<&ast::Expr>) -> io::Result<()> {
         try!(self.head("if let"));
         try!(self.print_pat(pat));
         try!(space(&mut self.s));
@@ -1510,7 +1510,7 @@ pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Bloc
     }
 
     pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
-                     -> IoResult<()> {
+                     -> io::Result<()> {
         match m.node {
             // I think it's reasonable to hide the ctxt here:
             ast::MacInvocTT(ref pth, ref tts, _) => {
@@ -1532,13 +1532,13 @@ pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
     }
 
 
-    fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> IoResult<()> {
+    fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
         try!(self.popen());
         try!(self.commasep_exprs(Inconsistent, args));
         self.pclose()
     }
 
-    pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
+    pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
         let needs_par = needs_parentheses(expr);
         if needs_par {
             try!(self.popen());
@@ -1552,7 +1552,7 @@ pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
 
     fn print_expr_box(&mut self,
                       place: &Option<P<ast::Expr>>,
-                      expr: &ast::Expr) -> IoResult<()> {
+                      expr: &ast::Expr) -> io::Result<()> {
         try!(word(&mut self.s, "box"));
         try!(word(&mut self.s, "("));
         try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
@@ -1560,7 +1560,7 @@ fn print_expr_box(&mut self,
         self.print_expr(expr)
     }
 
-    fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> IoResult<()> {
+    fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
         try!(self.ibox(indent_unit));
         try!(word(&mut self.s, "["));
         try!(self.commasep_exprs(Inconsistent, &exprs[..]));
@@ -1570,7 +1570,7 @@ fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> IoResult<()> {
 
     fn print_expr_repeat(&mut self,
                          element: &ast::Expr,
-                         count: &ast::Expr) -> IoResult<()> {
+                         count: &ast::Expr) -> io::Result<()> {
         try!(self.ibox(indent_unit));
         try!(word(&mut self.s, "["));
         try!(self.print_expr(element));
@@ -1583,7 +1583,7 @@ fn print_expr_repeat(&mut self,
     fn print_expr_struct(&mut self,
                          path: &ast::Path,
                          fields: &[ast::Field],
-                         wth: &Option<P<ast::Expr>>) -> IoResult<()> {
+                         wth: &Option<P<ast::Expr>>) -> io::Result<()> {
         try!(self.print_path(path, true, 0));
         if !(fields.is_empty() && wth.is_none()) {
             try!(word(&mut self.s, "{"));
@@ -1616,7 +1616,7 @@ fn print_expr_struct(&mut self,
         Ok(())
     }
 
-    fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> IoResult<()> {
+    fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
         try!(self.popen());
         try!(self.commasep_exprs(Inconsistent, &exprs[..]));
         if exprs.len() == 1 {
@@ -1627,7 +1627,7 @@ fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> IoResult<()> {
 
     fn print_expr_call(&mut self,
                        func: &ast::Expr,
-                       args: &[P<ast::Expr>]) -> IoResult<()> {
+                       args: &[P<ast::Expr>]) -> io::Result<()> {
         try!(self.print_expr_maybe_paren(func));
         self.print_call_post(args)
     }
@@ -1635,7 +1635,7 @@ fn print_expr_call(&mut self,
     fn print_expr_method_call(&mut self,
                               ident: ast::SpannedIdent,
                               tys: &[P<ast::Ty>],
-                              args: &[P<ast::Expr>]) -> IoResult<()> {
+                              args: &[P<ast::Expr>]) -> io::Result<()> {
         let base_args = &args[1..];
         try!(self.print_expr(&*args[0]));
         try!(word(&mut self.s, "."));
@@ -1652,7 +1652,7 @@ fn print_expr_method_call(&mut self,
     fn print_expr_binary(&mut self,
                          op: ast::BinOp,
                          lhs: &ast::Expr,
-                         rhs: &ast::Expr) -> IoResult<()> {
+                         rhs: &ast::Expr) -> io::Result<()> {
         try!(self.print_expr(lhs));
         try!(space(&mut self.s));
         try!(self.word_space(ast_util::binop_to_string(op.node)));
@@ -1661,20 +1661,20 @@ fn print_expr_binary(&mut self,
 
     fn print_expr_unary(&mut self,
                         op: ast::UnOp,
-                        expr: &ast::Expr) -> IoResult<()> {
+                        expr: &ast::Expr) -> io::Result<()> {
         try!(word(&mut self.s, ast_util::unop_to_string(op)));
         self.print_expr_maybe_paren(expr)
     }
 
     fn print_expr_addr_of(&mut self,
                           mutability: ast::Mutability,
-                          expr: &ast::Expr) -> IoResult<()> {
+                          expr: &ast::Expr) -> io::Result<()> {
         try!(word(&mut self.s, "&"));
         try!(self.print_mutability(mutability));
         self.print_expr_maybe_paren(expr)
     }
 
-    pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
+    pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
         try!(self.maybe_print_comment(expr.span.lo));
         try!(self.ibox(indent_unit));
         try!(self.ann.pre(self, NodeExpr(expr)));
@@ -1958,7 +1958,7 @@ pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
         self.end()
     }
 
-    pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
+    pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
         try!(self.print_pat(&*loc.pat));
         if let Some(ref ty) = loc.ty {
             try!(self.word_space(":"));
@@ -1967,7 +1967,7 @@ pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
         Ok(())
     }
 
-    pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
+    pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
         try!(self.maybe_print_comment(decl.span.lo));
         match decl.node {
             ast::DeclLocal(ref loc) => {
@@ -1989,7 +1989,7 @@ pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
         }
     }
 
-    pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
+    pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
         if self.encode_idents_with_hygiene {
             let encoded = ident.encode_with_hygiene();
             try!(word(&mut self.s, &encoded[..]))
@@ -1999,17 +1999,17 @@ pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
         self.ann.post(self, NodeIdent(&ident))
     }
 
-    pub fn print_usize(&mut self, i: usize) -> IoResult<()> {
+    pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
         word(&mut self.s, &i.to_string())
     }
 
-    pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
+    pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
         try!(word(&mut self.s, &token::get_name(name)));
         self.ann.post(self, NodeName(&name))
     }
 
     pub fn print_for_decl(&mut self, loc: &ast::Local,
-                          coll: &ast::Expr) -> IoResult<()> {
+                          coll: &ast::Expr) -> io::Result<()> {
         try!(self.print_local_decl(loc));
         try!(space(&mut self.s));
         try!(self.word_space("in"));
@@ -2020,7 +2020,7 @@ fn print_path(&mut self,
                   path: &ast::Path,
                   colons_before_params: bool,
                   depth: usize)
-                  -> IoResult<()>
+                  -> io::Result<()>
     {
         try!(self.maybe_print_comment(path.span.lo));
 
@@ -2044,7 +2044,7 @@ fn print_qpath(&mut self,
                    path: &ast::Path,
                    qself: &ast::QSelf,
                    colons_before_params: bool)
-                   -> IoResult<()>
+                   -> io::Result<()>
     {
         try!(word(&mut self.s, "<"));
         try!(self.print_type(&qself.ty));
@@ -2064,7 +2064,7 @@ fn print_qpath(&mut self,
     fn print_path_parameters(&mut self,
                              parameters: &ast::PathParameters,
                              colons_before_params: bool)
-                             -> IoResult<()>
+                             -> io::Result<()>
     {
         if parameters.is_empty() {
             return Ok(());
@@ -2134,7 +2134,7 @@ fn print_path_parameters(&mut self,
         Ok(())
     }
 
-    pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
+    pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
         try!(self.maybe_print_comment(pat.span.lo));
         try!(self.ann.pre(self, NodePat(pat)));
         /* Pat isn't normalized, but the beauty of it
@@ -2253,7 +2253,7 @@ pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
         self.ann.post(self, NodePat(pat))
     }
 
-    fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
+    fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
         // I have no idea why this check is necessary, but here it
         // is :(
         if arm.attrs.is_empty() {
@@ -2302,7 +2302,7 @@ fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
     // Returns whether it printed anything
     fn print_explicit_self(&mut self,
                            explicit_self: &ast::ExplicitSelf_,
-                           mutbl: ast::Mutability) -> IoResult<bool> {
+                           mutbl: ast::Mutability) -> io::Result<bool> {
         try!(self.print_mutability(mutbl));
         match *explicit_self {
             ast::SelfStatic => { return Ok(false); }
@@ -2331,7 +2331,7 @@ pub fn print_fn(&mut self,
                     name: ast::Ident,
                     generics: &ast::Generics,
                     opt_explicit_self: Option<&ast::ExplicitSelf_>,
-                    vis: ast::Visibility) -> IoResult<()> {
+                    vis: ast::Visibility) -> io::Result<()> {
         try!(self.head(""));
         try!(self.print_fn_header_info(unsafety, abi, vis));
         try!(self.nbsp());
@@ -2343,7 +2343,7 @@ pub fn print_fn(&mut self,
 
     pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
                          opt_explicit_self: Option<&ast::ExplicitSelf_>)
-        -> IoResult<()> {
+        -> io::Result<()> {
         // It is unfortunate to duplicate the commasep logic, but we want the
         // self type and the args all in the same box.
         try!(self.rbox(0, Inconsistent));
@@ -2376,7 +2376,7 @@ pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
 
     pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
                                  opt_explicit_self: Option<&ast::ExplicitSelf_>)
-        -> IoResult<()> {
+        -> io::Result<()> {
         try!(self.popen());
         try!(self.print_fn_args(decl, opt_explicit_self));
         if decl.variadic {
@@ -2390,7 +2390,7 @@ pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
     pub fn print_fn_block_args(
             &mut self,
             decl: &ast::FnDecl)
-            -> IoResult<()> {
+            -> io::Result<()> {
         try!(word(&mut self.s, "|"));
         try!(self.print_fn_args(decl, None));
         try!(word(&mut self.s, "|"));
@@ -2415,7 +2415,7 @@ pub fn print_fn_block_args(
     }
 
     pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
-                                -> IoResult<()> {
+                                -> io::Result<()> {
         match capture_clause {
             ast::CaptureByValue => self.word_space("move"),
             ast::CaptureByRef => Ok(()),
@@ -2425,7 +2425,7 @@ pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
     pub fn print_bounds(&mut self,
                         prefix: &str,
                         bounds: &[ast::TyParamBound])
-                        -> IoResult<()> {
+                        -> io::Result<()> {
         if !bounds.is_empty() {
             try!(word(&mut self.s, prefix));
             let mut first = true;
@@ -2458,14 +2458,14 @@ pub fn print_bounds(&mut self,
 
     pub fn print_lifetime(&mut self,
                           lifetime: &ast::Lifetime)
-                          -> IoResult<()>
+                          -> io::Result<()>
     {
         self.print_name(lifetime.name)
     }
 
     pub fn print_lifetime_def(&mut self,
                               lifetime: &ast::LifetimeDef)
-                              -> IoResult<()>
+                              -> io::Result<()>
     {
         try!(self.print_lifetime(&lifetime.lifetime));
         let mut sep = ":";
@@ -2479,7 +2479,7 @@ pub fn print_lifetime_def(&mut self,
 
     pub fn print_generics(&mut self,
                           generics: &ast::Generics)
-                          -> IoResult<()>
+                          -> io::Result<()>
     {
         let total = generics.lifetimes.len() + generics.ty_params.len();
         if total == 0 {
@@ -2508,7 +2508,7 @@ pub fn print_generics(&mut self,
         Ok(())
     }
 
-    pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
+    pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
         try!(self.print_ident(param.ident));
         try!(self.print_bounds(":", &param.bounds));
         match param.default {
@@ -2522,7 +2522,7 @@ pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
     }
 
     pub fn print_where_clause(&mut self, generics: &ast::Generics)
-                              -> IoResult<()> {
+                              -> io::Result<()> {
         if generics.where_clause.predicates.len() == 0 {
             return Ok(())
         }
@@ -2573,7 +2573,7 @@ pub fn print_where_clause(&mut self, generics: &ast::Generics)
         Ok(())
     }
 
-    pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
+    pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
         try!(self.ibox(indent_unit));
         match item.node {
             ast::MetaWord(ref name) => {
@@ -2596,7 +2596,7 @@ pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
         self.end()
     }
 
-    pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
+    pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
         match vp.node {
             ast::ViewPathSimple(ident, ref path) => {
                 try!(self.print_path(path, false, 0));
@@ -2640,19 +2640,19 @@ pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
     }
 
     pub fn print_mutability(&mut self,
-                            mutbl: ast::Mutability) -> IoResult<()> {
+                            mutbl: ast::Mutability) -> io::Result<()> {
         match mutbl {
             ast::MutMutable => self.word_nbsp("mut"),
             ast::MutImmutable => Ok(()),
         }
     }
 
-    pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
+    pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
         try!(self.print_mutability(mt.mutbl));
         self.print_type(&*mt.ty)
     }
 
-    pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
+    pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
         try!(self.ibox(indent_unit));
         match input.ty.node {
             ast::TyInfer => try!(self.print_pat(&*input.pat)),
@@ -2675,7 +2675,7 @@ pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
         self.end()
     }
 
-    pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
+    pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
         if let ast::DefaultReturn(..) = decl.output {
             return Ok(());
         }
@@ -2705,7 +2705,7 @@ pub fn print_ty_fn(&mut self,
                        id: Option<ast::Ident>,
                        generics: &ast::Generics,
                        opt_explicit_self: Option<&ast::ExplicitSelf_>)
-                       -> IoResult<()> {
+                       -> io::Result<()> {
         try!(self.ibox(indent_unit));
         try!(self.print_fn_header_info(Some(unsafety), abi, ast::Inherited));
 
@@ -2726,7 +2726,7 @@ pub fn print_ty_fn(&mut self,
 
     pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
                                         next_pos: Option<BytePos>)
-        -> IoResult<()> {
+        -> io::Result<()> {
         let cm = match self.cm {
             Some(cm) => cm,
             _ => return Ok(())
@@ -2749,7 +2749,7 @@ pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
         Ok(())
     }
 
-    pub fn print_remaining_comments(&mut self) -> IoResult<()> {
+    pub fn print_remaining_comments(&mut self) -> io::Result<()> {
         // If there aren't any remaining comments, then we need to manually
         // make sure there is a line break at the end.
         if self.next_comment().is_none() {
@@ -2767,7 +2767,7 @@ pub fn print_remaining_comments(&mut self) -> IoResult<()> {
         Ok(())
     }
 
-    pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
+    pub fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
         try!(self.maybe_print_comment(lit.span.lo));
         match self.next_lit(lit.span.lo) {
             Some(ref ltrl) => {
@@ -2848,7 +2848,7 @@ pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
         }
     }
 
-    pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
+    pub fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
         loop {
             match self.next_comment() {
                 Some(ref cmnt) => {
@@ -2864,7 +2864,7 @@ pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
     }
 
     pub fn print_comment(&mut self,
-                         cmnt: &comments::Comment) -> IoResult<()> {
+                         cmnt: &comments::Comment) -> io::Result<()> {
         match cmnt.style {
             comments::Mixed => {
                 assert_eq!(cmnt.lines.len(), 1);
@@ -2915,7 +2915,7 @@ pub fn print_comment(&mut self,
     }
 
     pub fn print_string(&mut self, st: &str,
-                        style: ast::StrStyle) -> IoResult<()> {
+                        style: ast::StrStyle) -> io::Result<()> {
         let st = match style {
             ast::CookedStr => {
                 (format!("\"{}\"", st.escape_default()))
@@ -2943,7 +2943,7 @@ pub fn next_comment(&mut self) -> Option<comments::Comment> {
     }
 
     pub fn print_opt_unsafety(&mut self,
-                            opt_unsafety: Option<ast::Unsafety>) -> IoResult<()> {
+                            opt_unsafety: Option<ast::Unsafety>) -> io::Result<()> {
         match opt_unsafety {
             Some(unsafety) => self.print_unsafety(unsafety),
             None => Ok(())
@@ -2952,7 +2952,7 @@ pub fn print_opt_unsafety(&mut self,
 
     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
                                                   opt_abi: Option<abi::Abi>)
-        -> IoResult<()> {
+        -> io::Result<()> {
         match opt_abi {
             Some(abi::Rust) => Ok(()),
             Some(abi) => {
@@ -2964,7 +2964,7 @@ pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
     }
 
     pub fn print_extern_opt_abi(&mut self,
-                                opt_abi: Option<abi::Abi>) -> IoResult<()> {
+                                opt_abi: Option<abi::Abi>) -> io::Result<()> {
         match opt_abi {
             Some(abi) => {
                 try!(self.word_nbsp("extern"));
@@ -2977,7 +2977,7 @@ pub fn print_extern_opt_abi(&mut self,
     pub fn print_fn_header_info(&mut self,
                                 opt_unsafety: Option<ast::Unsafety>,
                                 abi: abi::Abi,
-                                vis: ast::Visibility) -> IoResult<()> {
+                                vis: ast::Visibility) -> io::Result<()> {
         try!(word(&mut self.s, &visibility_qualified(vis, "")));
         try!(self.print_opt_unsafety(opt_unsafety));
 
@@ -2989,7 +2989,7 @@ pub fn print_fn_header_info(&mut self,
         word(&mut self.s, "fn")
     }
 
-    pub fn print_unsafety(&mut self, s: ast::Unsafety) -> IoResult<()> {
+    pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
         match s {
             ast::Unsafety::Normal => Ok(()),
             ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
index 756d67b5db1e1a37212ee04f4e0a133d80ba856a..ba9860ee31f604603a7ebba8d607317f68804dc6 100644 (file)
 
 #![feature(box_syntax)]
 #![feature(collections)]
+#![feature(fs)]
 #![feature(int_uint)]
+#![feature(io)]
 #![feature(old_io)]
-#![feature(old_path)]
+#![feature(path)]
 #![feature(rustc_private)]
 #![feature(staged_api)]
-#![feature(unicode)]
 #![feature(std_misc)]
-#![feature(os)]
+#![feature(unicode)]
 #![cfg_attr(windows, feature(libc))]
 
 #[macro_use] extern crate log;
index c147e6aa056dd2a916402ab636ee7dcfadd6e268..cc9a2880b5d07d10b5f8502315b1f9e9951f0798 100644 (file)
@@ -13,7 +13,8 @@
 //! ncurses-compatible compiled terminfo format parsing (term(5))
 
 use std::collections::HashMap;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
 use super::super::TermInfo;
 
 // These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
     "box1"];
 
 /// Parse a compiled terminfo entry, using long capability names if `longnames` is true
-pub fn parse(file: &mut old_io::Reader, longnames: bool)
+pub fn parse(file: &mut Read, longnames: bool)
              -> Result<Box<TermInfo>, String> {
     macro_rules! try { ($e:expr) => (
         match $e {
@@ -182,17 +183,17 @@ macro_rules! try { ($e:expr) => (
     }
 
     // Check magic number
-    let magic = try!(file.read_le_u16());
+    let magic = try!(read_le_u16(file));
     if magic != 0x011A {
         return Err(format!("invalid magic number: expected {:x}, found {:x}",
                            0x011A as usize, magic as usize));
     }
 
-    let names_bytes          = try!(file.read_le_i16()) as int;
-    let bools_bytes          = try!(file.read_le_i16()) as int;
-    let numbers_count        = try!(file.read_le_i16()) as int;
-    let string_offsets_count = try!(file.read_le_i16()) as int;
-    let string_table_bytes   = try!(file.read_le_i16()) as int;
+    let names_bytes          = try!(read_le_u16(file)) as int;
+    let bools_bytes          = try!(read_le_u16(file)) as int;
+    let numbers_count        = try!(read_le_u16(file)) as int;
+    let string_offsets_count = try!(read_le_u16(file)) as int;
+    let string_table_bytes   = try!(read_le_u16(file)) as int;
 
     assert!(names_bytes          > 0);
 
@@ -212,7 +213,7 @@ macro_rules! try { ($e:expr) => (
     }
 
     // don't read NUL
-    let bytes = try!(file.read_exact(names_bytes as uint - 1));
+    let bytes = try!(read_exact(file, names_bytes as uint - 1));
     let names_str = match String::from_utf8(bytes) {
         Ok(s)  => s,
         Err(_) => return Err("input not utf-8".to_string()),
@@ -222,12 +223,12 @@ macro_rules! try { ($e:expr) => (
                                            .map(|s| s.to_string())
                                            .collect();
 
-    try!(file.read_byte()); // consume NUL
+    try!(read_byte(file)); // consume NUL
 
     let mut bools_map = HashMap::new();
     if bools_bytes != 0 {
         for i in 0..bools_bytes {
-            let b = try!(file.read_byte());
+            let b = try!(read_byte(file));
             if b == 1 {
                 bools_map.insert(bnames[i as uint].to_string(), true);
             }
@@ -235,13 +236,13 @@ macro_rules! try { ($e:expr) => (
     }
 
     if (bools_bytes + names_bytes) % 2 == 1 {
-        try!(file.read_byte()); // compensate for padding
+        try!(read_byte(file)); // compensate for padding
     }
 
     let mut numbers_map = HashMap::new();
     if numbers_count != 0 {
         for i in 0..numbers_count {
-            let n = try!(file.read_le_u16());
+            let n = try!(read_le_u16(file));
             if n != 0xFFFF {
                 numbers_map.insert(nnames[i as uint].to_string(), n);
             }
@@ -253,10 +254,10 @@ macro_rules! try { ($e:expr) => (
     if string_offsets_count != 0 {
         let mut string_offsets = Vec::with_capacity(10);
         for _ in 0..string_offsets_count {
-            string_offsets.push(try!(file.read_le_u16()));
+            string_offsets.push(try!(read_le_u16(file)));
         }
 
-        let string_table = try!(file.read_exact(string_table_bytes as uint));
+        let string_table = try!(read_exact(file, string_table_bytes as usize));
 
         if string_table.len() != string_table_bytes as uint {
             return Err("error: hit EOF before end of string \
@@ -309,6 +310,25 @@ macro_rules! try { ($e:expr) => (
     })
 }
 
+fn read_le_u16<R: Read + ?Sized>(r: &mut R) -> io::Result<u16> {
+    let mut b = [0; 2];
+    assert_eq!(try!(r.read(&mut b)), 2);
+    Ok((b[0] as u16) | ((b[1] as u16) << 8))
+}
+
+fn read_byte<R: Read + ?Sized>(r: &mut R) -> io::Result<u8> {
+    let mut b = [0; 1];
+    assert_eq!(try!(r.read(&mut b)), 1);
+    Ok(b[0])
+}
+
+fn read_exact<R: Read + ?Sized>(r: &mut R, sz: usize) -> io::Result<Vec<u8>> {
+    let mut v = Vec::with_capacity(sz);
+    try!(r.take(sz as u64).read_to_end(&mut v));
+    assert_eq!(v.len(), sz);
+    Ok(v)
+}
+
 /// Create a dummy TermInfo struct for msys terminals
 pub fn msys_terminfo() -> Box<TermInfo> {
     let mut strings = HashMap::new();
index a0cd78420700187e78aa2ef451e5ff81f0bf2a3a..f47921cbf5e6acc3e921dd04ea36b1b373a33b2e 100644 (file)
 //!
 //! Does not support hashed database, only filesystem!
 
-use std::old_io::File;
-use std::old_io::fs::PathExtensions;
 use std::env;
+use std::fs::File;
+use std::io::prelude::*;
+use std::path::PathBuf;
 
 /// Return path to database entry for `term`
 #[allow(deprecated)]
-pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> {
+pub fn get_dbpath_for_term(term: &str) -> Option<Box<PathBuf>> {
     if term.len() == 0 {
         return None;
     }
 
-    let homedir = ::std::os::homedir();
+    let homedir = env::home_dir();
 
     let mut dirs_to_search = Vec::new();
     let first_char = term.char_at(0);
 
     // Find search directory
-    match env::var("TERMINFO") {
-        Ok(dir) => dirs_to_search.push(Path::new(dir)),
-        Err(..) => {
+    match env::var_os("TERMINFO") {
+        Some(dir) => dirs_to_search.push(PathBuf::new(&dir)),
+        None => {
             if homedir.is_some() {
                 // ncurses compatibility;
                 dirs_to_search.push(homedir.unwrap().join(".terminfo"))
@@ -39,9 +40,9 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> {
             match env::var("TERMINFO_DIRS") {
                 Ok(dirs) => for i in dirs.split(':') {
                     if i == "" {
-                        dirs_to_search.push(Path::new("/usr/share/terminfo"));
+                        dirs_to_search.push(PathBuf::new("/usr/share/terminfo"));
                     } else {
-                        dirs_to_search.push(Path::new(i));
+                        dirs_to_search.push(PathBuf::new(i));
                     }
                 },
                 // Found nothing in TERMINFO_DIRS, use the default paths:
@@ -49,9 +50,9 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> {
                 // ~/.terminfo, ncurses will search /etc/terminfo, then
                 // /lib/terminfo, and eventually /usr/share/terminfo.
                 Err(..) => {
-                    dirs_to_search.push(Path::new("/etc/terminfo"));
-                    dirs_to_search.push(Path::new("/lib/terminfo"));
-                    dirs_to_search.push(Path::new("/usr/share/terminfo"));
+                    dirs_to_search.push(PathBuf::new("/etc/terminfo"));
+                    dirs_to_search.push(PathBuf::new("/lib/terminfo"));
+                    dirs_to_search.push(PathBuf::new("/usr/share/terminfo"));
                 }
             }
         }
@@ -61,13 +62,13 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> {
     for p in &dirs_to_search {
         if p.exists() {
             let f = first_char.to_string();
-            let newp = p.join_many(&[&f[..], term]);
+            let newp = p.join(&f).join(term);
             if newp.exists() {
                 return Some(box newp);
             }
             // on some installations the dir is named after the hex of the char (e.g. OS X)
             let f = format!("{:x}", first_char as uint);
-            let newp = p.join_many(&[&f[..], term]);
+            let newp = p.join(&f).join(term);
             if newp.exists() {
                 return Some(box newp);
             }
@@ -96,17 +97,17 @@ pub fn open(term: &str) -> Result<File, String> {
 fn test_get_dbpath_for_term() {
     // woefully inadequate test coverage
     // note: current tests won't work with non-standard terminfo hierarchies (e.g. OS X's)
-    use std::os::{setenv, unsetenv};
+    use std::env;
     // FIXME (#9639): This needs to handle non-utf8 paths
     fn x(t: &str) -> String {
         let p = get_dbpath_for_term(t).expect("no terminfo entry found");
-        p.as_str().unwrap().to_string()
+        p.to_str().unwrap().to_string()
     };
     assert!(x("screen") == "/usr/share/terminfo/s/screen");
     assert!(get_dbpath_for_term("") == None);
-    setenv("TERMINFO_DIRS", ":");
+    env::set_var("TERMINFO_DIRS", ":");
     assert!(x("screen") == "/usr/share/terminfo/s/screen");
-    unsetenv("TERMINFO_DIRS");
+    env::remove_var("TERMINFO_DIRS");
 }
 
 #[test]
index a144904903e58e8f7ca2d7dfcdd3da4e3926288e..e309e7a6c221d2665994421b15cb2cdd066f65dd 100644 (file)
 #![feature(core)]
 #![feature(int_uint)]
 #![feature(old_io)]
-#![feature(old_path)]
+#![feature(path)]
+#![feature(fs)]
 #![feature(rustc_private)]
 #![feature(staged_api)]
 #![feature(std_misc)]
+#![feature(io)]
 
 extern crate getopts;
 extern crate serialize;
 use std::any::Any;
 use std::cmp;
 use std::collections::BTreeMap;
+use std::env;
 use std::fmt;
-use std::old_io::stdio::StdWriter;
-use std::old_io::{File, ChanReader, ChanWriter};
-use std::old_io;
+use std::fs::File;
+use std::io::{self, Write};
 use std::iter::repeat;
 use std::num::{Float, Int};
-use std::env;
+use std::old_io::stdio::StdWriter;
+use std::old_io::{ChanReader, ChanWriter};
+use std::old_io;
+use std::path::{PathBuf};
 use std::sync::mpsc::{channel, Sender};
 use std::thread;
 use std::thunk::{Thunk, Invoke};
@@ -287,7 +292,7 @@ pub struct TestOpts {
     pub run_ignored: bool,
     pub run_tests: bool,
     pub run_benchmarks: bool,
-    pub logfile: Option<Path>,
+    pub logfile: Option<PathBuf>,
     pub nocapture: bool,
     pub color: ColorConfig,
 }
@@ -376,7 +381,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> {
     let run_ignored = matches.opt_present("ignored");
 
     let logfile = matches.opt_str("logfile");
-    let logfile = logfile.map(|s| Path::new(s));
+    let logfile = logfile.map(|s| PathBuf::new(&s));
 
     let run_benchmarks = matches.opt_present("bench");
     let run_tests = ! run_benchmarks ||
@@ -446,11 +451,19 @@ struct ConsoleTestState<T> {
     max_name_len: uint, // number of columns to fill when aligning names
 }
 
+fn new2old(new: io::Error) -> old_io::IoError {
+    old_io::IoError {
+        kind: old_io::OtherIoError,
+        desc: "other error",
+        detail: Some(new.to_string()),
+    }
+}
+
 impl<T: Writer> ConsoleTestState<T> {
     pub fn new(opts: &TestOpts,
                _: Option<T>) -> old_io::IoResult<ConsoleTestState<StdWriter>> {
         let log_out = match opts.logfile {
-            Some(ref path) => Some(try!(File::create(path))),
+            Some(ref path) => Some(try!(File::create(path).map_err(new2old))),
             None => None
         };
         let out = match term::stdout() {
@@ -560,7 +573,7 @@ pub fn write_result(&mut self, result: &TestResult) -> old_io::IoResult<()> {
     }
 
     pub fn write_log(&mut self, test: &TestDesc,
-                     result: &TestResult) -> old_io::IoResult<()> {
+                     result: &TestResult) -> io::Result<()> {
         match self.log_out {
             None => Ok(()),
             Some(ref mut o) => {
@@ -646,7 +659,7 @@ fn callback<T: Writer>(event: &TestEvent,
             TeFiltered(ref filtered_tests) => st.write_run_start(filtered_tests.len()),
             TeWait(ref test, padding) => st.write_test_start(test, padding),
             TeResult(test, result, stdout) => {
-                try!(st.write_log(&test, &result));
+                try!(st.write_log(&test, &result).map_err(new2old));
                 try!(st.write_result(&result));
                 match result {
                     TrOk => st.passed += 1,
@@ -732,8 +745,8 @@ fn should_sort_failures_before_printing_them() {
         Pretty(_) => unreachable!()
     };
 
-    let apos = s.find_str("a").unwrap();
-    let bpos = s.find_str("b").unwrap();
+    let apos = s.find("a").unwrap();
+    let bpos = s.find("b").unwrap();
     assert!(apos < bpos);
 }
 
index 8900b60d1913a2eb533702a630fda0cb4f0b9063..ac7f2f824cbbf9ab9c5d3dcab3fb911ad7ea8df0 100644 (file)
 
 //! Basic data structures for representing a book.
 
-use std::old_io::BufferedReader;
+use std::io::prelude::*;
+use std::io::BufReader;
 use std::iter;
 use std::iter::AdditiveIterator;
+use std::path::{Path, PathBuf};
 
 pub struct BookItem {
     pub title: String,
-    pub path: Path,
-    pub path_to_root: Path,
+    pub path: PathBuf,
+    pub path_to_root: PathBuf,
     pub children: Vec<BookItem>,
 }
 
@@ -76,7 +78,7 @@ pub fn iter(&self) -> BookItems {
 }
 
 /// Construct a book by parsing a summary (markdown table of contents).
-pub fn parse_summary<R: Reader>(input: R, src: &Path) -> Result<Book, Vec<String>> {
+pub fn parse_summary(input: &mut Read, src: &Path) -> Result<Book, Vec<String>> {
     fn collapse(stack: &mut Vec<BookItem>,
                 top_items: &mut Vec<BookItem>,
                 to_level: usize) {
@@ -100,16 +102,16 @@ fn collapse(stack: &mut Vec<BookItem>,
     // always include the introduction
     top_items.push(BookItem {
         title: "Introduction".to_string(),
-        path: Path::new("README.md"),
-        path_to_root: Path::new("."),
+        path: PathBuf::new("README.md"),
+        path_to_root: PathBuf::new("."),
         children: vec!(),
     });
 
-    for line_result in BufferedReader::new(input).lines() {
+    for line_result in BufReader::new(input).lines() {
         let line = match line_result {
             Ok(line) => line,
             Err(err) => {
-                errors.push(err.desc.to_string()); // FIXME: include detail
+                errors.push(err.to_string());
                 return Err(errors);
             }
         };
@@ -125,16 +127,16 @@ fn collapse(stack: &mut Vec<BookItem>,
         let title = line[start_bracket + 1..end_bracket].to_string();
         let indent = &line[..star_idx];
 
-        let path_from_root = match src.join(given_path).path_relative_from(src) {
-            Some(p) => p,
+        let path_from_root = match src.join(given_path).relative_from(src) {
+            Some(p) => p.to_path_buf(),
             None => {
                 errors.push(format!("paths in SUMMARY.md must be relative, \
                                      but path '{}' for section '{}' is not.",
                                      given_path, title));
-                Path::new("")
+                PathBuf::new("")
             }
         };
-        let path_to_root = Path::new(iter::repeat("../")
+        let path_to_root = PathBuf::new(&iter::repeat("../")
                                          .take(path_from_root.components().count() - 1)
                                          .collect::<String>());
         let item = BookItem {
index f36d97d6d120d50ef2f42aaa2f47f3de788e49c7..1fb30e15400efb7c8fa71965cd92cce3cfad98c7 100644 (file)
 //! Implementation of the `build` subcommand, used to compile a book.
 
 use std::env;
-use std::os;
-use std::old_io;
-use std::old_io::{fs, File, BufferedWriter, TempDir, IoResult};
+use std::fs::{self, File, TempDir};
+use std::io::prelude::*;
+use std::io::{self, BufWriter};
+use std::path::{Path, PathBuf};
 
 use subcommand::Subcommand;
 use term::Term;
-use error::{Error, CliResult, CommandResult};
+use error::{err, CliResult, CommandResult};
 use book;
 use book::{Book, BookItem};
 use css;
 
 pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> {
     if name == "build" {
-        Some(box Build as Box<Subcommand>)
+        Some(Box::new(Build))
     } else {
         None
     }
 }
 
-fn write_toc(book: &Book, path_to_root: &Path, out: &mut Writer) -> IoResult<()> {
+fn write_toc(book: &Book, path_to_root: &Path, out: &mut Write) -> io::Result<()> {
     fn walk_items(items: &[BookItem],
                   section: &str,
                   path_to_root: &Path,
-                  out: &mut Writer) -> IoResult<()> {
+                  out: &mut Write) -> io::Result<()> {
         for (i, item) in items.iter().enumerate() {
             try!(walk_item(item, &format!("{}{}.", section, i + 1)[..], path_to_root, out));
         }
@@ -48,9 +49,9 @@ fn walk_items(items: &[BookItem],
     fn walk_item(item: &BookItem,
                  section: &str,
                  path_to_root: &Path,
-                 out: &mut Writer) -> IoResult<()> {
+                 out: &mut Write) -> io::Result<()> {
         try!(writeln!(out, "<li><a href='{}'><b>{}</b> {}</a>",
-                 path_to_root.join(item.path.with_extension("html")).display(),
+                 path_to_root.join(&item.path.with_extension("html")).display(),
                  section,
                  item.title));
         if !item.children.is_empty() {
@@ -75,30 +76,35 @@ fn walk_item(item: &BookItem,
 fn render(book: &Book, tgt: &Path) -> CliResult<()> {
     let tmp = try!(TempDir::new("rust-book"));
 
-    for (section, item) in book.iter() {
-        println!("{} {}", section, item.title);
-
-        let out_path = tgt.join(item.path.dirname());
+    for (_section, item) in book.iter() {
+        let out_path = match item.path.parent() {
+            Some(p) => tgt.join(p),
+            None => tgt.to_path_buf(),
+        };
 
         let src;
         if env::args().len() < 3 {
-            src = os::getcwd().unwrap().clone();
+            src = env::current_dir().unwrap().clone();
         } else {
-            src = Path::new(env::args().nth(2).unwrap().clone());
+            src = PathBuf::new(&env::args().nth(2).unwrap());
         }
         // preprocess the markdown, rerouting markdown references to html references
-        let markdown_data = try!(File::open(&src.join(&item.path)).read_to_string());
-        let preprocessed_path = tmp.path().join(item.path.filename().unwrap());
+        let mut markdown_data = String::new();
+        try!(File::open(&src.join(&item.path)).and_then(|mut f| {
+            f.read_to_string(&mut markdown_data)
+        }));
+        let preprocessed_path = tmp.path().join(item.path.file_name().unwrap());
         {
             let urls = markdown_data.replace(".md)", ".html)");
-            try!(File::create(&preprocessed_path)
-                      .write_str(&urls[..]));
+            try!(File::create(&preprocessed_path).and_then(|mut f| {
+                f.write_all(urls.as_bytes())
+            }));
         }
 
         // write the prelude to a temporary HTML file for rustdoc inclusion
         let prelude = tmp.path().join("prelude.html");
         {
-            let mut toc = BufferedWriter::new(try!(File::create(&prelude)));
+            let mut toc = BufWriter::new(try!(File::create(&prelude)));
             try!(writeln!(&mut toc, r#"<div id="nav">
                 <button id="toggle-nav">
                   <span class="sr-only">Toggle navigation</span>
@@ -115,12 +121,12 @@ fn render(book: &Book, tgt: &Path) -> CliResult<()> {
         // write the postlude to a temporary HTML file for rustdoc inclusion
         let postlude = tmp.path().join("postlude.html");
         {
-            let mut toc = BufferedWriter::new(try!(File::create(&postlude)));
-            try!(toc.write_str(javascript::JAVASCRIPT));
+            let mut toc = BufWriter::new(try!(File::create(&postlude)));
+            try!(toc.write_all(javascript::JAVASCRIPT.as_bytes()));
             try!(writeln!(&mut toc, "</div></div>"));
         }
 
-        try!(fs::mkdir_recursive(&out_path, old_io::USER_DIR));
+        try!(fs::create_dir_all(&out_path));
 
         let rustdoc_args: &[String] = &[
             "".to_string(),
@@ -135,7 +141,7 @@ fn render(book: &Book, tgt: &Path) -> CliResult<()> {
         if output_result != 0 {
             let message = format!("Could not execute `rustdoc` with {:?}: {}",
                                   rustdoc_args, output_result);
-            return Err(box message as Box<Error>);
+            return Err(err(&message));
         }
     }
 
@@ -150,28 +156,30 @@ fn parse_args(&mut self, _: &[String]) -> CliResult<()> {
     }
     fn usage(&self) {}
     fn execute(&mut self, term: &mut Term) -> CommandResult<()> {
-        let cwd = os::getcwd().unwrap();
+        let cwd = env::current_dir().unwrap();
         let src;
         let tgt;
 
         if env::args().len() < 3 {
             src = cwd.clone();
         } else {
-            src = Path::new(env::args().nth(2).unwrap().clone());
+            src = PathBuf::new(&env::args().nth(2).unwrap());
         }
 
         if env::args().len() < 4 {
             tgt = cwd.join("_book");
         } else {
-            tgt = Path::new(env::args().nth(3).unwrap().clone());
+            tgt = PathBuf::new(&env::args().nth(3).unwrap());
         }
 
-        try!(fs::mkdir(&tgt, old_io::USER_DIR));
+        try!(fs::create_dir(&tgt));
 
-        try!(File::create(&tgt.join("rust-book.css")).write_str(css::STYLE));
+        try!(File::create(&tgt.join("rust-book.css")).and_then(|mut f| {
+            f.write_all(css::STYLE.as_bytes())
+        }));
 
-        let summary = try!(File::open(&src.join("SUMMARY.md")));
-        match book::parse_summary(summary, &src) {
+        let mut summary = try!(File::open(&src.join("SUMMARY.md")));
+        match book::parse_summary(&mut summary, &src) {
             Ok(book) => {
                 // execute rustdoc on the whole book
                 render(&book, &tgt)
@@ -182,7 +190,7 @@ fn execute(&mut self, term: &mut Term) -> CommandResult<()> {
                     term.err(&format!("error: {}", err)[..]);
                 }
 
-                Err(box format!("{} errors occurred", n) as Box<Error>)
+                Err(err(&format!("{} errors occurred", n)))
             }
         }
     }
index 43c882c7d5b8a69c1c660049f7abf6f969fe8764..294b4e556694ad2be1c935ab5749226a392877bf 100644 (file)
 
 //! Error handling utilities. WIP.
 
+use std::error::Error;
 use std::fmt;
-use std::fmt::{Debug, Formatter};
-
-use std::old_io::IoError;
 
 pub type CliError = Box<Error + 'static>;
 pub type CliResult<T> = Result<T, CliError>;
 pub type CommandError = Box<Error + 'static>;
 pub type CommandResult<T> = Result<T, CommandError>;
 
-pub trait Error {
-    fn description(&self) -> &str;
-
-    fn detail(&self) -> Option<&str> { None }
-    fn cause(&self) -> Option<&Error> { None }
-}
-
-pub trait FromError<E> {
-    fn from_err(err: E) -> Self;
-}
-
-impl Debug for Box<Error + 'static> {
-    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
-        write!(f, "{}", self.description())
-    }
-}
-
-impl<E: Error + 'static> FromError<E> for Box<Error + 'static> {
-    fn from_err(err: E) -> Box<Error + 'static> {
-        box err as Box<Error>
-    }
-}
+pub fn err(s: &str) -> CliError {
+    struct E(String);
 
-impl<'a> Error for &'a str {
-    fn description<'b>(&'b self) -> &'b str {
-        *self
+    impl Error for E {
+        fn description(&self) -> &str { &self.0 }
     }
-}
-
-impl Error for String {
-    fn description<'a>(&'a self) -> &'a str {
-        &self[..]
+    impl fmt::Display for E {
+        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+            self.0.fmt(f)
+        }
     }
-}
-
-impl<'a> Error for Box<Error + 'a> {
-    fn description(&self) -> &str { (**self).description() }
-    fn detail(&self) -> Option<&str> { (**self).detail() }
-    fn cause(&self) -> Option<&Error> { (**self).cause() }
-}
-
-impl FromError<()> for () {
-    fn from_err(_: ()) -> () { () }
-}
 
-impl FromError<IoError> for IoError {
-    fn from_err(error: IoError) -> IoError { error }
+    Box::new(E(s.to_string()))
 }
-
-impl Error for IoError {
-    fn description(&self) -> &str {
-        self.desc
-    }
-    fn detail(&self) -> Option<&str> {
-        self.detail.as_ref().map(|s| &s[..])
-    }
-}
-
-
-//fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I,
index 7fd8214f7311af078614aaf7ebcb4eebaa8f3569..995d2f2494a490b1845344aaa86886152a733bd9 100644 (file)
@@ -19,7 +19,7 @@
 
 pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> {
     match name {
-        "help" | "--help" | "-h" | "-?" => Some(box Help as Box<Subcommand>),
+        "help" | "--help" | "-h" | "-?" => Some(Box::new(Help)),
         _ => None
     }
 }
index b9fc011e8b9a584edf198247e2eb1d0de9f67399..848f960839e6e0c4cd56fb5ec4823e9c1112cc7a 100644 (file)
@@ -8,31 +8,24 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-#![feature(collections)]
+#![deny(warnings)]
+
 #![feature(core)]
+#![feature(exit_status)]
+#![feature(fs)]
+#![feature(io)]
 #![feature(old_io)]
-#![feature(env)]
-#![feature(os)]
-#![feature(old_path)]
+#![feature(path)]
 #![feature(rustdoc)]
+#![feature(tempdir)]
 
 extern crate rustdoc;
 
 use std::env;
+use std::error::Error;
 use subcommand::Subcommand;
 use term::Term;
 
-macro_rules! try (
-    ($expr:expr) => ({
-        use error;
-        match $expr {
-            Ok(val) => val,
-            Err(err) => return Err(error::FromError::from_err(err))
-        }
-    })
-);
-
 mod term;
 mod error;
 mod book;
@@ -56,15 +49,12 @@ fn main() {
     } else {
         match subcommand::parse_name(&cmd[1][..]) {
             Some(mut subcmd) => {
-                match subcmd.parse_args(cmd.tail()) {
+                match subcmd.parse_args(&cmd[..cmd.len()-1]) {
                     Ok(_) => {
                         match subcmd.execute(&mut term) {
                             Ok(_) => (),
                             Err(err) => {
-                                term.err(&format!("error: {}", err.description())[..]);
-                                err.detail().map(|detail| {
-                                    term.err(&format!("detail: {}", detail)[..]);
-                                });
+                                term.err(&format!("error: {}", err));
                             }
                         }
                     }
index 808527dcef95eeeaa2b2b96f3dbfe37abc24e4aa..2fa7b7eed7b05d77a8bd6f58ea0b29c7a4f7bc48 100644 (file)
@@ -19,7 +19,7 @@
 
 pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> {
     if name == "serve" {
-        Some(box Serve as Box<Subcommand>)
+        Some(Box::new(Serve))
     } else {
         None
     }
index 98aa3fca184dca3f4c05e04fc9d09ba91641892d..06595cb0455a31d1bb4cecc50bbd546688bcb952 100644 (file)
@@ -21,7 +21,7 @@ pub struct Term {
 impl Term {
     pub fn new() -> Term {
         Term {
-            err: box stdio::stderr() as Box<Writer>,
+            err: Box::new(stdio::stderr())
         }
     }
 
index 727a385a8f02811e19eb7a43d87b6500cd369e63..72df0768e7b9b5c70972123ec3c2425db87bbafe 100644 (file)
 //! Implementation of the `test` subcommand. Just a stub for now.
 
 use subcommand::Subcommand;
-use error::CliResult;
-use error::CommandResult;
-use error::Error;
+use error::{err, CliResult, CommandResult};
 use term::Term;
 use book;
-use std::old_io::{Command, File};
-use std::os;
+
+use std::fs::File;
+use std::env;
+use std::process::Command;
 
 struct Test;
 
 pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> {
     if name == "test" {
-        Some(box Test as Box<Subcommand>)
+        Some(Box::new(Test))
     } else {
         None
     }
@@ -35,11 +35,11 @@ fn parse_args(&mut self, _: &[String]) -> CliResult<()> {
     }
     fn usage(&self) {}
     fn execute(&mut self, term: &mut Term) -> CommandResult<()> {
-        let cwd = os::getcwd().unwrap();
+        let cwd = env::current_dir().unwrap();
         let src = cwd.clone();
 
-        let summary = File::open(&src.join("SUMMARY.md"));
-        match book::parse_summary(summary, &src) {
+        let mut summary = try!(File::open(&src.join("SUMMARY.md")));
+        match book::parse_summary(&mut summary, &src) {
             Ok(book) => {
                 for (_, item) in book.iter() {
                     let output_result = Command::new("rustdoc")
@@ -50,15 +50,15 @@ fn execute(&mut self, term: &mut Term) -> CommandResult<()> {
                         Ok(output) => {
                             if !output.status.success() {
                                 term.err(&format!("{}\n{}",
-                                         String::from_utf8_lossy(&output.output[..]),
-                                         String::from_utf8_lossy(&output.error[..]))[..]);
-                                return Err(box "Some tests failed." as Box<Error>);
+                                         String::from_utf8_lossy(&output.stdout),
+                                         String::from_utf8_lossy(&output.stderr)));
+                                return Err(err("some tests failed"));
                             }
 
                         }
                         Err(e) => {
-                            let message = format!("Could not execute `rustdoc`: {}", e);
-                            return Err(box message as Box<Error>);
+                            let message = format!("could not execute `rustdoc`: {}", e);
+                            return Err(err(&message))
                         }
                     }
                 }
@@ -67,7 +67,7 @@ fn execute(&mut self, term: &mut Term) -> CommandResult<()> {
                 for err in errors {
                     term.err(&err[..]);
                 }
-                return Err(box "There was an error." as Box<Error>);
+                return Err(err("there was an error"))
             }
         }
         Ok(()) // lol
diff --git a/src/test/auxiliary/cross_crate_spans.rs b/src/test/auxiliary/cross_crate_spans.rs
new file mode 100644 (file)
index 0000000..22c2068
--- /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.
+
+#![crate_type = "rlib"]
+#![omit_gdb_pretty_printer_section]
+
+// no-prefer-dynamic
+// compile-flags:-g
+
+pub fn generic_function<T: Clone>(val: T) -> (T, T) {
+    let result = (val.clone(), val.clone());
+    let a_variable: u32 = 123456789;
+    let another_variable: f64 = 123456789.5;
+    zzz();
+    result
+}
+
+#[inline(never)]
+fn zzz() {()}
\ No newline at end of file
index 01bfbd3dbceb6f65e52de3217a9773bac356455f..d9afc1df28ebf79348ec3bb8255a3d803ba78519 100644 (file)
@@ -36,10 +36,12 @@ pub fn plugin_registrar(reg: &mut Registry) {
     reg.register_macro("identity", expand_identity);
     reg.register_syntax_extension(
         token::intern("into_foo"),
-        Modifier(box expand_into_foo));
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        Modifier(Box::new(expand_into_foo)));
     reg.register_syntax_extension(
         token::intern("into_multi_foo"),
-        MultiModifier(box expand_into_foo_multi));
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        MultiModifier(Box::new(expand_into_foo_multi)));
 }
 
 fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
index 1775bbf4af21f635ce32c5d6434d9daae132ded1..20c84c4ba5b4a9863d9623e558bb940d9cc7bb98 100644 (file)
@@ -46,5 +46,6 @@ fn expand<'cx>(&self,
 pub fn plugin_registrar(reg: &mut Registry) {
     let args = reg.args().clone();
     reg.register_syntax_extension(token::intern("plugin_args"),
-        NormalTT(box Expander { args: args, }, None));
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        NormalTT(Box::new(Expander { args: args, }), None));
 }
diff --git a/src/test/auxiliary/procedural_mbe_matching.rs b/src/test/auxiliary/procedural_mbe_matching.rs
new file mode 100644 (file)
index 0000000..d9a2b06
--- /dev/null
@@ -0,0 +1,69 @@
+// 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.
+
+// force-host
+
+#![crate_type="dylib"]
+#![feature(plugin_registrar, quote)]
+
+extern crate syntax;
+extern crate rustc;
+
+use syntax::codemap::Span;
+use syntax::parse::token::{self, str_to_ident, NtExpr, NtPat};
+use syntax::ast::{TokenTree, TtToken, Pat};
+use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager};
+use syntax::ext::build::AstBuilder;
+use syntax::ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
+use syntax::ext::tt::macro_parser::{Success, Failure, Error};
+use syntax::ptr::P;
+use rustc::plugin::Registry;
+
+fn expand_mbe_matches(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
+        -> Box<MacResult + 'static> {
+
+    let mbe_matcher = quote_matcher!(cx, $matched:expr, $($pat:pat)|+);
+
+    let mac_expr = match TokenTree::parse(cx, &mbe_matcher[..], args) {
+        Success(map) => {
+            match (&*map[str_to_ident("matched")], &*map[str_to_ident("pat")]) {
+                (&MatchedNonterminal(NtExpr(ref matched_expr)),
+                 &MatchedSeq(ref pats, seq_sp)) => {
+                    let pats: Vec<P<Pat>> = pats.iter().map(|pat_nt|
+                        if let &MatchedNonterminal(NtPat(ref pat)) = &**pat_nt {
+                            pat.clone()
+                        } else {
+                            unreachable!()
+                        }
+                    ).collect();
+                    let arm = cx.arm(seq_sp, pats, cx.expr_bool(seq_sp, true));
+
+                    quote_expr!(cx,
+                        match $matched_expr {
+                            $arm
+                            _ => false
+                        }
+                    )
+                }
+                _ => unreachable!()
+            }
+        }
+        Failure(_, s) | Error(_, s) => {
+            panic!("expected Success, but got Error/Failure: {}", s);
+        }
+    };
+
+    MacEager::expr(mac_expr)
+}
+
+#[plugin_registrar]
+pub fn plugin_registrar(reg: &mut Registry) {
+    reg.register_macro("matches", expand_mbe_matches);
+}
index f239a0d78d1ddd9875bb6c873d5f5f07e0aeb6b4..5cfe62d967c580b9face83b4cb4c074fe79fd429 100644 (file)
@@ -146,7 +146,7 @@ fn new() -> Table {
     fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
         match item.next {
             None => {
-                let mut entry = box Entry {
+                let mut entry: Box<_> = box Entry {
                     code: key,
                     count: 0,
                     next: None,
@@ -170,7 +170,7 @@ fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
 
         {
             if self.items[index as usize].is_none() {
-                let mut entry = box Entry {
+                let mut entry: Box<_> = box Entry {
                     code: key,
                     count: 0,
                     next: None,
index 40e1e7d2b76b02614a211db532013b8a9a0b1452..f308743ad136d276fbf2c472bbc5690ad0a2ac69 100644 (file)
@@ -124,7 +124,7 @@ pub fn solve(&mut self) {
     fn next_color(&mut self, row: u8, col: u8, start_color: u8) -> bool {
         if start_color < 10u8 {
             // colors not yet used
-            let mut avail = box Colors::new(start_color);
+            let mut avail: Box<_> = box Colors::new(start_color);
 
             // drop colors already in use in neighbourhood
             self.drop_colors(&mut *avail, row, col);
index 40e077bd1b55d5fa17df67aa2937f8e97211765a..b1abbad525356a5ff43f6a894b765ff3d5a20290 100644 (file)
@@ -16,7 +16,7 @@
 struct Bar(isize, isize);
 
 fn main() {
-    let x = (box 1, 2);
+    let x: (Box<_>, _) = (box 1, 2);
     let r = &x.0;
     let y = x; //~ ERROR cannot move out of `x` because it is borrowed
 
index 4d1939be5b9f7350eeeb6772b458d21badf7227d..7913f9ac90300c80f9a54abf4e6dc5a62432fe79 100644 (file)
@@ -23,7 +23,7 @@ fn add(v: &usize, w: usize) -> usize {
 }
 
 fn implicit() {
-    let mut a = box 1;
+    let mut a: Box<_> = box 1;
 
     // Note the danger here:
     //
@@ -36,7 +36,7 @@ fn implicit() {
 }
 
 fn explicit() {
-    let mut a = box 1;
+    let mut a: Box<_> = box 1;
     add(
         &*a,
         rewrite(&mut a)); //~ ERROR cannot borrow
index 9eda3689334c19f4176be63c228ea93157ac9e62..e24d4e87add83613a27f3d3acc7480cd79c84fd7 100644 (file)
@@ -23,7 +23,7 @@ fn add(v: &usize, w: Box<usize>) -> usize {
 }
 
 fn implicit() {
-    let mut a = box 1;
+    let mut a: Box<_> = box 1;
 
     // Note the danger here:
     //
@@ -36,7 +36,7 @@ fn implicit() {
 }
 
 fn explicit() {
-    let mut a = box 1;
+    let mut a: Box<_> = box 1;
     add(
         &*a,
         a); //~ ERROR cannot move
index 794e0fc6e3aba95ab10168acd24d51a96b0d0ffd..3662e23a4122f71da9c7e74be2b7aa23773cb9b6 100644 (file)
@@ -18,7 +18,7 @@ fn foo(&mut self) {
 }
 
 pub fn main() {
-    let a = box A;
+    let a: Box<_> = box A;
     a.foo();
     //~^ ERROR cannot borrow immutable `Box` content `*a` as mutable
 }
index 9c10f01e027557c7e9885d43574a62044cc5f27a..8bbecfd48c6dca78c5b74dd6762f232319edb426 100644 (file)
 use std::collections::HashMap;
 
 fn main() {
-    let tmp;
+    let tmp: Box<_>;
     let mut buggy_map: HashMap<usize, &usize> = HashMap::new();
-    buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    buggy_map.insert(42, &*Box::new(1)); //~ ERROR borrowed value does not live long enough
 
     // but it is ok if we use a temporary
     tmp = box 2;
index 648d0d81ffbc0ef28fd99d0da26338f68e6cb177..59514f75a77d8b07bb39f68791677173a108fbd4 100644 (file)
@@ -31,100 +31,100 @@ struct D {
 }
 
 fn copy_after_move() {
-    let a = box A { x: box 0, y: 1 };
+    let a: Box<_> = box A { x: box 0, y: 1 };
     let _x = a.x;
     let _y = a.y; //~ ERROR use of moved
     //~^^ NOTE `a` moved here (through moving `a.x`)
 }
 
 fn move_after_move() {
-    let a = box B { x: box 0, y: box 1 };
+    let a: Box<_> = box B { x: box 0, y: box 1 };
     let _x = a.x;
     let _y = a.y; //~ ERROR use of moved
     //~^^ NOTE `a` moved here (through moving `a.x`)
 }
 
 fn borrow_after_move() {
-    let a = box A { x: box 0, y: 1 };
+    let a: Box<_> = box A { x: box 0, y: 1 };
     let _x = a.x;
     let _y = &a.y; //~ ERROR use of moved
     //~^^ NOTE `a` moved here (through moving `a.x`)
 }
 
 fn move_after_borrow() {
-    let a = box B { x: box 0, y: box 1 };
+    let a: Box<_> = box B { x: box 0, y: box 1 };
     let _x = &a.x;
     let _y = a.y; //~ ERROR cannot move
 }
 
 fn copy_after_mut_borrow() {
-    let mut a = box A { x: box 0, y: 1 };
+    let mut a: Box<_> = box A { x: box 0, y: 1 };
     let _x = &mut a.x;
     let _y = a.y; //~ ERROR cannot use
 }
 
 fn move_after_mut_borrow() {
-    let mut a = box B { x: box 0, y: box 1 };
+    let mut a: Box<_> = box B { x: box 0, y: box 1 };
     let _x = &mut a.x;
     let _y = a.y; //~ ERROR cannot move
 }
 
 fn borrow_after_mut_borrow() {
-    let mut a = box A { x: box 0, y: 1 };
+    let mut a: Box<_> = box A { x: box 0, y: 1 };
     let _x = &mut a.x;
     let _y = &a.y; //~ ERROR cannot borrow
 }
 
 fn mut_borrow_after_borrow() {
-    let mut a = box A { x: box 0, y: 1 };
+    let mut a: Box<_> = box A { x: box 0, y: 1 };
     let _x = &a.x;
     let _y = &mut a.y; //~ ERROR cannot borrow
 }
 
 fn copy_after_move_nested() {
-    let a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+    let a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
     let _x = a.x.x;
     let _y = a.y; //~ ERROR use of collaterally moved
 }
 
 fn move_after_move_nested() {
-    let a = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
+    let a: Box<_> = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
     let _x = a.x.x;
     let _y = a.y; //~ ERROR use of collaterally moved
 }
 
 fn borrow_after_move_nested() {
-    let a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+    let a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
     let _x = a.x.x;
     let _y = &a.y; //~ ERROR use of collaterally moved
 }
 
 fn move_after_borrow_nested() {
-    let a = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
+    let a: Box<_> = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
     let _x = &a.x.x;
     let _y = a.y; //~ ERROR cannot move
 }
 
 fn copy_after_mut_borrow_nested() {
-    let mut a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+    let mut a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
     let _x = &mut a.x.x;
     let _y = a.y; //~ ERROR cannot use
 }
 
 fn move_after_mut_borrow_nested() {
-    let mut a = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
+    let mut a: Box<_> = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
     let _x = &mut a.x.x;
     let _y = a.y; //~ ERROR cannot move
 }
 
 fn borrow_after_mut_borrow_nested() {
-    let mut a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+    let mut a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
     let _x = &mut a.x.x;
     let _y = &a.y; //~ ERROR cannot borrow
 }
 
 fn mut_borrow_after_borrow_nested() {
-    let mut a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+    let mut a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
     let _x = &a.x.x;
     let _y = &mut a.y; //~ ERROR cannot borrow
 }
index 9ea5fbbdb1af08e72e83750025961b6652fbfe72..7626f354eb46415a13575402bf74991f11b65bc5 100644 (file)
@@ -11,7 +11,6 @@
 // Ensure that invoking a closure counts as a unique immutable borrow
 
 #![feature(unboxed_closures)]
-#![feature(box_syntax)]
 
 type Fn<'a> = Box<FnMut() + 'a>;
 
@@ -19,11 +18,12 @@ struct Test<'a> {
     f: Box<FnMut() + 'a>
 }
 
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
 fn call<F>(mut f: F) where F: FnMut(Fn) {
-    f(box || {
+    f(Box::new(|| {
     //~^ ERROR: cannot borrow `f` as mutable more than once
-        f(box || {})
-    });
+        f((Box::new(|| {})))
+    }));
 }
 
 fn test1() {
@@ -58,11 +58,12 @@ fn test6() {
 fn test7() {
     fn foo<F>(_: F) where F: FnMut(Box<FnMut(isize)>, isize) {}
     let mut f = |g: Box<FnMut(isize)>, b: isize| {};
-    f(box |a| {
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    f(Box::new(|a| {
         foo(f);
         //~^ ERROR cannot move `f` into closure because it is borrowed
         //~| ERROR cannot move out of captured outer variable in an `FnMut` closure
-    }, 3);
+    }), 3);
 }
 
 fn main() {}
index 851b11fac2b9d1949f9eb09f3e5a15a82c5afe33..aaa0766121543fc5c4b0f2a000fb424b2d2ff106 100644 (file)
@@ -52,7 +52,7 @@ fn e() {
 }
 
 fn f() {
-    let mut x = box 3;
+    let mut x: Box<_> = box 3;
     let c1 = || get(&*x);
     *x = 5; //~ ERROR cannot assign
 }
@@ -62,7 +62,7 @@ struct Foo {
         f: Box<isize>
     }
 
-    let mut x = box Foo { f: box 3 };
+    let mut x: Box<_> = box Foo { f: box 3 };
     let c1 = || get(&*x.f);
     *x.f = 5; //~ ERROR cannot assign to `*x.f`
 }
@@ -72,7 +72,7 @@ struct Foo {
         f: Box<isize>
     }
 
-    let mut x = box Foo { f: box 3 };
+    let mut x: Box<_> = box Foo { f: box 3 };
     let c1 = || get(&*x.f);
     let c2 = || *x.f = 5; //~ ERROR cannot borrow `x` as mutable
 }
index 8ab4e257b0626d35a76eca6239519d5e2072e8f4..29546abe0bb20bb66b40b284ea23a686840e61af 100644 (file)
@@ -50,7 +50,7 @@ struct Foo {
         f: Box<isize>
     }
 
-    let mut x = box Foo { f: box 3 };
+    let mut x: Box<_> = box Foo { f: box 3 };
     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 32cd364d1f2d644ad18917d46514eeaa30e795b1..bb474342a7c6f5bcb61fbab51b66e4ba8105f189 100644 (file)
@@ -25,7 +25,7 @@ fn drop(&mut self) {
 }
 
 fn main() {
-  let mut ptr = box Foo { x: 0 };
+  let mut ptr: Box<_> = box Foo { x: 0 };
   let mut test = |foo: &Foo| {
     ptr = box Foo { x: ptr.x + 1 };
   };
index 492fd4a2c849a8ba9d9f7a9c2c1de65fbbe2b32c..b6b260065557a16baac6f2de819475bba376c8a4 100644 (file)
@@ -28,7 +28,7 @@ fn main() {
     for &a in &f.a {  //~ ERROR cannot move out
     }
 
-    let x = Some(box 1);
+    let x: Option<Box<_>> = Some(box 1);
     for &a in x.iter() {    //~ ERROR cannot move out
     }
 }
index cc562afa9f818ecbe89946d1c0d64378020f1a69..deae1fbad20c8484f65d2d6b47b9d7c3ac78b71f 100644 (file)
@@ -18,7 +18,7 @@ struct B<'a> { a: Box<&'a mut isize> }
 
 fn borrow_in_var_from_var() {
     let mut x: isize = 1;
-    let y = box &mut x;
+    let y: Box<_> = box &mut x;
     let p = &y;
     let q = &***p;
     **y = 2; //~ ERROR cannot assign to `**y` because it is borrowed
@@ -28,7 +28,7 @@ fn borrow_in_var_from_var() {
 
 fn borrow_in_var_from_field() {
     let mut x = A { a: 1 };
-    let y = box &mut x.a;
+    let y: Box<_> = box &mut x.a;
     let p = &y;
     let q = &***p;
     **y = 2; //~ ERROR cannot assign to `**y` because it is borrowed
index 0c717d2ee5ffff4a9a194c1cdcbed3187aef57b3..0e1712137d34e27c554732cd7aa48e869ef3ee16 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(box_syntax)]
 
 fn main() {
-    let x = Some(box 1);
+    let x: Option<Box<_>> = Some(box 1);
     match x {
       Some(ref _y) => {
         let _a = x; //~ ERROR cannot move
index b4e5ae1c25bf799b13c00d3048d52e17c96a341c..a389a4a5593f07ca879ecbb53f9b6d200636da51 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(box_syntax)]
 
 fn main() {
-    let x = Some(box 1);
+    let x: Option<Box<_>> = Some(box 1);
     match x {
       Some(ref y) => {
         let _b = *y; //~ ERROR cannot move out
index ca8efb5dc967d7f5286982ec741c73a7b20e62c3..0efe8622621785c0e762210c11463bd3b51db05c 100644 (file)
@@ -30,7 +30,7 @@ fn pre_freeze_cond() {
     // In this instance, the freeze is conditional and starts before
     // the mut borrow.
 
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     let _w;
     if cond() {
         _w = &v;
@@ -42,7 +42,7 @@ fn pre_freeze_else() {
     // In this instance, the freeze and mut borrow are on separate sides
     // of the if.
 
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     let _w;
     if cond() {
         _w = &v;
index 5418a531fe68a19dd7e74652ddba41f46cb19331..f841fedf75af913cd03a0e26fe7f17c3b3dfaf5b 100644 (file)
@@ -28,7 +28,7 @@ fn inc(v: &mut Box<isize>) {
 fn loop_overarching_alias_mut() {
     // In this instance, the borrow encompasses the entire loop.
 
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     let mut x = &mut v;
     **x += 1;
     loop {
@@ -39,7 +39,7 @@ fn loop_overarching_alias_mut() {
 fn block_overarching_alias_mut() {
     // In this instance, the borrow encompasses the entire closure call.
 
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     let mut x = &mut v;
     for _ in 0..3 {
         borrow(&*v); //~ ERROR cannot borrow
@@ -50,8 +50,8 @@ fn block_overarching_alias_mut() {
 fn loop_aliased_mut() {
     // In this instance, the borrow is carried through the loop.
 
-    let mut v = box 3;
-    let mut w = box 4;
+    let mut v: Box<_> = box 3;
+    let mut w: Box<_> = box 4;
     let mut _x = &w;
     loop {
         borrow_mut(&mut *v); //~ ERROR cannot borrow
@@ -62,8 +62,8 @@ fn loop_aliased_mut() {
 fn while_aliased_mut() {
     // In this instance, the borrow is carried through the loop.
 
-    let mut v = box 3;
-    let mut w = box 4;
+    let mut v: Box<_> = box 3;
+    let mut w: Box<_> = box 4;
     let mut _x = &w;
     while cond() {
         borrow_mut(&mut *v); //~ ERROR cannot borrow
@@ -75,8 +75,8 @@ fn while_aliased_mut() {
 fn loop_aliased_mut_break() {
     // In this instance, the borrow is carried through the loop.
 
-    let mut v = box 3;
-    let mut w = box 4;
+    let mut v: Box<_> = box 3;
+    let mut w: Box<_> = box 4;
     let mut _x = &w;
     loop {
         borrow_mut(&mut *v);
@@ -89,8 +89,8 @@ fn loop_aliased_mut_break() {
 fn while_aliased_mut_break() {
     // In this instance, the borrow is carried through the loop.
 
-    let mut v = box 3;
-    let mut w = box 4;
+    let mut v: Box<_> = box 3;
+    let mut w: Box<_> = box 4;
     let mut _x = &w;
     while cond() {
         borrow_mut(&mut *v);
@@ -101,8 +101,8 @@ fn while_aliased_mut_break() {
 }
 
 fn while_aliased_mut_cond(cond: bool, cond2: bool) {
-    let mut v = box 3;
-    let mut w = box 4;
+    let mut v: Box<_> = box 3;
+    let mut w: Box<_> = box 4;
     let mut x = &mut w;
     while cond {
         **x += 1;
index 177976c15f0f46831762f717273b6f699c3227fd..6da8f088b3279005474b3368b9d6cd4e5f745784 100644 (file)
@@ -29,7 +29,7 @@ fn inc(v: &mut Box<isize>) {
 fn pre_freeze() {
     // In this instance, the freeze starts before the mut borrow.
 
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     let _w = &v;
     borrow_mut(&mut *v); //~ ERROR cannot borrow
 }
@@ -37,7 +37,7 @@ fn pre_freeze() {
 fn post_freeze() {
     // In this instance, the const alias starts after the borrow.
 
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     borrow_mut(&mut *v);
     let _w = &v;
 }
index 7f676f5166f7f77fb77129553870257313bc66ac..57b584a89599f0a88512b043d7ec66dc34047eff 100644 (file)
@@ -17,7 +17,7 @@ fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) {
 }
 
 fn box_imm() {
-    let v = box 3;
+    let v: Box<_> = box 3;
     let _w = &v;
     thread::spawn(move|| {
         println!("v={}", *v);
@@ -26,7 +26,7 @@ fn box_imm() {
 }
 
 fn box_imm_explicit() {
-    let v = box 3;
+    let v: Box<_> = box 3;
     let _w = &v;
     thread::spawn(move|| {
         println!("v={}", *v);
index a52a4484b20d123440a7c602d20c1c8d9ed6eee9..32d8088549d4fb9fd113ffe82313bee07ab7c4d0 100644 (file)
@@ -15,7 +15,7 @@ fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) {
 }
 
 fn box_imm() {
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     borrow(&*v,
            |w| { //~ ERROR cannot borrow `v` as mutable
             v = box 4;
index a1708e7f497286c81a4d6007aafb13c7ea4420c0..bad521210439ff2f68f3773bea6e627feeb15ad6 100644 (file)
@@ -14,7 +14,7 @@ fn to_fn_mut<A,F:FnMut<A>>(f: F) -> F { f }
 fn to_fn_once<A,F:FnOnce<A>>(f: F) -> F { f }
 
 pub fn main() {
-    let bar = box 3;
+    let bar: Box<_> = box 3;
     let _g = to_fn_mut(|| {
         let _h = to_fn_once(move || -> isize { *bar }); //~ ERROR cannot move out of
     });
index 3d8d599970f2c57715347b74d249b8e1134ec7fe..c02c6a7151428fbedb7e79b8e3b2ff89cde5308d 100644 (file)
@@ -14,7 +14,7 @@
 #![feature(box_syntax)]
 
 fn main() {
-    let a = box box 2;
+    let a: Box<Box<_>> = box box 2;
     let b = &a;
 
     let z = *a; //~ ERROR: cannot move out of `*a` because it is borrowed
index 43bf3f25d1ab9ff4d8380bb8750cb7f857b62679..c46bcbb32b9cf13bd796b10637762629bd7af739 100644 (file)
@@ -15,7 +15,7 @@ fn call_f<F:FnOnce() -> isize>(f: F) -> isize {
 }
 
 fn main() {
-    let t = box 3;
+    let t: Box<_> = box 3;
 
     call_f(move|| { *t + 1 });
     call_f(move|| { *t + 1 }); //~ ERROR capture of moved value
index 9db05d76284e8d23cdc1660fb9e834e3310a9f2f..f417416e7b53e6c860c13f70722845dc9573fa8a 100644 (file)
@@ -15,9 +15,9 @@
 fn borrow<T>(_: &T) { }
 
 fn different_vars_after_borrows() {
-    let x1 = box 1;
+    let x1: Box<_> = box 1;
     let p1 = &x1;
-    let x2 = box 2;
+    let x2: Box<_> = box 2;
     let p2 = &x2;
     thread::spawn(move|| {
         drop(x1); //~ ERROR cannot move `x1` into closure because it is borrowed
@@ -28,9 +28,9 @@ fn different_vars_after_borrows() {
 }
 
 fn different_vars_after_moves() {
-    let x1 = box 1;
+    let x1: Box<_> = box 1;
     drop(x1);
-    let x2 = box 2;
+    let x2: Box<_> = box 2;
     drop(x2);
     thread::spawn(move|| {
         drop(x1); //~ ERROR capture of moved value: `x1`
@@ -39,7 +39,7 @@ fn different_vars_after_moves() {
 }
 
 fn same_var_after_borrow() {
-    let x = box 1;
+    let x: Box<_> = box 1;
     let p = &x;
     thread::spawn(move|| {
         drop(x); //~ ERROR cannot move `x` into closure because it is borrowed
@@ -49,7 +49,7 @@ fn same_var_after_borrow() {
 }
 
 fn same_var_after_move() {
-    let x = box 1;
+    let x: Box<_> = box 1;
     drop(x);
     thread::spawn(move|| {
         drop(x); //~ ERROR capture of moved value: `x`
index 6985d203fb163cc554940e8646d4d56ffeebdb83..8cb7423f3cb5efc1aa4bf349ba25c0b1821f0c31 100644 (file)
@@ -19,7 +19,7 @@ enum cycle {
     empty
 }
 fn main() {
-    let mut x = box cycle::node(node_ {a: box cycle::empty});
+    let mut x: Box<_> = box cycle::node(node_ {a: box cycle::empty});
     // Create a cycle!
     match *x {
       cycle::node(ref mut y) => {
index e9d8544a06a90e3247ed00eced1c778bf52dabfc..58668b73cbffbc609681893e986472ba282117de 100644 (file)
@@ -25,7 +25,7 @@ fn index(&self, &i: &usize) -> &T {
 }
 
 fn main() {
-    let v = MyVec { data: vec!(box 1, box 2, box 3) };
+    let v = MyVec::<Box<_>> { data: vec!(box 1, box 2, box 3) };
     let good = &v[0]; // Shouldn't fail here
     let bad = v[0];
     //~^ ERROR cannot move out of indexed content
index 49a1b782a3db443aeff1c72640ea17e74c722f2c..f36dc0ca43fa25beaa03a6ac3bd03bbbcbaa1f07 100644 (file)
@@ -13,7 +13,7 @@
 fn borrow(_v: &isize) {}
 
 fn local() {
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     borrow(&*v);
 }
 
@@ -32,27 +32,27 @@ struct H { h: Box<isize> }
 }
 
 fn aliased_imm() {
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     let _w = &v;
     borrow(&*v);
 }
 
 fn aliased_mut() {
-    let mut v = box 3;
+    let mut v: Box<_> = box 3;
     let _w = &mut v;
     borrow(&*v); //~ ERROR cannot borrow `*v`
 }
 
 fn aliased_other() {
-    let mut v = box 3;
-    let mut w = box 4;
+    let mut v: Box<_> = box 3;
+    let mut w: Box<_> = box 4;
     let _x = &mut w;
     borrow(&*v);
 }
 
 fn aliased_other_reassign() {
-    let mut v = box 3;
-    let mut w = box 4;
+    let mut v: Box<_> = box 3;
+    let mut w: Box<_> = box 4;
     let mut _x = &mut w;
     _x = &mut v;
     borrow(&*v); //~ ERROR cannot borrow `*v`
index 6bd21101a609df402b94dd01bb93a5a36892a5d7..871f52cbebddc35fa026b3f2ca19c55986428014 100644 (file)
 // Test that cross-borrowing (implicitly converting from `Box<T>` to `&T`) is
 // forbidden when `T` is a trait.
 
-#![feature(box_syntax)]
-
 struct Foo;
 trait Trait { fn foo(&self) {} }
 impl Trait for Foo {}
 
 pub fn main() {
-    let x: Box<Trait> = box Foo;
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let x: Box<Trait> = Box::new(Foo);
     let _y: &Trait = x; //~  ERROR mismatched types
                         //~| expected `&Trait`
                         //~| found `Box<Trait>`
index 7dbb8fc92e345bd3021f2485628f9dcd7ab332a1..8441f3a99e1aa6b3430191b4672c1303de85d3c4 100644 (file)
@@ -10,8 +10,6 @@
 
 // Forbid assignment into a dynamically sized type.
 
-#![feature(box_syntax)]
-
 struct Fat<T: ?Sized> {
     f1: isize,
     f2: &'static str,
@@ -43,7 +41,8 @@ fn to_val(&self) -> isize {
 pub fn main() {
     // Assignment.
     let f5: &mut Fat<ToBar> = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} };
-    let z: Box<ToBar> = box Bar1 {f: 36};
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let z: Box<ToBar> = Box::new(Bar1 {f: 36});
     f5.ptr = *z;
     //~^ ERROR the trait `core::marker::Sized` is not implemented
 }
index 152864b601c20818da6b5f6a8eff691d58a97305..d3029bc6a99801a785754a1a9b8ac6bf92e05ec0 100644 (file)
@@ -10,8 +10,6 @@
 
 // Forbid assignment into a dynamically sized type.
 
-#![feature(box_syntax)]
-
 struct Fat<T: ?Sized> {
     f1: isize,
     f2: &'static str,
@@ -43,7 +41,8 @@ fn to_val(&self) -> isize {
 pub fn main() {
     // Assignment.
     let f5: &mut Fat<ToBar> = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} };
-    let z: Box<ToBar> = box Bar1 {f: 36};
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let z: Box<ToBar> = Box::new(Bar1 {f: 36});
     f5.ptr = Bar1 {f: 36};
     //~^ ERROR mismatched types
     //~| expected `ToBar`
index 9b7df81a5dcbd666e0e489327f6dc9d97516f519..8791481d9e75e63b42ac90350468f0b3d5dc5244 100644 (file)
@@ -9,6 +9,6 @@
 // except according to those terms.
 
 // compile-flags: --extern std=
-// error-pattern: is not a file
+// error-pattern: can't find crate for `std`
 
 fn main() {}
index 45f6e55914a1b07ba3a8c28cd3e87dc4858ee94f..9711d760ae666ccb54409aa5fdb6dd90f43f3478 100644 (file)
@@ -8,13 +8,12 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 fn test<'x>(x: &'x isize) {
-    drop::<Box<for<'z> FnMut(&'z isize) -> &'z isize>>(box |z| {
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    drop::<Box<for<'z> FnMut(&'z isize) -> &'z isize>>(Box::new(|z| {
         x
         //~^ ERROR cannot infer an appropriate lifetime
-    });
+    }));
 }
 
 fn main() {}
index 736f9630127121e23bd24340114c5700f4102656..08e8effc626f5bd68b7e6bda91e97b9fb3fa3aa5 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(box_syntax)]
 
 fn main() {
-    let x = box 1;
+    let x: Box<_> = box 1;
     let f = move|| {
         let _a = x;
         drop(x);
index a95bcc73a9c473adf98a2ac38839dfdeaf42ee73..7313d357ffc1a09f2a068e53e1667be3e953f38c 100644 (file)
@@ -21,7 +21,7 @@ fn drop(&mut self) {
 }
 
 fn main() {
-    let mut ptr = box Foo { x: 0 };
+    let mut ptr: Box<_> = box Foo { x: 0 };
     let mut test = |foo: &Foo| {
         println!("access {}", foo.x);
         ptr = box Foo { x: ptr.x + 1 };
index 4ff574e939df649794a2b31bdd4f49a374ed3c05..f682d618ab646131735f3cf47ff98976be17369c 100644 (file)
@@ -15,6 +15,7 @@ struct Test {
 }
 
 fn main() {
-    let closure: Box<Fn()+'static> = box || ();
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let closure: Box<Fn()+'static> = Box::new(|| ());
     let test = box Test { func: closure }; //~ ERROR mismatched types
 }
index df4dab2552e7de8922613d5f6a683a4a338778b3..7bd072c6268cdfcc7520130b545a62fc46a8a95b 100644 (file)
@@ -14,7 +14,7 @@ fn to_fn_once<A,F:FnOnce<A>>(f: F) -> F { f }
 
 fn main() {
     let r = {
-        let x = box 42;
+        let x: Box<_> = box 42;
         let f = to_fn_once(move|| &x); //~ ERROR: `x` does not live long enough
         f()
     };
index 40d446b91a5a8b659d56cb79dcbec7b202c8249d..5565a9a5761166d0a52fb7649d241990b546c492 100644 (file)
@@ -14,7 +14,7 @@ fn to_fn_once<A,F:FnOnce<A>>(f: F) -> F { f }
 fn do_it(x: &isize) { }
 
 fn main() {
-    let x = box 22;
+    let x: Box<_> = box 22;
     let f = to_fn_once(move|| do_it(&*x));
     to_fn_once(move|| {
         f();
index 543063b3fc968a225f2eb99ef54ef7d2b4c3041d..f40d51f1d2fd3c59c3aef358a2ca1de3b5aef372 100644 (file)
 struct Foo { a: isize, b: isize }
 
 fn main() {
-    let mut x = box Foo { a: 1, b: 2 };
+    let mut x: Box<_> = box Foo { a: 1, b: 2 };
     let (a, b) = (&mut x.a, &mut x.b);
     //~^ ERROR cannot borrow `x` (here through borrowing `x.b`) as mutable more than once at a time
     //~^^ NOTE previous borrow of `x` occurs here (through borrowing `x.a`)
 
-    let mut foo = box Foo { a: 1, b: 2 };
+    let mut foo: Box<_> = box Foo { a: 1, b: 2 };
     let (c, d) = (&mut foo.a, &foo.b);
     //~^ ERROR cannot borrow `foo` (here through borrowing `foo.b`) as immutable
     //~^^ NOTE previous borrow of `foo` occurs here (through borrowing `foo.a`)
index 9f76f360f26ba7db9cf81f7def9321c8110111ad..68ddef671887852f14b200910d6a2529ccf9be92 100644 (file)
@@ -8,18 +8,20 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 fn main() {
     let _foo = &[1_usize, 2] as [usize];
     //~^ ERROR cast to unsized type: `&[usize; 2]` as `[usize]`
     //~^^ HELP consider using an implicit coercion to `&[usize]` instead
-    let _bar = box 1_usize as std::fmt::Debug;
+
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let _bar = Box::new(1_usize) as std::fmt::Debug;
     //~^ ERROR cast to unsized type: `Box<usize>` as `core::fmt::Debug`
     //~^^ HELP did you mean `Box<core::fmt::Debug>`?
+
     let _baz = 1_usize as std::fmt::Debug;
     //~^ ERROR cast to unsized type: `usize` as `core::fmt::Debug`
     //~^^ HELP consider using a box or reference as appropriate
+
     let _quux = [1_usize, 2] as [usize];
     //~^ ERROR cast to unsized type: `[usize; 2]` as `[usize]`
     //~^^ HELP consider using a box or reference as appropriate
index 172f37af834400ba766388c9a2c8a54b4d8b779d..d6471ca018deec2c8c1eea7c26aa1f97090b7905 100644 (file)
 // Test that moves of unsized values within closures are caught
 // and rejected.
 
-#![feature(box_syntax)]
-
 fn main() {
-    (|| box *[0_usize].as_slice())();
-    //~^ ERROR cannot move out of borrowed content
-    //~^^ ERROR cannot move a value of type [usize]
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    (|| Box::new(*[0_usize].as_slice()))();
+    //~^ ERROR the trait `core::marker::Sized` is not implemented for the type `[usize]`
 }
index 8035cffabda9717aa51317533ca9ac4b19944c0c..80e5f2b6e2157917e943bc88a1397a720c917abd 100644 (file)
 #[cfg(target_pointer_width = "64")]
 fn main() {
     let n = 0_usize;
-    let a = box [&n; 0xF000000000000000_usize];
+    let a: Box<_> = box [&n; 0xF000000000000000_usize];
     println!("{}", a[0xFFFFFF_usize]);
 }
 
 #[cfg(target_pointer_width = "32")]
 fn main() {
     let n = 0_usize;
-    let a = box [&n; 0xFFFFFFFF_usize];
+    let a: Box<_> = box [&n; 0xFFFFFFFF_usize];
     println!("{}", a[0xFFFFFF_usize]);
 }
index 13908bda9d83bf1e2d61f8d3304cc8144db12f97..f6a3da81857750fd5937f66b5632e08f8471aafb 100644 (file)
@@ -8,15 +8,15 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 use std::cell::RefCell;
 
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
 fn main() {
     let mut y = 1_usize;
     let c = RefCell::new(vec![]);
-    c.push(box || y = 0);
-    c.push(box || y = 0);
+    c.push(Box::new(|| y = 0));
+    c.push(Box::new(|| y = 0));
 //~^ ERROR cannot borrow `y` as mutable more than once at a time
 }
 
@@ -24,8 +24,8 @@ fn ufcs() {
     let mut y = 1_usize;
     let c = RefCell::new(vec![]);
 
-    Push::push(&c, box || y = 0);
-    Push::push(&c, box || y = 0);
+    Push::push(&c, Box::new(|| y = 0));
+    Push::push(&c, Box::new(|| y = 0));
 //~^ ERROR cannot borrow `y` as mutable more than once at a time
 }
 
index 6e6c19a5bf6b08428a8024e7312b50edf5b2e927..085b4e76afbf71650fece23c0481522a9d9de5da 100644 (file)
@@ -8,8 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 mod my_mod {
     pub struct MyStruct {
         priv_field: isize
@@ -26,10 +24,15 @@ fn main() {
     let my_struct = my_mod::MyStruct();
     let _woohoo = (&my_struct).priv_field;
     //~^ ERROR field `priv_field` of struct `my_mod::MyStruct` is private
-    let _woohoo = (box my_struct).priv_field;
+
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let _woohoo = (Box::new(my_struct)).priv_field;
     //~^ ERROR field `priv_field` of struct `my_mod::MyStruct` is private
+
     (&my_struct).happyfun();               //~ ERROR method `happyfun` is private
-    (box my_struct).happyfun();            //~ ERROR method `happyfun` is private
+
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    (Box::new(my_struct)).happyfun();          //~ ERROR method `happyfun` is private
     let nope = my_struct.priv_field;
     //~^ ERROR field `priv_field` of struct `my_mod::MyStruct` is private
 }
index 85298e4c6e096e3a4e19c576a9ff448fb3685aed..55a793f7480a42e1db237844f544e8271d6c0a10 100644 (file)
@@ -9,12 +9,12 @@
 // except according to those terms.
 
 #![feature(unboxed_closures)]
-#![feature(box_syntax)]
 
 fn id<T>(t: T) -> T { t }
 
 fn f<'r, T>(v: &'r T) -> Box<FnMut() -> T + 'r> {
-    id(box || *v)
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    id(Box::new(|| *v))
         //~^ ERROR `v` does not live long enough
         //~| ERROR cannot move out of borrowed content
 }
index 4d721ad76666dab6c2482a1e207cb0ce31542522..c27362eea3e3c6cea897f9fe8ac073de693fc3d6 100644 (file)
@@ -8,13 +8,12 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 trait Foo { fn foo(&self) {} }
 impl Foo for u8 {}
 
 fn main() {
-    let r: Box<Foo> = box 5;
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let r: Box<Foo> = Box::new(5);
     let _m: Box<Foo> = r as Box<Foo>;
     //~^ ERROR `core::marker::Sized` is not implemented for the type `Foo`
 }
index b575144f637f1e73629df653cb0ae1ea8a3974c2..fd0789421e0045fb4a5c45f25076c139a8ac7e2c 100644 (file)
@@ -21,7 +21,7 @@ impl<T:Copy> Foo for T {
 fn take_param<T:Foo>(foo: &T) { }
 
 fn main() {
-    let x = box 3;
+    let x: Box<_> = box 3;
     take_param(&x);
     //~^ ERROR the trait `core::marker::Copy` is not implemented
 }
index 0072b1228af486d49b47c8e20f3c41c8dd8b83bc..52ca24d0f547a7fe20a4177bdd25f5f19453c630 100644 (file)
@@ -24,12 +24,12 @@ impl<T:Copy> Foo for T {
 fn take_param<T:Foo>(foo: &T) { }
 
 fn a() {
-    let x = box 3;
+    let x: Box<_> = box 3;
     take_param(&x); //~ ERROR `core::marker::Copy` is not implemented
 }
 
 fn b() {
-    let x = box 3;
+    let x: Box<_> = box 3;
     let y = &x;
     let z = &x as &Foo; //~ ERROR `core::marker::Copy` is not implemented
 }
index 985eb1cd7babcb556487c770e122cb82f1dc83e2..6fcab380030331417ffe56711e8eb3630ce9a15f 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(box_syntax)]
 
 fn main() {
-    let x = box 5;
+    let x: Box<_> = box 5;
     let y = x;
     println!("{}", *x); //~ ERROR use of moved value: `*x`
     y.clone();
index 6e8719eeaceda58e6ffce825b5805468cdc8f542..e298a0f62cd81882ab9e47920f4ac74347b58e82 100644 (file)
@@ -26,6 +26,7 @@ impl<K, V> Map<K, V> for HashMap<K, V> {}
 fn main() {
     let x: Box<HashMap<isize, isize>> = box HashMap::new();
     let x: Box<Map<isize, isize>> = x;
-    let y: Box<Map<usize, isize>> = box x;
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let y: Box<Map<usize, isize>> = Box::new(x);
     //~^ ERROR the trait `Map<usize, isize>` is not implemented
 }
index 5d29d0e1fd083914964e45c8bb686ab5da2a082f..068bfa3cd7c7b0728cdee3600590a4d9182e5292 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let x = box 1;
+    let x: Box<_> = box 1;
 
     let v = (1, 2);
 
index 23af25797975f3720843c415adf2ef098ffbd48a..984963b2f830ee2246e297175db744f6d1d3eb47 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let x = box 1;
+    let x: Box<_> = box 1;
 
     let v = (1, 2);
 
index 7e3a85569d413f5ea39a489fa54df1c095de9434..b7393666719630029aa400475ed9bb880ac0acae 100644 (file)
@@ -13,7 +13,7 @@
 struct Foo(Box<isize>);
 
 fn main() {
-    let x = (box 1,);
+    let x: (Box<_>,) = (box 1,);
     let y = x.0;
     let z = x.0; //~ ERROR use of moved value: `x.0`
 
index f410541f0b7e93a15eefae799cf4e74a71771e62..5af326b4298499ed42bfdd5bb505e75657b104d9 100644 (file)
@@ -12,7 +12,6 @@
 // bound must be noncopyable. For details see
 // http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/
 
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 struct R<'a> {
@@ -41,7 +40,8 @@ fn innocent_looking_victim() {
 }
 
 fn conspirator<F>(mut f: F) where F: FnMut(&mut R, bool) {
-    let mut r = R {c: box f};
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let mut r = R {c: Box::new(f)};
     f(&mut r, false) //~ ERROR use of moved value
 }
 
index 2cf6e67a90958baa9742be4d6004340c5bf4f774..6829cd574e1b00114c716a17c851bf14ec930405 100644 (file)
@@ -13,7 +13,7 @@
 fn f(_: &mut isize) {}
 
 fn main() {
-    let mut x = box 3;
+    let mut x: Box<_> = box 3;
     f(x)    //~ ERROR mismatched types
 }
 
index 2da414befd8979312cc7b1c3e18466197d5f9f7a..1bb2bb5a15450f3aa774ded692b1ac6f0e610626 100644 (file)
 // Test that attempts to implicitly coerce a value into an
 // object respect the lifetime bound on the object type.
 
-#![feature(box_syntax)]
-
 trait Foo : ::std::marker::MarkerTrait {}
 impl<'a> Foo for &'a [u8] {}
 
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
 fn a(v: &[u8]) -> Box<Foo + 'static> {
-    let x: Box<Foo + 'static> = box v; //~ ERROR does not fulfill the required lifetime
+    let x: Box<Foo + 'static> = Box::new(v);
+    //~^ ERROR cannot infer an appropriate lifetime due to conflicting
     x
 }
 
 fn b(v: &[u8]) -> Box<Foo + 'static> {
-    box v //~ ERROR does not fulfill the required lifetime
+    Box::new(v)
+        //~^ ERROR cannot infer an appropriate lifetime due to conflicting
 }
 
 fn c(v: &[u8]) -> Box<Foo> {
     // same as previous case due to RFC 599
 
-    box v //~ ERROR does not fulfill the required lifetime
+    Box::new(v)
+        //~^ ERROR cannot infer an appropriate lifetime due to conflicting
 }
 
 fn d<'a,'b>(v: &'a [u8]) -> Box<Foo+'b> {
-    box v //~ ERROR does not fulfill the required lifetime
+    Box::new(v)
+        //~^ ERROR cannot infer an appropriate lifetime due to conflicting
 }
 
 fn e<'a:'b,'b>(v: &'a [u8]) -> Box<Foo+'b> {
-    box v // OK, thanks to 'a:'b
+    Box::new(v) // OK, thanks to 'a:'b
 }
 
 fn main() { }
index 979c1e997d03c8b694c2bcb78605f5fcade1e610..72a024e563c6f6bc06caa285fe9b20879752c471 100644 (file)
@@ -10,6 +10,8 @@
 
 #![feature(box_syntax)]
 
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
 use std::marker::MarkerTrait;
 
 trait X : MarkerTrait {}
@@ -24,48 +26,48 @@ trait Iter {
 fn bad1<T: Iter>(v: T) -> Box<X+'static>
 {
     let item = v.into_item();
-    box item //~ ERROR associated type `<T as Iter>::Item` may not live long enough
+    Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
 }
 
 fn bad2<T: Iter>(v: T) -> Box<X+'static>
     where Box<T::Item> : X
 {
-    let item = box v.into_item();
-    box item //~ ERROR associated type `<T as Iter>::Item` may not live long enough
+    let item: Box<_> = box v.into_item();
+    Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
 }
 
 fn bad3<'a, T: Iter>(v: T) -> Box<X+'a>
 {
     let item = v.into_item();
-    box item //~ ERROR associated type `<T as Iter>::Item` may not live long enough
+    Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
 }
 
 fn bad4<'a, T: Iter>(v: T) -> Box<X+'a>
     where Box<T::Item> : X
 {
-    let item = box v.into_item();
-    box item //~ ERROR associated type `<T as Iter>::Item` may not live long enough
+    let item: Box<_> = box v.into_item();
+    Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
 }
 
 fn ok1<'a, T: Iter>(v: T) -> Box<X+'a>
     where T::Item : 'a
 {
     let item = v.into_item();
-    box item // OK, T::Item : 'a is declared
+    Box::new(item) // OK, T::Item : 'a is declared
 }
 
 fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<X+'a>
     where T::Item : Clone
 {
     let item = Clone::clone(w);
-    box item // OK, T::Item : 'a is implied
+    Box::new(item) // OK, T::Item : 'a is implied
 }
 
 fn ok3<'a, T: Iter>(v: &'a T) -> Box<X+'a>
     where T::Item : Clone + 'a
 {
     let item = Clone::clone(v.as_item());
-    box item // OK, T::Item : 'a was declared
+    Box::new(item) // OK, T::Item : 'a was declared
 }
 
 fn meh1<'a, T: Iter>(v: &'a T) -> Box<X+'a>
@@ -78,7 +80,7 @@ fn meh1<'a, T: Iter>(v: &'a T) -> Box<X+'a>
     // T::Item`. But we're not that smart at present.
 
     let item = Clone::clone(v.as_item());
-    box item //~ ERROR associated type `<T as Iter>::Item` may not live
+    Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live
 }
 
 fn main() {}
index 655ac6f66c97db2ac173069431fcb36ce6203896..eebf93bc89377995173e7a3098eb7b4790203f53 100644 (file)
@@ -8,32 +8,32 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
 
 trait X { fn foo(&self) {} }
 
 fn p1<T>(v: T) -> Box<X+'static>
     where T : X
 {
-    box v //~ ERROR parameter type `T` may not live long enough
+    Box::new(v) //~ ERROR parameter type `T` may not live long enough
 }
 
 fn p2<T>(v: Box<T>) -> Box<X+'static>
     where Box<T> : X
 {
-    box v //~ ERROR parameter type `T` may not live long enough
+    Box::new(v) //~ ERROR parameter type `T` may not live long enough
 }
 
 fn p3<'a,T>(v: T) -> Box<X+'a>
     where T : X
 {
-    box v //~ ERROR parameter type `T` may not live long enough
+    Box::new(v) //~ ERROR parameter type `T` may not live long enough
 }
 
 fn p4<'a,T>(v: Box<T>) -> Box<X+'a>
     where Box<T> : X
 {
-    box v //~ ERROR parameter type `T` may not live long enough
+    Box::new(v) //~ ERROR parameter type `T` may not live long enough
 }
 
 fn main() {}
index 58386c319f8abaaf107f3b7b5d339cd282a3725b..f114a8bc7ce668bfe6a35ac4e3141cf41709bed1 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
 
 fn ignore<T>(t: T) {}
 
@@ -16,17 +16,17 @@ fn nested<'x>(x: &'x isize) {
     let y = 3;
     let mut ay = &y;
 
-    ignore::<Box<for<'z> FnMut(&'z isize)>>(box |z| {
+    ignore::<Box<for<'z> FnMut(&'z isize)>>(Box::new(|z| {
         ay = x; //~ ERROR cannot infer
         ay = &y;
         ay = z;
-    });
+    }));
 
-    ignore::< Box<for<'z> FnMut(&'z isize) -> &'z isize>>(box |z| {
+    ignore::< Box<for<'z> FnMut(&'z isize) -> &'z isize>>(Box::new(|z| {
         if false { return x; }  //~ ERROR cannot infer an appropriate lifetime for automatic
         if false { return ay; }
         return z;
-    });
+    }));
 }
 
 fn main() {}
index cc33d11241757923acc065286c5de077204ca6e9..3c137133c9867ca077ec86420b3d0c6e3716cce6 100644 (file)
@@ -8,17 +8,17 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
 
 fn borrowed_proc<'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a> {
     // This is legal, because the region bound on `proc`
     // states that it captures `x`.
-    box move|| { *x }
+    Box::new(move|| { *x })
 }
 
 fn static_proc(x: &isize) -> Box<FnMut()->(isize) + 'static> {
     // This is illegal, because the region bound on `proc` is 'static.
-    box move|| { *x } //~ ERROR captured variable `x` does not outlive the enclosing closure
+    Box::new(move|| { *x }) //~ ERROR captured variable `x` does not outlive the enclosing closure
 }
 
 fn main() { }
index c9b378d1df26d433eaaffb4dbfed0f8a381d768c..a30d8471a31788e6136a8498f009b8539722a075 100644 (file)
@@ -8,7 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 struct closure_box<'a> {
@@ -22,7 +21,8 @@ fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> {
 fn main() {
     let mut cl_box = {
         let mut i = 3;
-        box_it(box || i += 1) //~ ERROR `i` does not live long enough
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        box_it(Box::new(|| i += 1)) //~ ERROR `i` does not live long enough
     };
     cl_box.cl.call_mut(());
 }
index 200aa9891935a3cee037a9c55cdb39a5392385a5..eca22bfdda07a8a1579af54dd3cb380d5d450c6d 100644 (file)
@@ -13,7 +13,7 @@
 fn f<T:'static>(_: T) {}
 
 fn main() {
-    let x = box 3;
+    let x: Box<_> = box 3;
     f(x);
     let x = &3; //~ ERROR borrowed value does not live long enough
     f(x);
index 1ddfc5b7ccd487d9369e73b06df65189f4fc6292..b25af522b2476e35759af8a255ade6225020a8c0 100644 (file)
@@ -8,8 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 struct Struct {
     person: &'static str
 }
@@ -25,7 +23,8 @@ fn f(&self, x: &'static str) {
 }
 
 fn main() {
-    let s: Box<Trait<isize>> = box Struct { person: "Fred" };
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let s: Box<Trait<isize>> = Box::new(Struct { person: "Fred" });
     //~^ ERROR the trait `Trait<isize>` is not implemented for the type `Struct`
     s.f(1);
 }
index 7b426a4c0331545da4961f70a408d13627fdb7cd..bbe256d1c8fd20cd36d5e0ce303556a72ecea839 100644 (file)
@@ -8,8 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 struct Struct {
     person: &'static str
 }
@@ -27,6 +25,7 @@ fn f(&self, x: &'static str) {
 fn main() {
     let person = "Fred".to_string();
     let person: &str = &person;  //~ ERROR `person` does not live long enough
-    let s: Box<Trait<&'static str>> = box Struct { person: person };
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let s: Box<Trait<&'static str>> = Box::new(Struct { person: person });
 }
 
index 800126450c9726887796a01a8c5343225e3982ab..86e326f3c5a8b7f4b15f708491a39f15c225ccea 100644 (file)
@@ -8,7 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 // Tests that we can't move out of an unboxed closure environment
@@ -19,31 +18,33 @@ fn to_fn<A,F:Fn<A>>(f: F) -> F { f }
 fn to_fn_mut<A,F:FnMut<A>>(f: F) -> F { f }
 fn to_fn_once<A,F:FnOnce<A>>(f: F) -> F { f }
 
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
 fn main() {
     // By-ref cases
     {
-        let x = box 0_usize;
+        let x = Box::new(0_usize);
         let f = to_fn(|| drop(x)); //~ ERROR cannot move
     }
     {
-        let x = box 0_usize;
+        let x = Box::new(0_usize);
         let f = to_fn_mut(|| drop(x)); //~ ERROR cannot move
     }
     {
-        let x = box 0_usize;
+        let x = Box::new(0_usize);
         let f = to_fn_once(|| drop(x)); // OK -- FnOnce
     }
     // By-value cases
     {
-        let x = box 0_usize;
+        let x = Box::new(0_usize);
         let f = to_fn(move || drop(x)); //~ ERROR cannot move
     }
     {
-        let x = box 0_usize;
+        let x = Box::new(0_usize);
         let f = to_fn_mut(move || drop(x)); //~ ERROR cannot move
     }
     {
-        let x = box 0_usize;
+        let x = Box::new(0_usize);
         let f = to_fn_once(move || drop(x)); // this one is ok
     }
 }
index 88535ee04fb5b847fd23c21f4433d4d0331cdcf7..2ec10d08bb41d5ff92087c2eae36c4a410fd15a9 100644 (file)
@@ -8,8 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 #[derive(Debug)]
 struct r {
   b: bool,
@@ -20,7 +18,8 @@ fn drop(&mut self) {}
 }
 
 fn main() {
-    let i = box r { b: true };
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let i = Box::new(r { b: true });
     let _j = i.clone(); //~ ERROR not implement
     println!("{:?}", i);
 }
index 046337c33f0131dc4c2b4f5f5c58e26ec269a63a..86fe4da3429d084f23d164d47fe024fc4811ae79 100644 (file)
@@ -8,15 +8,14 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 use std::rc::Rc;
 
 fn f<T:Send>(__isize: T) {
 }
 
 fn main() {
-    let i = box Rc::new(100);
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let i = Box::new(Rc::new(100));
     f(i);
     //~^ ERROR `core::marker::Send` is not implemented
 }
index 91a41ad6a4986d81e8d91f0dad2bd50642c5642a..938abbf2c2018952a44739b07b3a7c027c866598 100644 (file)
@@ -10,8 +10,6 @@
 
 #![feature(unsafe_destructor)]
 
-#![feature(box_syntax)]
-
 use std::cell::Cell;
 
 #[derive(Debug)]
@@ -36,8 +34,9 @@ fn clone<T: Clone>(t: &T) -> T { t.clone() }
 fn main() {
     let i1 = &Cell::new(0);
     let i2 = &Cell::new(1);
-    let r1 = vec!(box r { i: i1 });
-    let r2 = vec!(box r { i: i2 });
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let r1 = vec!(Box::new(r { i: i1 }));
+    let r2 = vec!(Box::new(r { i: i2 }));
     f(clone(&r1), clone(&r2));
     //~^ ERROR the trait `core::clone::Clone` is not implemented for the type
     //~^^ ERROR the trait `core::clone::Clone` is not implemented for the type
index 1998f8ab15529e5cc110fcd28462a8e6ab0d4b74..26d22b072eb48ce3eda25139d5348ebe21141180 100644 (file)
@@ -34,8 +34,8 @@ fn push(&mut self, n: Box<ToString+'static>) {
 }
 
 fn main() {
-    let n = box Number { n: 42 };
-    let mut l = box List { list: Vec::new() };
+    let n: Box<_> = box Number { n: 42 };
+    let mut l: Box<_> = box List { list: Vec::new() };
     l.push(n);
     let x = n.to_string();
     //~^ ERROR: use of moved value: `n`
index 2cfc6855e5bc6c9e4b4e08d8a38c4250ad261026..4430ea9380d43585a8c11ef49edbaf7febd4a074 100644 (file)
@@ -78,7 +78,7 @@ fn main() {
     let stack_val_interior_ref_2: &f64 = &stack_val.y;
     let ref_to_unnamed: &SomeStruct = &SomeStruct { x: 11, y: 24.5 };
 
-    let unique_val = box SomeStruct { x: 13, y: 26.5 };
+    let unique_val: Box<_> = box SomeStruct { x: 13, y: 26.5 };
     let unique_val_ref: &SomeStruct = &*unique_val;
     let unique_val_interior_ref_1: &int = &unique_val.x;
     let unique_val_interior_ref_2: &f64 = &unique_val.y;
index 972d6ab12e13fea6c3049e0041a2eaf66f39e9b3..9c6e197e65e23ebd495db0996f15fe8ed50c762e 100644 (file)
@@ -57,9 +57,9 @@ fn drop(&mut self) {}
 
 fn main() {
 
-    let unique = box StructWithSomePadding { x: 99, y: 999, z: 9999, w: 99999 };
+    let unique: Box<_> = box StructWithSomePadding { x: 99, y: 999, z: 9999, w: 99999 };
 
-    let unique_dtor = box StructWithDestructor { x: 77, y: 777, z: 7777, w: 77777 };
+    let unique_dtor: Box<_> = box StructWithDestructor { x: 77, y: 777, z: 7777, w: 77777 };
     zzz(); // #break
 }
 
index b92f5de21b5753d0b815d0db6022ae61c04a0f7d..448e157a251b211494910338d7a26a639e0c5ff1 100644 (file)
@@ -60,7 +60,7 @@ fn some_generic_fun<T1, T2>(a: T1, b: T2) -> (T2, T1) {
 
 fn main() {
     some_generic_fun(0.5f64, 10);
-    some_generic_fun(&29, box 110);
+    some_generic_fun(&29, Box::new(110));
 }
 
 fn zzz() { () }
diff --git a/src/test/debuginfo/cross-crate-spans.rs b/src/test/debuginfo/cross-crate-spans.rs
new file mode 100644 (file)
index 0000000..3aef943
--- /dev/null
@@ -0,0 +1,74 @@
+// 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.
+
+#![omit_gdb_pretty_printer_section]
+
+// ignore-android: FIXME(#10381)
+// min-lldb-version: 310
+
+// aux-build:cross_crate_spans.rs
+extern crate cross_crate_spans;
+
+// compile-flags:-g
+
+
+// === GDB TESTS ===================================================================================
+
+// gdb-command:break cross_crate_spans.rs:21
+// gdb-command:run
+
+// gdb-command:print result
+// gdb-check:$1 = {17, 17}
+// gdb-command:print a_variable
+// gdb-check:$2 = 123456789
+// gdb-command:print another_variable
+// gdb-check:$3 = 123456789.5
+// gdb-command:continue
+
+// gdb-command:print result
+// gdb-check:$4 = {1212, 1212}
+// gdb-command:print a_variable
+// gdb-check:$5 = 123456789
+// gdb-command:print another_variable
+// gdb-check:$6 = 123456789.5
+// gdb-command:continue
+
+
+
+// === LLDB TESTS ==================================================================================
+
+// lldb-command:b cross_crate_spans.rs:21
+// lldb-command:run
+
+// lldb-command:print result
+// lldb-check:[...]$0 = (17, 17)
+// lldb-command:print a_variable
+// lldb-check:[...]$1 = 123456789
+// lldb-command:print another_variable
+// lldb-check:[...]$2 = 123456789.5
+// lldb-command:continue
+
+// lldb-command:print result
+// lldb-check:[...]$3 = (1212, 1212)
+// lldb-command:print a_variable
+// lldb-check:[...]$4 = 123456789
+// lldb-command:print another_variable
+// lldb-check:[...]$5 = 123456789.5
+// lldb-command:continue
+
+
+// This test makes sure that we can break in functions inlined from other crates.
+
+fn main() {
+
+    let _ = cross_crate_spans::generic_function(17u32);
+    let _ = cross_crate_spans::generic_function(1212i16);
+
+}
index 8c4eeb27c0f6d5b69c2aefd6e1b10d54233168ed..8b698d900af0428cb2ec8ce8fbb90a71cc80d3fd 100644 (file)
@@ -142,7 +142,7 @@ fn main() {
     let _ = stack.self_by_ref(-1, 2_u16);
     let _ = stack.self_by_val(-3, -4_i16);
 
-    let owned = box Struct { x: 1234.5f64 };
+    let owned: Box<_> = box Struct { x: 1234.5f64 };
     let _ = owned.self_by_ref(-5, -6_i32);
     let _ = owned.self_by_val(-7, -8_i64);
     let _ = owned.self_owned(-9, -10.5_f32);
index 7ad668791d3b899b1ff6f4756c7f2c5fdfdbb5f4..638d73f0d4e3c09e222663576a4a4fb22f8d5bac 100644 (file)
@@ -144,7 +144,7 @@ fn main() {
     let _ = stack.self_by_ref(-1, -2);
     let _ = stack.self_by_val(-3, -4);
 
-    let owned = box Enum::Variant1{ x: 1799, y: 1799 };
+    let owned: Box<_> = box Enum::Variant1{ x: 1799, y: 1799 };
     let _ = owned.self_by_ref(-5, -6);
     let _ = owned.self_by_val(-7, -8);
     let _ = owned.self_owned(-9, -10);
index 6b56a7998c919880a2ba618b9bcd9859a735c361..784d60eec9a1ad953787b9cb7ee984a0710067bf 100644 (file)
@@ -143,7 +143,7 @@ fn main() {
     let _ = stack.self_by_ref(-1, -2);
     let _ = stack.self_by_val(-3, -4);
 
-    let owned = box Struct { x: 1234.5f64 };
+    let owned: Box<_> = box Struct { x: 1234.5f64 };
     let _ = owned.self_by_ref(-5, -6);
     let _ = owned.self_by_val(-7, -8);
     let _ = owned.self_owned(-9, -10);
index e32288a8e7d0362df7765afe467ea62dd3370bd1..a91586a6aa6bee4e335b0a27433c34f2788f7e0c 100644 (file)
@@ -143,7 +143,7 @@ fn main() {
     let _ = stack.self_by_ref(-1, -2);
     let _ = stack.self_by_val(-3, -4);
 
-    let owned = box Struct { x: 200 };
+    let owned: Box<_> = box Struct { x: 200 };
     let _ = owned.self_by_ref(-5, -6);
     let _ = owned.self_by_val(-7, -8);
     let _ = owned.self_owned(-9, -10);
index 6e9a695720a141b68d0288b26c8c9d4074cfc96b..e2c827ee5170f0f8af4b08fbd025a56862556734 100644 (file)
@@ -149,7 +149,7 @@ fn main() {
     let _ = stack.self_by_ref(-1, -2);
     let _ = stack.self_by_val(-3, -4);
 
-    let owned = box Struct { x: 200 };
+    let owned: Box<_> = box Struct { x: 200 };
     let _ = owned.self_by_ref(-5, -6);
     let _ = owned.self_by_val(-7, -8);
     let _ = owned.self_owned(-9, -10);
index cee04e92c2d24e4de671dbb7a5225a1b17a491c2..e8bc40f1810f3b921df98a481eaf00eaa01d76eb 100644 (file)
@@ -141,7 +141,7 @@ fn main() {
     let _ = stack.self_by_ref(-1, -2);
     let _ = stack.self_by_val(-3, -4);
 
-    let owned = box TupleStruct(200, -200.5);
+    let owned: Box<_> = box TupleStruct(200, -200.5);
     let _ = owned.self_by_ref(-5, -6);
     let _ = owned.self_by_val(-7, -8);
     let _ = owned.self_owned(-9, -10);
index cb2b04f4d8695df3f9a116ab144278d3646c8b3c..03a799933421c0d35c629f62507033ccea7dd905 100644 (file)
@@ -143,7 +143,7 @@ fn main() {
     let _ = stack.self_by_ref(-1, -2);
     let _ = stack.self_by_val(-3, -4);
 
-    let owned = box Struct { x: 200 };
+    let owned: Box<_> = box Struct { x: 200 };
     let _ = owned.self_by_ref(-5, -6);
     let _ = owned.self_by_val(-7, -8);
     let _ = owned.self_owned(-9, -10);
index b96ec3b7b889cc18f815403a47798b3d6fd3b092..5869625bafe597feeeb2c24470d2b3230d608d16 100644 (file)
@@ -144,7 +144,7 @@ fn main() {
     let _ = stack.self_by_ref(-1, 2_u16);
     let _ = stack.self_by_val(-3, -4_i16);
 
-    let owned = box Struct { x: 879 };
+    let owned: Box<_> = box Struct { x: 879 };
     let _ = owned.self_by_ref(-5, -6_i32);
     let _ = owned.self_by_val(-7, -8_i64);
     let _ = owned.self_owned(-9, -10.5_f32);
index 69b5797007bdb8b689708aa6315a5d9a536fc8be..607a237d22e41ee1b4624cb0e1710b253e13864c 100644 (file)
@@ -67,15 +67,15 @@ fn main() {
     // 0b01111100011111000111110001111100 = 2088533116
     // 0b0111110001111100 = 31868
     // 0b01111100 = 124
-    let the_a = box ABC::TheA { x: 0, y: 8970181431921507452 };
+    let the_a: Box<_> = box ABC::TheA { x: 0, y: 8970181431921507452 };
 
     // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
     // 0b00010001000100010001000100010001 = 286331153
     // 0b0001000100010001 = 4369
     // 0b00010001 = 17
-    let the_b = box ABC::TheB (0, 286331153, 286331153);
+    let the_b: Box<_> = box ABC::TheB (0, 286331153, 286331153);
 
-    let univariant = box Univariant::TheOnlyCase(123234);
+    let univariant: Box<_> = box Univariant::TheOnlyCase(123234);
 
     zzz(); // #break
 }
index 9c9d82249ee317d70764a9f17fdd8067f6a9806e..05872e3fc36b2fb8072e01ab07fe29b931041864 100644 (file)
@@ -98,7 +98,7 @@ fn main() {
     };
 
     let struct_ref = &a_struct;
-    let owned = box 6;
+    let owned: Box<_> = box 6;
 
     let mut closure = || {
         let closure_local = 8;
index 3c442c95e0f59aa0329cc2029ad13207ee0c7c54..295d57f4cfa97fc22acc1926bbba4b5bf40d20d4 100644 (file)
@@ -58,7 +58,7 @@ fn main() {
         c: 4
     };
 
-    let owned = box 5;
+    let owned: Box<_> = box 5;
 
     let closure = move || {
         zzz(); // #break
index e3bd1eade7538d9d3c08b429c1962e2e3e90ac99..57dcac409bab8ad6cd39e22d5081dfccd84708cc 100644 (file)
@@ -90,7 +90,7 @@ fn main() {
     };
 
     let struct_ref = &a_struct;
-    let owned = box 6;
+    let owned: Box<_> = box 6;
 
     {
         let mut first_closure = || {
index ac5ec1236ff9d083294b9503ac261c84022f0436..3e548981f1ed4676f86801259a8573090f35044a 100644 (file)
@@ -9,10 +9,10 @@
 // except according to those terms.
 
 #[path = "circular_modules_hello.rs"]
-mod circular_modules_hello; //~ERROR: circular modules
+mod circular_modules_hello; //~ ERROR: circular modules
 
 pub fn hi_str() -> String {
-  "Hi!".to_string()
+    "Hi!".to_string()
 }
 
 fn main() {
index 597366a1b35dfc8b8ad13d393f1132b56d727828..b2608cc0b925ef41056586b1b1332292b78c4635 100644 (file)
@@ -8,15 +8,8 @@
 // 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.
+// ignore-windows
+// ignore-freebsd
 
 #[path = "../compile-fail"]
 mod foo; //~ ERROR: a directory
index 89e47bf46ab020c375f1d16a72acb219d9379513..4d0f7c29cb9df4ead4e9e10ff50fb7c2e2d7e386 100644 (file)
@@ -10,9 +10,6 @@
 
 // error-pattern:panicked at 'Box<Any>'
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 fn main() {
-    panic!(box 612_i64);
+    panic!(Box::new(612_i64));
 }
index 9f643c09795dfd1c63ca7a45c50ee1959f2c7eae..83b2bb91f0073a59ba3418da547d8df276e47677 100644 (file)
@@ -10,7 +10,4 @@
 
 // error-pattern: panic
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
-fn main() { box panic!(); }
+fn main() { Box::new(panic!()); }
index e1176b1bcdbc931f7ce1806cfad95c9cbb8a53b7..f4ba789d6bf7be1c92b6bb1b7e2114c4936aae4f 100644 (file)
 
 // error-pattern:fail
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 fn failfn() {
     panic!();
 }
 
 fn main() {
-    box 0;
+    Box::new(0);
     failfn();
 }
index cff4d44910b3146d312c11a0d41958d79c3a22c8..1ed816ed7290a87645737874135e5a3169a04de4 100644 (file)
@@ -18,6 +18,8 @@
 use rustc_driver::driver::{compile_input, CompileController};
 use syntax::diagnostics::registry::Registry;
 
+use std::path::PathBuf;
+
 fn main() {
     let src = r#"
     fn main() {}
@@ -29,9 +31,9 @@ fn main() {}
         panic!("expected rustc path");
     }
 
-    let tmpdir = Path::new(&args[1]);
+    let tmpdir = PathBuf::new(&args[1]);
 
-    let mut sysroot = Path::new(&args[3]);
+    let mut sysroot = PathBuf::new(&args[3]);
     sysroot.pop();
     sysroot.pop();
 
@@ -40,7 +42,7 @@ fn main() {}
     compile(src.to_string(), tmpdir.join("out"), sysroot.clone());
 }
 
-fn basic_sess(sysroot: Path) -> Session {
+fn basic_sess(sysroot: PathBuf) -> Session {
     let mut opts = basic_options();
     opts.output_types = vec![OutputTypeExe];
     opts.maybe_sysroot = Some(sysroot);
@@ -51,7 +53,7 @@ fn basic_sess(sysroot: Path) -> Session {
     sess
 }
 
-fn compile(code: String, output: Path, sysroot: Path) {
+fn compile(code: String, output: PathBuf, sysroot: PathBuf) {
     let sess = basic_sess(sysroot);
     let cfg = build_configuration(&sess);
     let control = CompileController::basic();
index 38381da3670c18be3fa9e126ccb3c08e0237f031..7d94f4c7b172a0b09be5dbf7727cb78351db7a6e 100644 (file)
@@ -245,9 +245,10 @@ fn hello<X: SomeTrait>((z, a) : (u32, String), ex: X) {
     let x = 32.0f32;
     let _ = (x + ((x * x) + 1.0).sqrt()).ln();
 
-    let s: Box<SomeTrait> = box some_fields {field1: 43};
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let s: Box<SomeTrait> = Box::new(some_fields {field1: 43});
     let s2: Box<some_fields> =  box some_fields {field1: 43};
-    let s3 = box nofields;
+    let s3: Box<_> = box nofields;
 
     s.Method(43);
     s3.Method(43);
@@ -282,7 +283,7 @@ pub struct blah {
 }
 
 fn main() { // foo
-    let s = box some_fields {field1: 43};
+    let s: Box<_> = box some_fields {field1: 43};
     hello((43, "a".to_string()), *s);
     sub::sub2::hello();
     sub2::sub3::hello();
index 9e164522d77a60db51fd8c6e693eecb7587b36a2..75a968c3f811330de7eda03ceacbbfbd5e54e7d8 100644 (file)
@@ -25,6 +25,7 @@
 use rustc_driver::{driver, CompilerCalls, Compilation};
 use syntax::diagnostics;
 
+use std::path::PathBuf;
 
 struct TestCalls {
     count: u32
@@ -43,14 +44,15 @@ fn late_callback(&mut self,
                      _: &getopts::Matches,
                      _: &Session,
                      _: &Input,
-                     _: &Option<Path>,
-                     _: &Option<Path>)
+                     _: &Option<PathBuf>,
+                     _: &Option<PathBuf>)
                      -> Compilation {
         self.count *= 3;
         Compilation::Stop
     }
 
-    fn some_input(&mut self, input: Input, input_path: Option<Path>) -> (Input, Option<Path>) {
+    fn some_input(&mut self, input: Input, input_path: Option<PathBuf>)
+                  -> (Input, Option<PathBuf>) {
         self.count *= 5;
         (input, input_path)
     }
@@ -58,10 +60,10 @@ fn some_input(&mut self, input: Input, input_path: Option<Path>) -> (Input, Opti
     fn no_input(&mut self,
                 _: &getopts::Matches,
                 _: &config::Options,
-                _: &Option<Path>,
-                _: &Option<Path>,
+                _: &Option<PathBuf>,
+                _: &Option<PathBuf>,
                 _: &diagnostics::registry::Registry)
-                -> Option<(Input, Option<Path>)> {
+                -> Option<(Input, Option<PathBuf>)> {
         panic!("This shouldn't happen");
     }
 
diff --git a/src/test/run-pass-fulldeps/mbe_matching_test_macro.rs b/src/test/run-pass-fulldeps/mbe_matching_test_macro.rs
new file mode 100644 (file)
index 0000000..5383b11
--- /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.
+
+// aux-build:procedural_mbe_matching.rs
+// ignore-stage1
+
+#![feature(plugin)]
+#![plugin(procedural_mbe_matching)]
+
+#[no_link]
+extern crate procedural_mbe_matching;
+
+pub fn main() {
+    let abc = 123u32;
+    assert_eq!(matches!(Some(123), None | Some(0)), false);
+    assert_eq!(matches!(Some(123), None | Some(123)), true);
+    assert_eq!(matches!(true, true), true);
+}
index 252d297d12d3053d44f3be816057c9d146d0e928..92cb0d71e4570fe6f422f4549b6da83ff07d64b3 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// 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.
 //
@@ -74,6 +74,9 @@ fn main() {
 
     let arm = quote_arm!(cx, (ref x, ref y) => (x, y));
     check_pp(ext_cx, arm, pprust::print_stmt, "(ref x, ref y) = (x, y)".to_string());
+
+    let attr = quote_attr!(cx, #![cfg(foo = "bar")]);
+    check_pp(ext_cx, attr, pprust::print_attribute, "#![cfg(foo = "bar")]".to_string());
 }
 
 fn check_pp<T>(cx: fake_ext_ctxt,
index e76c379177b9962dec61dfa1028c2ebe95d4180f..4e6f9b46402956e51100735eda180f76e0b6d4dc 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// 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.
 //
@@ -40,6 +40,9 @@ fn syntax_extension(cx: &ExtCtxt) {
     let _k: P<syntax::ast::Method> = quote_method!(cx, #[doc = "hello"] fn foo(&self) {});
 
     let _l: P<syntax::ast::Ty> = quote_ty!(cx, &int);
+
+    let _m: Vec<syntax::ast::TokenTree> = quote_matcher!(cx, $($foo:tt,)* bar);
+    let _n: syntax::ast::Attribute = quote_attr!(cx, #![cfg(foo, bar = "baz")]);
 }
 
 fn main() {
index c49a684de945df046b3015e2cd5b0a35488b865e..d051b7b491b946d775b677ca982c4e7fba40dc1a 100644 (file)
@@ -8,8 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 static mut DROP_RAN: bool = false;
 
 struct Foo;
@@ -28,7 +26,8 @@ struct Fat<T: ?Sized> {
 
 pub fn main() {
     {
-        let _x: Box<Fat<Trait>> = box Fat { f: Foo };
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        let _x: Box<Fat<Trait>> = Box::<Fat<Foo>>::new(Fat { f: Foo });
     }
     unsafe {
         assert!(DROP_RAN);
index 2c7b89d680a3d92275c096f97dd55f35eb6de962..2cb5f77fdc3f3b0e7385a08478c60d6d2def0862 100644 (file)
@@ -8,8 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(box_syntax)]
-
 static mut DROP_RAN: int = 0;
 
 struct Foo;
@@ -25,7 +23,8 @@ struct Fat<T: ?Sized> {
 
 pub fn main() {
     {
-        let _x: Box<Fat<[Foo]>> = box Fat { f: [Foo, Foo, Foo] };
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        let _x: Box<Fat<[Foo]>> = Box::<Fat<[Foo; 3]>>::new(Fat { f: [Foo, Foo, Foo] });
     }
     unsafe {
         assert!(DROP_RAN == 3);
index e55a2d39cbf889af375405d39a020049a64eddfa..c52e04322e911b24ce1e881e0a119c3f3d968243 100644 (file)
@@ -8,15 +8,12 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 #[derive(PartialEq, Debug)]
 struct Point { x : int }
 
 pub fn main() {
     assert_eq!(14,14);
     assert_eq!("abc".to_string(),"abc".to_string());
-    assert_eq!(box Point{x:34},box Point{x:34});
+    assert_eq!(Box::new(Point{x:34}),Box::new(Point{x:34}));
     assert_eq!(&Point{x:34},&Point{x:34});
 }
index 7365e052171eff975809517f89c5a5a7b8d056ce..941e9a84538025b34d0b0b3e030cee1d90449a7a 100644 (file)
@@ -25,6 +25,7 @@ fn pairwise_sub(mut t: Box<DoubleEndedIterator<Item=int>>) -> int {
 
 fn main() {
     let v = vec!(1, 2, 3, 4, 5, 6);
-    let r = pairwise_sub(box v.into_iter());
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let r = pairwise_sub(Box::new(v.into_iter()));
     assert_eq!(r, 9);
 }
index 9e88eb6da6aea813b1f6472ce2206ead59bec651..8121edfd2cc6ddc621aca2bede107744482bd06b 100644 (file)
@@ -20,6 +20,6 @@ fn double(self: Box<uint>) -> uint { *self * 2_usize }
 }
 
 pub fn main() {
-    let x = box() (box 3_usize as Box<double>);
+    let x: Box<_> = box() (box 3_usize as Box<double>);
     assert_eq!(x.double(), 6_usize);
 }
index 67dd25ddc5389154872251209486312aee9291ef..537894bfd158dffdeb71cd5d8e90fb7166525f38 100644 (file)
@@ -24,6 +24,6 @@ fn double(self) -> uint { *self * 2_usize }
 }
 
 pub fn main() {
-    let x = box 3_usize;
+    let x: Box<_> = box 3_usize;
     assert_eq!(x.double(), 6_usize);
 }
index 6437c78161c00f72d4fa104533ebc79216330130..2ffdd576ffb783aae0c29ca52d55cf35a8719c79 100644 (file)
@@ -20,6 +20,6 @@ fn double(self: Box<Box<uint>>) -> uint { **self * 2_usize }
 }
 
 pub fn main() {
-    let x = box box box box box 3_usize;
+    let x: Box<Box<Box<Box<Box<_>>>>> = box box box box box 3_usize;
     assert_eq!(x.double(), 6_usize);
 }
index 8cbc151f0cd24af4930e5eaeb24296789b1983b1..82510aea162b8bb733610bf96d781b9abe3351fa 100644 (file)
@@ -20,6 +20,6 @@ fn double(self: Box<uint>) -> uint { *self * 2_usize }
 }
 
 pub fn main() {
-    let x = box box 3_usize;
+    let x: Box<Box<_>> = box box 3_usize;
     assert_eq!(x.double(), 6_usize);
 }
index c8fa3c9fd5fb505518d1e71e396f891d0321beb1..c9aa1133101788ef3fafad86029e04a25b1e4417 100644 (file)
@@ -20,6 +20,6 @@ fn double(self: Box<uint>) -> uint { *self * 2_usize }
 }
 
 pub fn main() {
-    let x = box 3_usize;
+    let x: Box<_> = box 3_usize;
     assert_eq!(x.double(), 6_usize);
 }
index 87157b9334f167f0bf3a540a5dbcd132e9e37613..6e6e58a7ddf104796a2d5895cc16f1bcd6f574e0 100644 (file)
@@ -29,6 +29,6 @@ fn foo(&self) -> String {
 }
 
 pub fn main() {
-    let x = box 3_usize;
+    let x: Box<_> = box 3_usize;
     assert_eq!(x.foo(), "box 3".to_string());
 }
index 7bb9f042fe891ee418b2112c7f522f82fa54bbd7..24bfbd9eb44088b54b901caaa95587d5653255e7 100644 (file)
@@ -16,8 +16,8 @@
 use std::collections::BitVec;
 
 fn bitv_test() {
-    let mut v1 = box BitVec::from_elem(31, false);
-    let v2 = box BitVec::from_elem(31, true);
+    let mut v1: Box<_> = box BitVec::from_elem(31, false);
+    let v2: Box<_> = box BitVec::from_elem(31, true);
     v1.union(&*v2);
 }
 
index 1be57674fa1ff4ad9c981e3bd59c924029011e39..27fbfc9641088137c6abe59aa178e9c854d45d96 100644 (file)
@@ -13,7 +13,7 @@
 #![feature(unboxed_closures)]
 
 pub fn main() {
-    let bar = box 3;
+    let bar: Box<_> = box 3;
     let h = || -> int *bar;
     assert_eq!(h(), 3);
 }
index 2dbaec8fbb16796e8d072f80aa8e73e005876c6e..499650a6e51db82718408d3a71225b5d6e437f1e 100644 (file)
@@ -30,7 +30,7 @@ fn iter_ints<F>(x: &Ints, mut f: F) -> bool where F: FnMut(&int) -> bool {
 }
 
 pub fn main() {
-    let mut ints = box Ints {sum: box 0, values: Vec::new()};
+    let mut ints: Box<_> = box Ints {sum: box 0, values: Vec::new()};
     add_int(&mut *ints, 22);
     add_int(&mut *ints, 44);
 
index 00c600ed006f87d8125fa0ba0da420e3cb526cf2..89babb8f7221d4fdf2120ee1e218f77ec3c1ab2c 100644 (file)
@@ -17,7 +17,7 @@
 use cci_borrow_lib::foo;
 
 pub fn main() {
-    let p = box 22_usize;
+    let p: Box<_> = box 22_usize;
     let r = foo(&*p);
     println!("r={}", r);
     assert_eq!(r, 22_usize);
index 96ae7e3d3368f2fdc5abed5d7c8fbbbdd5f16e85..ff883294fd3940b4c115ef22e195b433b37e788b 100644 (file)
@@ -43,7 +43,7 @@ fn get_bar(x: uint) -> Vec<uint> { vec!(x * 2) }
 
 pub fn fails() {
     let x = 2;
-    let mut y = Vec::new();
+    let mut y: Vec<Box<_>> = Vec::new();
     y.push(box Conzabble::Bickwick(do_it(&get_bar(x))));
 }
 
index 8eeae7a28ac8543978d2078df31d197c7a466f24..5cc567cb14c6efda9c6561f00cdcced39a449d0d 100644 (file)
@@ -19,7 +19,7 @@ struct Pair {
 }
 
 pub fn main() {
-    let z = box Pair { a : 10, b : 12};
+    let z: Box<_> = box Pair { a : 10, b : 12};
 
     let _t = Thread::spawn(move|| {
         assert_eq!(z.a, 10);
index ee19d9e69b3018788b4abd0e534f0fa065375dc9..8a9325aecb1438832904b9deb3b6990dafdb91dd 100644 (file)
 // rvalue expressions to be unsized. See #20169 for more information.
 
 pub fn main() {
-    let _: Box<[int]> = box { [1, 2, 3] };
-    let _: Box<[int]> = box if true { [1, 2, 3] } else { [1, 3, 4] };
-    let _: Box<[int]> = box match true { true => [1, 2, 3], false => [1, 3, 4] };
-    let _: Box<Fn(int) -> _> = box { |x| (x as u8) };
-    let _: Box<Debug> = box if true { false } else { true };
-    let _: Box<Debug> = box match true { true => 'a', false => 'b' };
+    // FIXME #22405: We cannot infer the type `Box<[int; k]>` for
+    // the r-value expression from the context `Box<[int]>`, and
+    // therefore the `box EXPR` desugaring breaks down.
+    //
+    // One could reasonably claim that the `box EXPR` desugaring is
+    // effectively regressing half of Issue #20169. Hopefully we will
+    // eventually fix that, at which point the `Box::new` calls below
+    // should be replaced wth uses of `box`.
+
+    let _: Box<[int]> = Box::new({ [1, 2, 3] });
+    let _: Box<[int]> = Box::new(if true { [1, 2, 3] } else { [1, 3, 4] });
+    let _: Box<[int]> = Box::new(match true { true => [1, 2, 3], false => [1, 3, 4] });
+    let _: Box<Fn(int) -> _> = Box::new({ |x| (x as u8) });
+    let _: Box<Debug> = Box::new(if true { false } else { true });
+    let _: Box<Debug> = Box::new(match true { true => 'a', false => 'b' });
 
     let _: &[int] = &{ [1, 2, 3] };
     let _: &[int] = &if true { [1, 2, 3] } else { [1, 3, 4] };
@@ -36,6 +45,6 @@ pub fn main() {
 
     let _: Vec<Box<Fn(int) -> _>> = vec![
         Box::new(|x| (x as u8)),
-        box |x| (x as i16 as u8),
+        Box::new(|x| (x as i16 as u8)),
     ];
 }
index 098a08b07871d29a274736e4b0fb50ebba987e85..2592957b738596541d5bdd1afc5058d2787e9e5f 100644 (file)
 #![feature(box_syntax)]
 
 pub fn main() {
-    let _: Box<[int]> = if true { box [1, 2, 3] } else { box [1] };
+    let _: Box<[int]> =
+        if true { let b: Box<_> = box [1, 2, 3]; b } else { let b: Box<_> = box [1]; b };
 
-    let _: Box<[int]> = match true { true => box [1, 2, 3], false => box [1] };
+    let _: Box<[int]> = match true {
+        true => { let b: Box<_> = box [1, 2, 3]; b }
+        false => { let b: Box<_> = box [1]; b }
+    };
 
     // Check we don't get over-keen at propagating coercions in the case of casts.
     let x = if true { 42 } else { 42u8 } as u16;
index 93a7d3e1c36aa1bf095a89ac9f313e0f1468e861..3a64f53dbb01e4ef7d76a4b230af19904f5b845b 100644 (file)
@@ -11,9 +11,6 @@
 // Make sure const bounds work on things, and test that a few types
 // are const.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 fn foo<T: Sync>(x: T) -> T { x }
 
 struct F { field: int }
@@ -25,5 +22,5 @@ pub fn main() {
     foo(F{field: 42});
     foo((1, 2_usize));
     foo(@1);*/
-    foo(box 1);
+    foo(Box::new(1));
 }
index 1a3e87b55b64b5f5a438c8bceda395f08ed8dde5..043bfe429add3286620f4eefd503d6d66767e09d 100644 (file)
@@ -22,7 +22,7 @@
 pub fn main() {
     use crate_method_reexport_grrrrrrr2::rust::add;
     use crate_method_reexport_grrrrrrr2::rust::cx;
-    let x = box() ();
+    let x: Box<_> = box () ();
     x.cx();
     let y = ();
     y.add("hi".to_string());
index 41c74250b3b0ef0a7ebfecb6cd900f3ded848553..fc97b22a4a99e3cedd167e1789ca91091854e4b6 100644 (file)
@@ -14,7 +14,7 @@
 use std::cell::Cell;
 
 pub fn main() {
-    let x = box Cell::new(5);
+    let x: Box<_> = box Cell::new(5);
     x.set(1000);
     println!("{}", x.get());
 }
index b00ceb6ed22c75b622f25e57b26278dfccd5d1bd..4d157f64fb9eda85553d93f8141692b990783a73 100644 (file)
@@ -20,6 +20,7 @@ struct A {
 
 pub fn main() {
     let a: A = Default::default();
-    let b: Box<[_]> = box [];
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let b: Box<[_]> = Box::<[bool; 0]>::new([]);
     assert_eq!(a.foo, b);
 }
index 838d05cf0d53084873383d4c3cabd51529818619..454156b4c9e3fa25b9c0ddcbfff14a15f9738afd 100644 (file)
@@ -23,7 +23,8 @@ struct A {
 }
 
 fn main() {
-    let obj = A { foo: box [true, false] };
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let obj = A { foo: Box::new([true, false]) };
     let s = json::encode(&obj).unwrap();
     let obj2: A = json::decode(&s).unwrap();
     assert!(obj.foo == obj2.foo);
index 3b89c943edb1c20f4f2cae307338e4699f4b7ee5..03c93d3ab949b1efa06265c00e3989819f0b0bb1 100644 (file)
@@ -8,15 +8,13 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 #[derive(PartialEq, PartialOrd, Eq, Ord)]
 struct Foo(Box<[u8]>);
 
 pub fn main() {
-    let a = Foo(box [0, 1, 2]);
-    let b = Foo(box [0, 1, 2]);
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let a = Foo(Box::new([0, 1, 2]));
+    let b = Foo(Box::new([0, 1, 2]));
     assert!(a == b);
     println!("{}", a != b);
     println!("{}", a < b);
index 909f7f4897a6ae8372e20dc2355f65de47976c48..33548d5e298cd16600594173574b8549a810dc42 100644 (file)
@@ -10,9 +10,6 @@
 
 // Test that a custom deref with a fat pointer return type does not ICE
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 use std::ops::{Deref, DerefMut};
 
 pub struct Arr {
@@ -41,6 +38,7 @@ pub fn foo(arr: &mut Arr) {
 }
 
 fn main() {
-    let mut a = Arr { ptr: box [1, 2, 3] };
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let mut a = Arr { ptr: Box::new([1, 2, 3]) };
     foo(&mut a);
 }
index ad4456b5b592d1a05fc65715cbc7e35aff8e4a4e..147a27afa80ed69b683fcc0a59d994675d6c307c 100644 (file)
@@ -10,9 +10,6 @@
 
 // Test that a custom deref with a fat pointer return type does not ICE
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 use std::ops::Deref;
 
 pub struct Arr {
@@ -36,6 +33,7 @@ pub fn foo(arr: &Arr) {
 }
 
 fn main() {
-    let a = Arr { ptr: box [1, 2, 3] };
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let a = Arr { ptr: Box::new([1, 2, 3]) };
     foo(&a);
 }
index ee5193adbc6a4b1d93218a7d3ca0e6e4d3626e44..15558414bf58ebeeffc68cb9b478e2dcf218b0c2 100644 (file)
@@ -115,7 +115,7 @@ pub fn main() {
     foo3(f5);
 
     // Box.
-    let f1 = box [1, 2, 3];
+    let f1 = Box::new([1, 2, 3]);
     assert!((*f1)[1] == 2);
     let f2: Box<[int]> = f1;
     assert!((*f2)[1] == 2);
@@ -125,6 +125,9 @@ pub fn main() {
     foo(&*f1);
     let f2 : Box<Fat<[int]>> = f1;
     foo(&*f2);
-    let f3 : Box<Fat<[int]>> = box Fat { f1: 5, f2: "some str", ptr: [1, 2, 3] };
+
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let f3 : Box<Fat<[int]>> =
+        Box::<Fat<[_; 3]>>::new(Fat { f1: 5, f2: "some str", ptr: [1, 2, 3] });
     foo(&*f3);
 }
index fd1c7247e375d501a9c637b0606c593fcbc9bb79..6590a8e1847dca828bc8446200ddeff140a5bae2 100644 (file)
@@ -95,7 +95,9 @@ pub fn main() {
     assert!(f6.ptr.to_bar() == Bar);
 
     // &*
-    let f7: Box<ToBar> = box Bar1 {f :42};
+    //
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let f7: Box<ToBar> = Box::new(Bar1 {f :42});
     bar(&*f7);
 
     // Deep nesting
index 269e0ee6ce425662b5acd6ba452d547b205bf0bb..0459206c5b910854504bfeaa5227e69079d0a479 100644 (file)
@@ -8,18 +8,17 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
 
 pub fn main() {
-    assert!(Some(box() ()).is_some());
+    assert!(Some(Box::new(())).is_some());
 
-    let xs: Box<[()]> = box [];
+    let xs: Box<[()]> = Box::<[(); 0]>::new([]);
     assert!(Some(xs).is_some());
 
     struct Foo;
-    assert!(Some(box Foo).is_some());
+    assert!(Some(Box::new(Foo)).is_some());
 
-    let ys: Box<[Foo]> = box [];
+    let ys: Box<[Foo]> = Box::<[Foo; 0]>::new([]);
     assert!(Some(ys).is_some());
 }
index e95d58c706b27689f96c016ac3d7581eac87d25a..f56d8843acd3fae7fc37fc4ecdca227b8a064f68 100644 (file)
@@ -8,9 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 pub fn main() {
-    let x = *box() ();
+    let x = *Box::new(());
 }
index 382c5c58e92ee70adfde48df8f9c2c248706f94b..865fccbc3fa3a865e65dbdfebcee08ea08a1c390 100644 (file)
@@ -33,6 +33,6 @@ pub fn len(&mut self) -> uint {
 }
 
 pub fn main() {
-    let mut m = box linear_map::<(),()>();
+    let mut m: Box<_> = box linear_map::<(),()>();
     assert_eq!(m.len(), 0);
 }
index e5d8ec3f8ad0d497ca6ae282fd3360343ae1f233..3d06a5562034cc0c383bcfba68ad93a498f66bc8 100644 (file)
@@ -70,7 +70,7 @@ pub fn spam(self) -> int { self.x.a }
 impl Nus for thing { fn f(&self) {} }
 
 pub fn main() {
-    let y = box thing(A {a: 10});
+    let y: Box<_> = box thing(A {a: 10});
     assert_eq!(y.clone().bar(), 10);
     assert_eq!(y.quux(), 10);
 
index d10b209965f1374dfed9eedb68f3d1bb71f50152..d7d5a39f452f3dee030474b068d7e7ba05c4fd0d 100644 (file)
@@ -12,4 +12,4 @@
 #![allow(unknown_features)]
 #![feature(box_syntax)]
 
-pub fn main() { let x = { box 100 }; assert!((*x == 100)); }
+pub fn main() { let x: Box<_> = { box 100 }; assert!((*x == 100)); }
index 317e54349301144d7f54355f48f810980e3c1572..a58161277989870bf9da7f8a5230ecf9ec836897 100644 (file)
@@ -15,7 +15,7 @@
 
 // Tests for if as expressions returning boxed types
 fn test_box() {
-    let rs = if true { box 100 } else { box 101 };
+    let rs: Box<_> = if true { box 100 } else { box 101 };
     assert_eq!(*rs, 100);
 }
 
index 57ccfe1d5e09253a72c2904093282b842ea1a1dd..9641cacddc0a682e22cc498188ed097e172df876 100644 (file)
@@ -13,7 +13,7 @@
 
 // Tests for match as expressions resulting in boxed types
 fn test_box() {
-    let res = match true { true => { box 100 }, _ => panic!() };
+    let res: Box<_> = match true { true => { box 100 }, _ => panic!() };
     assert_eq!(*res, 100);
 }
 
index b23d8db3cfdd58890ab12cf9c765e74ad1194b9b..581f71a737651a59f5fe1abfcac2eda76e3fd6a8 100644 (file)
@@ -25,7 +25,7 @@ fn foo(Foo {x, ..}: Foo) -> *const uint {
 }
 
 pub fn main() {
-    let obj = box 1;
+    let obj: Box<_> = box 1;
     let objptr: *const uint = &*obj;
     let f = Foo {x: obj, y: box 2};
     let xptr = foo(f);
index 5d44a9461bebcbaf7d30511917e84ea04f3ed0c8..799b865bd2d7aa5c91d50d27cadd4b42f05716c0 100644 (file)
@@ -28,7 +28,7 @@ fn checkval(box ref x: Box<uint>) -> uint {
 }
 
 pub fn main() {
-    let obj = box 1;
+    let obj: Box<_> = box 1;
     let objptr: *const uint = &*obj;
     let xptr = getaddr(obj);
     assert_eq!(objptr, xptr);
index db468ba1802a662f374f32325f86be7e193cbb51..42062b89cfd2fe459eb7d2c86612ec88cab8a7dc 100644 (file)
@@ -14,7 +14,7 @@
 fn id<T:Send>(t: T) -> T { return t; }
 
 pub fn main() {
-    let expected = box 100;
+    let expected: Box<_> = box 100;
     let actual = id::<Box<int>>(expected.clone());
     println!("{}", *actual);
     assert_eq!(*expected, *actual);
index 677038af9a9c4e0de4609f0622e812f17f377486..81c4054d0091013a9d9ff2fccddb52e32f327965 100644 (file)
@@ -9,7 +9,6 @@
 // except according to those terms.
 
 #![allow(unknown_features)]
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 /**
@@ -61,7 +60,8 @@ fn emit(im: &mut HashMap<String, int>,
         }
 
         let ctrl_clone = ctrl.clone();
-        ::map(input, box |a,b| emit(&mut intermediates, ctrl.clone(), a, b) );
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        ::map(input, Box::new(|a,b| emit(&mut intermediates, ctrl.clone(), a, b)));
         ctrl_clone.send(ctrl_proto::mapper_done).unwrap();
     }
 
index b59e7b67d4eddb4ad11b80ede4fe0193feb0ad4e..f4daf9a4f629789696ce65177ad9f18ea75235b3 100644 (file)
@@ -9,7 +9,6 @@
 // except according to those terms.
 
 #![allow(unknown_features)]
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 // Test that `Fn(int) -> int + 'static` parses as `(Fn(int) -> int) +
@@ -17,7 +16,8 @@
 // cause a compilation error. Issue #18772.
 
 fn adder(y: int) -> Box<Fn(int) -> int + 'static> {
-    box move |x| y + x
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    Box::new(move |x| y + x)
 }
 
 fn main() {}
index 62b8ff528a5e2e1395881d72a19a6dba16a8765e..41c859214e96b188cdc19f970946831ad3bf30f2 100644 (file)
@@ -154,7 +154,7 @@ pub fn main() {
     test_order();
 
     // make sure that format! doesn't move out of local variables
-    let a = box 3;
+    let a: Box<_> = box 3;
     format!("{}", a);
     format!("{}", a);
 
index ee793359fbc89b522786b7c281d93987f0b35b24..4ee06d44e65656a1f8957c09f0722f8619a5a9ad 100644 (file)
@@ -67,7 +67,7 @@ fn test_tup() {
 fn test_unique() {
     let i = &Cell::new(0);
     {
-        let _a = box r(i);
+        let _a: Box<_> = box r(i);
     }
     assert_eq!(i.get(), 1);
 }
@@ -75,7 +75,7 @@ fn test_unique() {
 fn test_unique_rec() {
     let i = &Cell::new(0);
     {
-        let _a = box BoxR {
+        let _a: Box<_> = box BoxR {
             x: r(i)
         };
     }
index d3f62f9d04ad030555d7e393432d5c152cd3976c..1d7a74b042fac815fb7dbc48a9f70873122d607c 100644 (file)
@@ -40,7 +40,7 @@ mod rusti {
 
 pub fn main() {
     unsafe {
-        let mut x = box 1;
+        let mut x: Box<_> = box 1;
 
         assert_eq!(rusti::atomic_load(&*x), 1);
         *x = 5;
index 0daf661c2f6c5bd04f882d018065e1774893f666..09dd5304ec5c21a2a75bdb0bf22c4c270507ff47 100644 (file)
@@ -23,7 +23,7 @@ mod rusti {
 
 pub fn main() {
     unsafe {
-        let x = box 1;
+        let x: Box<_> = box 1;
         let mut y = rusti::init();
         let mut z: *const uint = transmute(&x);
         rusti::move_val_init(&mut y, x);
index 174a69e1135cdf7a766ada2f71a70984dd537e7d..48ea00e47d696a70c2ef4bd6c72eb7b1e6d12a2d 100644 (file)
@@ -42,13 +42,13 @@ fn new(w: Box<MyTrait+'static>) -> Whatever {
 
 fn main() {
     {
-        let f = box DroppableStruct;
+        let f: Box<_> = box DroppableStruct;
         let _a = Whatever::new(box f as Box<MyTrait>);
     }
     assert!(unsafe { DROPPED });
     unsafe { DROPPED = false; }
     {
-        let f = box DroppableEnum::DroppableVariant1;
+        let f: Box<_> = box DroppableEnum::DroppableVariant1;
         let _a = Whatever::new(box f as Box<MyTrait>);
     }
     assert!(unsafe { DROPPED });
index 1325b51a54ff2b6a4380f38bb7d64f8d9420846f..c67ce92ee0a9acebcc4bb53e0b876e0fd3728656 100644 (file)
@@ -9,8 +9,8 @@
 // except according to those terms.
 
 #![allow(dead_code)]
-#![allow(unknown_features)]
-#![feature(box_syntax)]
+
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
 
 trait Foo { fn dummy(&self) { } }
 impl Foo for int {}
@@ -39,16 +39,16 @@ fn main() {
     let r = &1;
     foog(x, &[r]);
 
-    let x: [Box<Foo>; 2] = [box 1, box 2];
+    let x: [Box<Foo>; 2] = [Box::new(1), Box::new(2)];
     bar(x);
-    bar([box 1, box 2]);
+    bar([Box::new(1), Box::new(2)]);
 
-    let x: &[Box<Foo>] = &[box 1, box 2];
+    let x: &[Box<Foo>] = &[Box::new(1), Box::new(2)];
     bars(x);
-    bars(&[box 1, box 2]);
+    bars(&[Box::new(1), Box::new(2)]);
 
-    let x: &[Box<Foo>] = &[box 1, box 2];
-    foog(x, &[box 1]);
+    let x: &[Box<Foo>] = &[Box::new(1), Box::new(2)];
+    foog(x, &[Box::new(1)]);
 
     struct T<'a> {
         t: [&'a (Foo+'a); 2]
@@ -85,9 +85,9 @@ struct M<'a> {
         t: &'a [Box<Foo+'static>]
     }
     let _n = M {
-        t: &[box 1, box 2]
+        t: &[Box::new(1), Box::new(2)]
     };
-    let x: [Box<Foo>; 2] = [box 1, box 2];
+    let x: [Box<Foo>; 2] = [Box::new(1), Box::new(2)];
     let _n = M {
         t: &x
     };
index 7cccac4483d49da1edfed2dd0c397493dc45c16d..4b2b3e8702427fc8725405d37e887b1831faff2f 100644 (file)
@@ -9,8 +9,6 @@
 // except according to those terms.
 
 #![allow(dead_code)]
-#![allow(unknown_features)]
-#![feature(box_syntax)]
 
 // this code used to cause an ICE
 
@@ -28,5 +26,6 @@ impl X<int> for F {
 }
 
 fn main() {
-  S {f: box F, g: box F};
+  // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+  S {f: Box::new(F), g: Box::new(F) };
 }
index 2f7ba315aa1f6ae073f1e5d8f0c3f684070131e4..56d1d3599c7fde3dcb7e3cfd8a49c5a88cc46d2f 100644 (file)
@@ -8,10 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 fn main() {
-    fn test() -> Box<std::any::Any + 'static> { box 1 }
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    fn test() -> Box<std::any::Any + 'static> { Box::new(1) }
     println!("{:?}", test())
 }
index 3c5ece87b737dabae0d7d16709bd68175e3a9cbb..96e2a0dc48539c71f620dfdf434145e038d9d119 100644 (file)
@@ -8,16 +8,14 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 struct Foo<'a> {
     listener: Box<FnMut() + 'a>,
 }
 
 impl<'a> Foo<'a> {
     fn new<F>(listener: F) -> Foo<'a> where F: FnMut() + 'a {
-        Foo { listener: box listener }
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        Foo { listener: Box::new(listener) }
     }
 }
 
index db7eacce9d10b007292ae09dce9b550eef54543f..d413e323a09997738ede945cb2b603abb11e2b08 100644 (file)
@@ -23,6 +23,6 @@ trait A { fn foo(&self) {} }
 impl A for B1 {}
 
 fn main() {
-    let v = box B1;
+    let v: Box<_> = box B1;
     let _c: Box<A> = v.clone();
 }
index 71d88ee6215103a991f81a0a2ea904f45ad3cf16..5924aa44d4d63c672dc701041d446289fdd8cfc6 100644 (file)
 // All 3 expressions should work in that the argument gets
 // coerced to a trait object
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
 
 fn main() {
-    send::<Box<Foo>>(box Output(0));
-    Test::<Box<Foo>>::foo(box Output(0));
-    Test::<Box<Foo>>::new().send(box Output(0));
+    send::<Box<Foo>>(Box::new(Output(0)));
+    Test::<Box<Foo>>::foo(Box::new(Output(0)));
+    Test::<Box<Foo>>::new().send(Box::new(Output(0)));
 }
 
 fn send<T>(_: T) {}
index 933e7e40f06d34ce23ae96de299da6a594acb62b..fbf08ab564d3510d9ba11ed64340cee2d1f47a3d 100644 (file)
@@ -8,9 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 trait Matcher {
     fn next_match(&mut self) -> Option<(uint, uint)>;
 }
@@ -32,9 +29,10 @@ trait IntoMatcher<'a, T> {
 
 impl<'a, 'b, F> IntoMatcher<'a, CharPredMatcher<'a, 'b>> for F where F: FnMut(char) -> bool + 'b {
     fn into_matcher(self, s: &'a str) -> CharPredMatcher<'a, 'b> {
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
         CharPredMatcher {
             str: s,
-            pred: box self,
+            pred: Box::new(self),
         }
     }
 }
index ab9554f65d4c89d93aa6c813b883551d737809ea..5b093d16cbf838a3f7c0a5b0735a3b3fcdef4f3d 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 fn match_on_local() {
-    let mut foo = Some(box 5);
+    let mut foo: Option<Box<_>> = Some(box 5);
     match foo {
         None => {},
         Some(x) => {
@@ -33,7 +33,7 @@ fn match_on_arg(mut foo: Option<Box<i32>>) {
 }
 
 fn match_on_binding() {
-    match Some(box 7) {
+    match Some(Box::new(7)) {
         mut foo => {
             match foo {
                 None => {},
@@ -47,7 +47,7 @@ fn match_on_binding() {
 }
 
 fn match_on_upvar() {
-    let mut foo = Some(box 8i32);
+    let mut foo: Option<Box<_>> = Some(box 8i32);
     let f = move|| {
         match foo {
             None => {},
index daf09047bef723649a519d9d5a952376ce28b4ec..786c701a0427bf0808c321b14002c872c25f1c4e 100644 (file)
@@ -11,7 +11,6 @@
 // ignore-pretty
 
 #![allow(unknown_features)]
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 struct Parser<'a, I, O> {
@@ -20,13 +19,14 @@ 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> {
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
         Parser {
-            parse: box move |x: I| {
+            parse: Box::new(move |x: I| {
                 match (self.parse)(x) {
                     Ok(r) => (rhs.parse)(r),
                     Err(e) => Err(e)
                 }
-            }
+            })
         }
     }
 }
index 3cff16409cb9b811c2b6fdf782bb18fdb7824578..497361969bfc3cffa1eddd796358c4c8a496eb05 100644 (file)
 
 // Test that generating drop glue for Box<str> doesn't ICE
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 fn f(s: Box<str>) -> Box<str> {
     s
 }
 
 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];
+    //
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let box_arr: Box<[u8]> = Box::new(['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, "hello");
     f(box_str);
index ec7481ead0482dd29af975617cf66ad6bd2ae045..2011b87e731021a96761aaea10b2d56ff5d963fd 100644 (file)
@@ -11,9 +11,6 @@
 // Check that trans doesn't ICE when translating an array repeat
 // expression with a count of 1 and a non-Copy element type.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 fn main() {
-    let _ = [box 1_usize; 1];
+    let _ = [Box::new(1_usize); 1];
 }
index f83150b95184b15167322500172257ba08346325..9ebd96a685eafefbccb7c421098bee23a51cc7ba 100644 (file)
 
 // Test that overloaded calls work with zero arity closures
 
-#![feature(box_syntax)]
-
 fn main() {
-    let functions: [Box<Fn() -> Option<()>>; 1] = [box || None];
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let functions: [Box<Fn() -> Option<()>>; 1] = [Box::new(|| None)];
 
     let _: Option<Vec<()>> = functions.iter().map(|f| (*f)()).collect();
 }
index 80e9ca470251775107a4ab4c03961df14ae64c86..0bef42b6202edfaec0291b7706f2b8a63ed10452 100644 (file)
@@ -17,6 +17,6 @@ fn a_val(x: Box<int>, y: Box<int>) -> int {
 }
 
 pub fn main() {
-    let z = box 22;
+    let z: Box<_> = box 22;
     a_val(z.clone(), z.clone());
 }
index 1f072af0f5a64c44c7739f47e7c414bc40490b4c..6aeec228c0d3e2f9a1bf4f3564b21daece451fa0 100644 (file)
@@ -31,5 +31,5 @@ fn Font() -> Font {
 }
 
 pub fn main() {
-    let _f = box Font();
+    let _f: Box<_> = box Font();
 }
index b8a541a0fc4de70876fe5240ec7efebbbc8e6192..ae146d8d35356960d45f15ec5ec1642f2e870bb4 100644 (file)
@@ -11,8 +11,6 @@
 //
 // ignore-lexer-test FIXME #15883
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
 #![feature(unsafe_destructor)]
 
 pub type Task = int;
@@ -52,11 +50,11 @@ unsafe impl<T:Send> Send for packet<T> {}
 
     pub fn packet<T:Send>() -> *const packet<T> {
         unsafe {
-            let p: *const packet<T> = mem::transmute(box Stuff{
+            let p: *const packet<T> = mem::transmute(Box::new(Stuff{
                 state: empty,
                 blocked_task: None::<Task>,
                 payload: None::<T>
-            });
+            }));
             p
         }
     }
index 31599d0caadeeee981557c3a874df23db7a1db0f..e653dda8de5f00591470368694d1b2ad82b4aac8 100644 (file)
@@ -28,7 +28,7 @@ pub fn main() {
   //   let y = box ({a: 4});
   //    let z = box ({a: 4} as it);
   //    let z = box ({a: true} as it);
-    let z = box() (box true as Box<it>);
+    let z: Box<_> = box () (box true as Box<it>);
     //  x.f();
     // y.f();
     // (*z).f();
index de2d4374d787fdf15915dbcf5b082fdb862fd69e..6f107a37e9b25b9bec97cb09f671e76b61017910 100644 (file)
@@ -20,5 +20,5 @@
 
 pub fn main() {
     let fd: libc::c_int = 1 as libc::c_int;
-    let _sock = box socket::socket_handle(fd);
+    let _sock: Box<_> = box socket::socket_handle(fd);
 }
index 25663f2605fcb4233cc47bc27743d738068f188b..98c9f3d5ec5ade97e045bbbe8973429857c07078 100644 (file)
@@ -17,7 +17,7 @@
 use std::collections::HashMap;
 
 pub fn main() {
-    let x;
+    let x: Box<_>;
     let mut buggy_map: HashMap<uint, &uint> = HashMap::new();
     x = box 1;
     buggy_map.insert(42, &*x);
index 3e7deee6ec10720b4690df4336df72e1beae4bca..0784c8be883c84dd39abde8723b1fd19404c1282 100644 (file)
@@ -8,13 +8,11 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 type Connection = Box<FnMut(Vec<u8>) + 'static>;
 
 fn f() -> Option<Connection> {
-    let mock_connection: Connection = box |_| {};
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let mock_connection: Connection = Box::new(|_| {});
     Some(mock_connection)
 }
 
index c8d6e69801fa13094a05b57347bcf9ab35c8bd9a..1c1b329e314c1d7ad96109c6467d138005685926 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-   let mut x = box 3;
+   let mut x: Box<_> = box 3;
    x = x;
    assert_eq!(*x, 3);
 }
index 0d85f61e51350d7dbc3715882505ab855f3f3d6e..e039be058defec1a6f6d1502da16eeda8172bcc5 100644 (file)
@@ -11,7 +11,6 @@
 // rustc --test ignores2.rs && ./ignores2
 
 #![allow(unknown_features)]
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 use std::old_path::{Path};
 
 fn tester()
 {
-    let mut loader: rsrc_loader = box move|_path| {
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let mut loader: rsrc_loader = Box::new(move|_path| {
         result::Result::Ok("more blah".to_string())
-    };
+    });
 
     let path = old_path::Path::new("blah");
     assert!(loader(&path).is_ok());
index 4a28c34e5d9f4299683811b7159e100fe59a5823..28e44536892a5a5d1be7919b0e4561bfb2e2a6b0 100644 (file)
@@ -9,7 +9,6 @@
 // except according to those terms.
 
 #![allow(unknown_features)]
-#![feature(box_syntax)]
 
 use std::thread::Thread;
 use std::sync::mpsc::Sender;
@@ -27,8 +26,8 @@ fn foo(name: String, samples_chan: Sender<Msg>) {
     let _t = Thread::spawn(move|| {
         let mut samples_chan = samples_chan;
 
-        // `box() (...)` syntax is needed to make pretty printer converge in one try:
-        let callback: SamplesFn = box() (move |buffer| {
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        let callback: SamplesFn = Box::new(move |buffer| {
             for i in 0_usize..buffer.len() {
                 println!("{}: {}", i, buffer[i])
             }
index c1d19f228db617511960278bbb2f5dbfb016fe32..1f53d9ce5422fc4831c540c3725beb2c424debf6 100644 (file)
@@ -13,6 +13,6 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let y = box 1;
+    let y: Box<_> = box 1;
     y;
 }
index 36aa8a9cbca5d2c66e4f225328e6943117d380da..7e773cd799476c12f9b46b0a53c991ba0d8c57f4 100644 (file)
@@ -16,7 +16,7 @@
 macro_rules! foo {
     ($tag: expr, $string: expr) => {
         if $tag == $string {
-            let element = box Element;
+            let element: Box<_> = box Element;
             unsafe {
                 return std::mem::transmute::<_, uint>(element);
             }
index 93edffdcb477fc9c62a7801c3bf302a4f062875e..562e2b68af174391bd71ddbf093f919bb22445db 100644 (file)
@@ -8,13 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 enum Either<T, U> { Left(T), Right(U) }
 
 pub fn main() {
-    match Either::Left(box 17) {
+    match Either::Left(Box::new(17)) {
         Either::Right(()) => {}
         _ => {}
     }
index 494b62178550349f2f545b5fee1c3c3d74690f90..d4d2603bfe2449b2626257b4e9504bcbdbe550b2 100644 (file)
@@ -8,18 +8,15 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 pub fn main() {
-    match &[(box 5,box 7)] {
+    match &[(Box::new(5),Box::new(7))] {
         ps => {
            let (ref y, _) = ps[0];
            assert!(**y == 5);
         }
     }
 
-    match Some(&[(box 5,)]) {
+    match Some(&[(Box::new(5),)]) {
         Some(ps) => {
            let (ref y,) = ps[0];
            assert!(**y == 5);
@@ -27,7 +24,7 @@ pub fn main() {
         None => ()
     }
 
-    match Some(&[(box 5,box 7)]) {
+    match Some(&[(Box::new(5),Box::new(7))]) {
         Some(ps) => {
            let (ref y, ref z) = ps[0];
            assert!(**y == 5);
index 566d34e6d86df763a4c9f13ee51bed0ea8555dae..74ddb990c31cb839928d1da2fffdd1a64cb0a06c 100644 (file)
 struct A { a: Box<isize> }
 
 fn foo() -> Box<FnMut() -> isize + 'static> {
-    let k = box 22;
+    let k: Box<_> = box 22;
     let _u = A {a: k.clone()};
     // FIXME(#16640) suffix in `22_isize` suffix shouldn't be necessary
     let result  = || 22_isize;
-    box result
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    Box::new(result)
 }
 
 pub fn main() {
index 19a780d180f2804d404971bf0f3de5827ccbc364..7b11aae168ca965744ccbb01a9423e799947db1f 100644 (file)
@@ -17,7 +17,7 @@ struct A { a: Box<int> }
 
 pub fn main() {
     fn invoke<F>(f: F) where F: FnOnce() { f(); }
-    let k = box 22;
+    let k: Box<_> = box 22;
     let _u = A {a: k.clone()};
     invoke(|| println!("{}", k.clone()) )
 }
index 9ac016d534f09c40c40ca235a1abdf74890b3fe0..1500edce779c371d5baa8ee5d069b95a2695c4f8 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 fn f() {
-    let a = box 1;
+    let a: Box<_> = box 1;
     let b: &int = &*a;
     println!("{}", b);
 }
index 6883187c402f3a3af8aa398e141cfd8fe03e1711..cd4802f4b397a6407f5e4525f459b842d415b99b 100644 (file)
@@ -14,7 +14,7 @@
 struct Pair { a: Box<int>, b: Box<int> }
 
 pub fn main() {
-    let mut x = box Pair {a: box 10, b: box 20};
+    let mut x: Box<_> = box Pair {a: box 10, b: box 20};
     let x_internal = &mut *x;
     match *x_internal {
       Pair {a: ref mut a, b: ref mut _b} => {
index 7463783be59892fe95a343a2eb4a220c5f773e45..a49ce82617007e2921b3fb5f207af537c0b1eccb 100644 (file)
@@ -39,7 +39,7 @@ fn call_foo_copy() -> int {
 }
 
 fn call_foo_other() -> int {
-    let mut x = Vec::new();
+    let mut x: Vec<Box<_>> = Vec::new();
     let y = x.foo();
     x.push(box 0);
     y
index 018cd440cad343523c65327f3661fb0273f58bdb..ff06df079b05e029717153c437d1d7a6ff28432f 100644 (file)
@@ -26,7 +26,7 @@ fn test(x: bool, foo: Box<Triple>) -> int {
 }
 
 pub fn main() {
-    let x = box Triple{x: 1, y: 2, z: 3};
+    let x: Box<_> = box Triple{x: 1, y: 2, z: 3};
     assert_eq!(test(true, x.clone()), 2);
     assert_eq!(test(true, x.clone()), 2);
     assert_eq!(test(true, x.clone()), 2);
index 50187ef8baad23fb8768c8e242b79c0a4e0ed139..590caff3c2dc850c168fb376c7c72b8137efba7a 100644 (file)
@@ -14,7 +14,7 @@
 struct X { x: int, y: int, z: int }
 
 pub fn main() {
-    let x = box X{x: 1, y: 2, z: 3};
+    let x: Box<_> = box X{x: 1, y: 2, z: 3};
     let y = x;
     assert!((y.y == 2));
 }
index 6561a9b2d5b565c24a3f6c525400170ee4d7b4af..0bff2c2292e74be2caf7c884473571bc40f038f0 100644 (file)
@@ -13,4 +13,4 @@
 
 struct X { x: int, y: int, z: int }
 
-pub fn main() { let x = box X {x: 1, y: 2, z: 3}; let y = x; assert!((y.y == 2)); }
+pub fn main() { let x: Box<_> = box X {x: 1, y: 2, z: 3}; let y = x; assert!((y.y == 2)); }
index 07d0594b494d966d1f5df70c0e05ffcf9423ac2d..8241424124e0e0e3373913c695927e0cd14a61f4 100644 (file)
@@ -26,7 +26,7 @@ fn test(x: bool, foo: Box<Triple>) -> int {
 }
 
 pub fn main() {
-    let x = box Triple{x: 1, y: 2, z: 3};
+    let x: Box<_> = box Triple{x: 1, y: 2, z: 3};
     for _ in 0_usize..10000_usize {
         assert_eq!(test(true, x.clone()), 2);
     }
index 64c4f1fdbaeabf6e2d9e06bdb80646e4063c4ede..d68a7c831f212ca4ae683e5e4469e4cc9c818d83 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(box_syntax)]
 
 fn main() {
-    let x = box 1;
+    let x: Box<_> = box 1;
 
     let v = (1, 2);
 
index 130cdc85b013d6af888468b6e809197e4c5d264b..039e53cab8044805db0dd51f51c63c482867bcd0 100644 (file)
 // Test that the lambda kind is inferred correctly as a return
 // expression
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
-fn unique() -> Box<FnMut()+'static> { return box || (); }
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+fn unique() -> Box<FnMut()+'static> { return Box::new(|| ()); }
 
 pub fn main() {
 }
index 0952bedd6e309a2fbfdcc798db2e30f2657064c7..b7216c87c30bbc22a7f174ca07c3f25ea4447d61 100644 (file)
 // Test that the lambda kind is inferred correctly as a return
 // expression
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
-fn unique() -> Box<FnMut()+'static> { box || () }
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+fn unique() -> Box<FnMut()+'static> { Box::new(|| ()) }
 
 pub fn main() {
 }
index f40c9dc45cab1c592adc549c22d50c1e557934e3..6436165968d678801130a581164d5a9e85b9f6fa 100644 (file)
@@ -22,9 +22,10 @@ struct Point {
 }
 
 pub fn main() {
-    let box_5 = box 5_usize;
+    let box_5: Box<_> = box 5_usize;
     assert_eq!(Rc::new(5_usize).to_uint(), Some(5));
-    assert_eq!((box &box &Rc::new(box box &box_5)).to_uint(), Some(5));
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    assert_eq!((Box::new(&Box::new(&Rc::new(Box::new(Box::new(&box_5)))))).to_uint(), Some(5));
     let point = Rc::new(Point {x: 2, y: 4});
     assert_eq!(point.x, 2);
     assert_eq!(point.y, 4);
index f56e7d56fe16aec00df2034f97375ea37f461eb2..bb1694be5e29b7765b8d2ae00449fbb84fa948a0 100644 (file)
@@ -8,9 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 use std::cell::RefCell;
 use std::rc::Rc;
 use std::string::String;
@@ -23,7 +20,7 @@ struct Point {
 
 pub fn main() {
     assert_eq!(*Rc::new(5), 5);
-    assert_eq!(***Rc::new(box box 5), 5);
+    assert_eq!(***Rc::new(Box::new(Box::new(5))), 5);
     assert_eq!(*Rc::new(Point {x: 2, y: 4}), Point {x: 2, y: 4});
 
     let i = Rc::new(RefCell::new(2));
index d5ccf8cd2befb0f4f18e29fc0021ba49f4d814bf..8f655f0517ddf47fe56224d420ba0e0a34992a59 100644 (file)
@@ -55,7 +55,7 @@ fn get_from_ref(&self) -> int { *self }
 }
 
 fn main() {
-    let mut f = box Foo {
+    let mut f: Box<_> = box Foo {
         x: 1,
         y: 2,
     };
index 2db6f7ffaaa61ccab311c3ecb93a978c91ddc04a..9be6b212a3caabd0b7259800b96999d68cf5ceee 100644 (file)
@@ -8,11 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 fn f<T: 'static>(_x: T) {}
 
 pub fn main() {
-    f(box 5);
+    f(Box::new(5));
 }
index f7adb0f6e444b91a18adedd6e70817a352dfe351..1fd83041f62077ca3c824706e7ae3bf9eef4904d 100644 (file)
@@ -25,7 +25,7 @@ fn sums_to(v: Vec<int> , sum: int) -> bool {
 
 fn sums_to_using_uniq(v: Vec<int> , sum: int) -> bool {
     let mut i = 0_usize;
-    let mut sum0 = box 0;
+    let mut sum0: Box<_> = box 0;
     while i < v.len() {
         *sum0 += v[i];
         i += 1_usize;
@@ -47,7 +47,7 @@ struct F<T> { f: T }
 
 fn sums_to_using_uniq_rec(v: Vec<int> , sum: int) -> bool {
     let mut i = 0_usize;
-    let mut sum0 = F {f: box 0};
+    let mut sum0 = F::<Box<_>> {f: box 0};
     while i < v.len() {
         *sum0.f += v[i];
         i += 1_usize;
index 84a230fd5767c201b25a00b417a735ebd4b39ff6..7bc761d2f606d06119d9b83a25196ade1b54c10b 100644 (file)
@@ -25,7 +25,7 @@ fn get(self) -> int {
 }
 
 pub fn main() {
-    let x = box 6;
+    let x: Box<_> = box 6;
     let y = x.get();
     println!("y={}", y);
     assert_eq!(y, 6);
index 89779fa4d2d46283df19b5420768fa98ebaa617b..1e91ab7e921d32aeeba7361bbca7c4d7cb109806 100644 (file)
@@ -16,7 +16,7 @@ fn foo(x: &uint) -> uint {
 }
 
 pub fn main() {
-    let p = box 22_usize;
+    let p: Box<_> = box 22_usize;
     let r = foo(&*p);
     println!("r={}", r);
     assert_eq!(r, 22_usize);
index a1af7159a93d99235a5927b467d75e16e222b4ed..7c9b1ae226f5aca97a6f091b970149367bda301c 100644 (file)
@@ -16,7 +16,7 @@ fn foo(x: &uint) -> uint {
 }
 
 pub fn main() {
-    let p = box 3_usize;
+    let p: Box<_> = box 3_usize;
     let r = foo(&*p);
     assert_eq!(r, 3_usize);
 }
index 6ebef9f34ad6619d54bd1798288acd183bf532d1..3704fc1d8d1a30dcec80b0b287195eb9d94d2963 100644 (file)
@@ -9,7 +9,6 @@
 // except according to those terms.
 
 #![allow(unknown_features)]
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 struct closure_box<'a> {
@@ -25,7 +24,8 @@ pub fn main() {
     assert_eq!(i, 3);
     {
         let cl = || i += 1;
-        let mut cl_box = box_it(box cl);
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        let mut cl_box = box_it(Box::new(cl));
         cl_box.cl.call_mut(());
     }
     assert_eq!(i, 4);
index b15f9d34859932fb4af53a03fbe10081c3cdb274..0ca17e218d2f637751d3dd781f4f131a0c515f5d 100644 (file)
@@ -15,6 +15,6 @@ fn foo(x: &uint) -> &uint { x }
 fn bar(x: &uint) -> uint { *x }
 
 pub fn main() {
-    let p = box 3_usize;
+    let p: Box<_> = box 3_usize;
     assert_eq!(bar(foo(&*p)), 3);
 }
index faa9b37bdcc630807125881fe3046d737f42ae4b..0057a51012dd0bdaef6fdeda53b048a37e14aaf0 100644 (file)
@@ -13,7 +13,8 @@
 #![allow(dead_assignment)]
 #![allow(unused_variable)]
 #![allow(unknown_features)]
-#![feature(box_syntax)]
+
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
 
 // Should pass region checking.
 fn ok(f: Box<FnMut(&uint)>) {
@@ -23,14 +24,14 @@ fn ok(f: Box<FnMut(&uint)>) {
     // f's type should be a subtype of g's type), because f can be
     // used in any context that expects g's type.  But this currently
     // fails.
-    let mut g: Box<for<'r> FnMut(&'r uint)> = box |x| { };
+    let mut g: Box<for<'r> FnMut(&'r uint)> = Box::new(|x| { });
     g = f;
 }
 
 // This version is the same as above, except that here, g's type is
 // inferred.
 fn ok_inferred(f: Box<FnMut(&uint)>) {
-    let mut g: Box<for<'r> FnMut(&'r uint)> = box |_| {};
+    let mut g: Box<for<'r> FnMut(&'r uint)> = Box::new(|_| {});
     g = f;
 }
 
index d07110fd7217f74f5a7673d94581cb9eaea9d433..86f4f2dd18e643377501f2444adadfce20133a99 100644 (file)
@@ -14,7 +14,7 @@
 fn borrow<T>(x: &T) -> &T {x}
 
 pub fn main() {
-    let x = box 3;
+    let x: Box<_> = box 3;
     loop {
         let y = borrow(&*x);
         assert_eq!(*x, *y);
index 708d031a68a6351e9051b6e97885810a323d711a..ebbc5b70f604153934b97bcd208ee3b1413dd42f 100644 (file)
@@ -18,7 +18,7 @@ fn x_coord(p: &Point) -> &int {
 }
 
 pub fn main() {
-    let p = box Point {x: 3, y: 4};
+    let p: Box<_> = box Point {x: 3, y: 4};
     let xc = x_coord(&*p);
     assert_eq!(*xc, 3);
 }
index e779e002b299005b33c9db21b1ea21bfb0f834ef..1ad96d4bc55933e7c1d783b5e777027dda87ca0a 100644 (file)
@@ -30,7 +30,8 @@ struct Foo<'a,'tcx:'a> {
 
 impl<'a,'tcx> Foo<'a,'tcx> {
     fn bother(&mut self) -> int {
-        self.elaborate_bounds(box |this| {
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        self.elaborate_bounds(Box::new(|this| {
             // (*) Here: type of `this` is `&'f0 Foo<&'f1, '_2>`,
             // where `'f0` and `'f1` are fresh, free regions that
             // result from the bound regions on the closure, and `'2`
@@ -44,7 +45,7 @@ fn bother(&mut self) -> int {
             // `region_inference.rs` file (and the `givens` field, in
             // particular) for more details.
             this.foo()
-        })
+        }))
     }
 
     fn foo(&mut self) -> int {
index 7198c35944f9a0f5b0e764cb55108a5346375ca0..1bcde77261b930d9ada9754a9a7e290f19bb7e61 100644 (file)
@@ -25,6 +25,7 @@ fn call_static_closure(mut cl: closure_box<'static>) {
 }
 
 pub fn main() {
-    let cl_box = box_it(box || println!("Hello, world!"));
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let cl_box = box_it(Box::new(|| println!("Hello, world!")));
     call_static_closure(cl_box);
 }
index e934498ea05066b34de6bea90afdf6f8dc92a682..92582177989b6d234d5dc26eb664898ce7dcc411 100644 (file)
@@ -40,7 +40,7 @@ pub fn main() {
     let new_x = x.change();
     assert_eq!(new_x.a, 55);
 
-    let x = box new_x;
+    let x: Box<_> = box new_x;
     let new_x = x.change_again();
     assert_eq!(new_x.a, 45);
 }
index cf09737e32efd5fc45d3302f40b693ef5310a310..b71b907fcf0432b23ae33ca4bee943041ccf282f 100644 (file)
@@ -17,7 +17,7 @@
 use std::rc::Rc;
 
 pub fn main() {
-   let mut x = box 3;
+   let mut x: Box<_> = box 3;
    x = x;
    assert!(*x == 3);
 
index 523b7528103ad55026b10a4306707b69943e052d..264ee5f55b9771814b3907724d1d0209f3f85a1c 100644 (file)
@@ -20,7 +20,7 @@ fn test05_start<F:FnOnce(int)>(f: F) {
 }
 
 fn test05() {
-    let three = box 3;
+    let three: Box<_> = box 3;
     let fn_to_send = move|n:int| {
         println!("{}", *three + n); // will copy x into the closure
         assert_eq!(*three, 3);
index f496765edca9882266cb850a8fc4399d93018680..03971668182acd98ff8d1607b2f6dad8033dfa98 100644 (file)
@@ -8,12 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 #[derive(Debug)]
 struct Foo(Box<[u8]>);
 
 pub fn main() {
-    println!("{:?}", Foo(box [0, 1, 2]));
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    println!("{:?}", Foo(Box::new([0, 1, 2])));
 }
index ca2a8cf5506eec1486b46550bfa9cacae87d1061..46f9e991347e42bc601c200cf0fd39d8b8fcb9c4 100644 (file)
@@ -17,7 +17,7 @@
 pub fn main() {
     let (tx, rx) = channel::<uint>();
 
-    let x = box 1;
+    let x: Box<_> = box 1;
     let x_in_parent = &(*x) as *const int as uint;
 
     let _t = Thread::spawn(move || {
index 26772a5b22c076c140adb0244b7ff98a1e7e28d2..cf23785b844482d226a02b63ee008f5042505076 100644 (file)
@@ -104,9 +104,10 @@ fn check_legs(arc: Arc<Vec<Box<Pet+Sync+Send>>>) {
 }
 fn check_names(arc: Arc<Vec<Box<Pet+Sync+Send>>>) {
     for pet in &*arc {
-        pet.name(box |name| {
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        pet.name(Box::new(|name| {
             assert!(name.as_bytes()[0] == 'a' as u8 && name.as_bytes()[1] == 'l' as u8);
-        })
+        }))
     }
 }
 fn check_pedigree(arc: Arc<Vec<Box<Pet+Sync+Send>>>) {
index fa02dabb373b198690cd228533e818a2ead112d3..1565ccfe459d26a11b8fa25a5c6faaee5596d53b 100644 (file)
@@ -8,9 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 trait Trait<T> {
     fn f(&self, x: T);
 }
@@ -29,7 +26,8 @@ fn f(&self, x: &'static str) {
 
 pub fn main() {
     let a = Struct { x: 1, y: 2 };
-    let b: Box<Trait<&'static str>> = box a;
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let b: Box<Trait<&'static str>> = Box::new(a);
     b.f("Mary");
     let c: &Trait<&'static str> = &a;
     c.f("Joe");
index 1ae9b3f0e959bb25d1a446075a37175532af6abe..6db7113b0504cb169b1f350b984fc43fc81ba7c4 100644 (file)
@@ -33,14 +33,16 @@ fn foo(mut a: Box<Writer>) {
     a.write(b"Hello\n");
 }
 
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
 pub fn main() {
     let a = Struct { x: 1, y: 2 };
-    let b: Box<Trait> = box a;
+    let b: Box<Trait> = Box::new(a);
     b.f();
     let c: &Trait = &a;
     c.f();
 
     let out = old_io::stdout();
-    foo(box out);
+    foo(Box::new(out));
 }
 
index 5af2d4ee806d225422b1d5de0cf4b487870a6792..650688dd9088fc9d8da4f90ff55c98233e0111d8 100644 (file)
@@ -35,5 +35,5 @@ fn main() {
     assert_eq!(get_it(&1_u32), 1_u32);
     assert_eq!(get_it(&1_u16), 1_u16);
     assert_eq!(get_it(&Some(1_u16)), Some(1_u16));
-    assert_eq!(get_it(&box 1), box 1);
+    assert_eq!(get_it(&Box::new(1)), Box::new(1));
 }
index 7d1fad5d281646281ce096e2cad70b83f08a451f..432dbd72a294887c30c2f8d3ac7820077a9aac06 100644 (file)
@@ -32,13 +32,13 @@ fn r(i:int) -> r {
 pub fn main() {
     p_foo(r(10));
 
-    p_foo(box r(10));
-    p_foo(box 10);
+    p_foo::<Box<_>>(box r(10));
+    p_foo::<Box<_>>(box 10);
     p_foo(10);
 
-    s_foo(box 10);
+    s_foo::<Box<_>>(box 10);
     s_foo(10);
 
-    u_foo(box 10);
+    u_foo::<Box<_>>(box 10);
     u_foo(10);
 }
index 2be9f75dae12ca2b1d071c262373524ee7b8c655..832c1f8802d1ff9ab3a67a5d0f5d303eb481b042 100644 (file)
@@ -46,11 +46,11 @@ fn baz(self: Bar<T>, x: int) -> int {
 }
 
 fn main() {
-    let foo = box Foo {
+    let foo: Box<_> = box Foo {
         f: 1,
     };
     println!("{} {} {}", foo.foo(2), foo.bar(2), foo.baz(2));
-    let bar = box Bar {
+    let bar: Box<_> = box Bar {
         f: 1,
     };
     println!("{} {} {}", bar.foo(2), bar.bar(2), bar.baz(2));
index da647e90c00f6fdbb4b3389d2fbce7bcd0708838..52311544297ae1d52149caa20415d55f7a76ecdf 100644 (file)
 // Test that the call operator autoderefs when calling to an object type.
 
 #![allow(unknown_features)]
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 use std::ops::FnMut;
 
 fn make_adder(x: int) -> Box<FnMut(int)->int + 'static> {
-    box move |y| { x + y }
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    Box::new(move |y| { x + y })
 }
 
 pub fn main() {
index 8ee3c96f580d1edb6521039950d50b779b98321a..a34799fdcc543b8adc9a1720da70be8ccf8a326a 100644 (file)
@@ -9,13 +9,13 @@
 // except according to those terms.
 
 #![allow(unknown_features)]
-#![feature(box_syntax)]
 #![feature(unboxed_closures)]
 
 use std::ops::FnMut;
 
 fn make_adder(x: int) -> Box<FnMut(int)->int + 'static> {
-    box move |y| { x + y }
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    Box::new(move |y| { x + y })
 }
 
 pub fn main() {
index 535c4562362c0d3ba9620e768aa66a9855ba4ad3..056ae63b68488d5773ea9fb23d7a484744790367 100644 (file)
@@ -17,7 +17,8 @@
 
 fn main(){
     fn bar<'a, T:Clone+'a> (t: T) -> Box<FnMut()->T + 'a> {
-        box move || t.clone()
+        // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+        Box::new(move || t.clone())
     }
 
     let mut f = bar(42_u32);
index c8f0d5fde45efea490bee262988152a5cd764987..16a55ab550d2fcd46d501ae729bd98110af418de 100644 (file)
 #![feature(unboxed_closures)]
 
 fn main() {
-    let task: Box<Fn(int) -> int> = box |x| x;
+    // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+    let task: Box<Fn(int) -> int> = Box::new(|x| x);
     task.call((0, ));
 
-    let mut task: Box<FnMut(int) -> int> = box |x| x;
+    let mut task: Box<FnMut(int) -> int> = Box::new(|x| x);
     task(0);
 
     call(|x| x, 22);
index b7980ed9021e2f9a241b01ccf131e724e0ea54bf..d44a8cdcc24756ec1968e787bdb5270c6c9940fd 100644 (file)
@@ -27,7 +27,7 @@ fn change(mut self: Box<X>) -> Box<X> {
 }
 
 pub fn main() {
-    let x = box X { a: 32 };
+    let x: Box<_> = box X { a: 32 };
     let new_x = x.change();
     assert_eq!(new_x.a, 55);
 }
index c19063fe46483e796bb66b287b989ab3f9e1deae..78578bdb3c3a1159d8badf59cea88674fe9f5ba1 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let mut i = box 1;
+    let mut i: Box<_> = box 1;
     // Should be a copy
     let mut j;
     j = i.clone();
index 241258f089c56cdf7fb95207ea0f121b365899b2..9edd83d2c7cb96a4ed107a70cf9ccf181d4a85da 100644 (file)
@@ -13,8 +13,8 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box 1;
-    let mut j = box 2;
+    let i: Box<_> = box 1;
+    let mut j: Box<_> = box 2;
     // Should drop the previous value of j
     j = i;
     assert_eq!(*j, 1);
index c8abb0808482fb813b3de7d03be0eaab10f8ee72..64f8b998096ed6e76a8e62fdd84eca1a5ccf03d0 100644 (file)
@@ -18,6 +18,6 @@ fn f<T>(t: T) -> T {
 }
 
 pub fn main() {
-    let t = f(box 100);
+    let t = f::<Box<_>>(box 100);
     assert_eq!(t, box 100);
 }
index cbcb6afb4c88c51ac1bc901d6bf2cc9c0fdf06a6..c9cbaf27c4f2ff73d0d0edd3a32ce41da3d3f31b 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let mut i;
+    let mut i: Box<_>;
     i = box 1;
     assert_eq!(*i, 1);
 }
index aab7f4108fba659f5a2099ab3ad1058a26b04bd4..3bab3a6b79a116b0d7f8b950fe7454a1cedc8c82 100644 (file)
@@ -14,7 +14,7 @@
 struct J { j: int }
 
 pub fn main() {
-    let i = box J {
+    let i: Box<_> = box J {
         j: 100
     };
     assert_eq!(i.j, 100);
index 30c4b2d7b565cb5a8d991517a3e9e46d8665ab40..1c94447392160ce0226f5fde8364eed03241ce18 100644 (file)
@@ -12,6 +12,6 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box vec!(100);
+    let i: Box<_> = box vec!(100);
     assert_eq!((*i)[0], 100);
 }
index a2962dc00d50300f34fac08b58d7e99697f472e8..8fe86455b4525785601685136f34b1d7b838131c 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box 100;
+    let i: Box<_> = box 100;
     assert!(i == box 100);
     assert!(i < box 101);
     assert!(i <= box 100);
index e4099c94c2f1a6e93941fc059f41f9d747535d08..cb6e84ae1aa7387b052dc45a76bbb86854298ef7 100644 (file)
@@ -14,7 +14,7 @@
 pub fn main() {
     enum t { t1(int), t2(int), }
 
-    let _x = box t::t1(10);
+    let _x: Box<_> = box t::t1(10);
 
     /*alt *x {
       t1(a) {
index 975f1e9da827f42245b551a67ccd7cbf9794d7ca..7264b9fee9524d672ba809b9bc1ae003091fe114 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    box 100;
+    let _: Box<_> = box 100;
 }
 
 fn vec() {
index 3af38784add9fbf1687e371f623295f92666563c..14bb72f4412bed49871b612cb5a0605b049d0f28 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let mut i = box 1;
+    let mut i: Box<_> = box 1;
     // Should be a copy
     let mut j = i.clone();
     *i = 2;
index c9192748809af7a23b3d67c51ff3de686751b15e..803e7ba16ed4003aaeadc0f692cb8e809a81a579 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box 1;
+    let i: Box<_> = box 1;
     let j = i;
     assert_eq!(*j, 1);
 }
index 96dd9f51fbe8fb4c0d11b5c1efcc1ef80fe971bd..360adaa638f96fcbcd9c5bec045948da8dfda016 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box 100;
+    let i: Box<_> = box 100;
     let j = i;
     assert_eq!(*j, 100);
 }
index 41d3b87a003c0e8bf7b0d30289cb2c8bc02b3124..1c1228f924145090952bc7958017b50612cc777d 100644 (file)
@@ -12,6 +12,6 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box 100;
+    let i: Box<_> = box 100;
     assert_eq!(*i, 100);
 }
index c5a0a4df2751da32803a7bdd0f36a2e408c1c334..745a55e06510facf894e3764eb21c3ed045bb6fb 100644 (file)
@@ -12,5 +12,5 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let _x = box vec!(0,0,0,0,0);
+    let _x: Box<_> = box vec!(0,0,0,0,0);
 }
index 3bde79fdce01be2c897aeec55285969293aff81d..20bf4bef1714dae413a5f886f154cab440456fe8 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let mut a = vec!(box 10);
+    let mut a: Vec<Box<_>> = vec!(box 10);
     let b = a.clone();
 
     assert_eq!(*a[0], 10);
index 05b0c7244deece4475096a0f13767794319f48d8..c24ec8fe44a3c396c9c2ad99128d0b098b949fa2 100644 (file)
@@ -12,6 +12,6 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let vect = vec!(box 100);
+    let vect : Vec<Box<_>> = vec!(box 100);
     assert!(vect[0] == box 100);
 }
index d3f13f1609f7551b936d7b8cef1060b679143060..44e8703aaf2febcf6f662c84c43a7721b4c2ee05 100644 (file)
@@ -12,5 +12,5 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let _i = box 100;
+    let _i: Box<_> = box 100;
 }
index 4c93c379b488a0d428540eb627ffce80f5d9797f..6bb1fdcf5627a5b72a20644832bff3bc7171a848 100644 (file)
@@ -23,11 +23,11 @@ fn g<T:Send + PartialEq>(i: T, j: T) {
         assert!(i != j);
     }
 
-    let i = box 100;
-    let j = box 100;
+    let i: Box<_> = box 100;
+    let j: Box<_> = box 100;
     f(i, j);
-    let i = box 100;
-    let j = box 101;
+    let i: Box<_> = box 100;
+    let j: Box<_> = box 101;
     g(i, j);
 }
 
@@ -41,11 +41,11 @@ fn g<T:PartialEq>(i: T, j: T) {
         assert!(i != j);
     }
 
-    let i = box 100;
-    let j = box 100;
+    let i: Box<_> = box 100;
+    let j: Box<_> = box 100;
     f(i, j);
-    let i = box 100;
-    let j = box 101;
+    let i: Box<_> = box 100;
+    let j: Box<_> = box 101;
     g(i, j);
 }
 
@@ -59,11 +59,11 @@ fn g<T:PartialEq>(i: T, j: T) {
         assert!(i != j);
     }
 
-    let i = box 100;
-    let j = box 100;
+    let i: Box<_> = box 100;
+    let j: Box<_> = box 100;
     f(i, j);
-    let i = box 100;
-    let j = box 101;
+    let i: Box<_> = box 100;
+    let j: Box<_> = box 101;
     g(i, j);
 }
 
index 4b21b949f8836bd0b4d3883456013cea4862b605..148ca4757ae927eccb8f1c5cb89e20f19a27c52f 100644 (file)
@@ -12,6 +12,6 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box 100;
+    let i: Box<_> = box 100;
     println!("{}", i);
 }
index a1502c2eb8c0fa3ffda2425bf0e3984a7510fdf2..93614e86c7303fb0cebe3aa5ddf3352126599a97 100644 (file)
 
 // Issue #961
 
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
 fn altsimple() {
-    match box true {
+    match Box::new(true) {
       _ => { }
     }
 }
index 705b9d6e92c53193212bed767210aebaaa97f089..126cc646833a14b83bb938680b83ee1341096da3 100644 (file)
@@ -13,8 +13,8 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box 100;
-    let j = box 200;
+    let i: Box<_> = box 100;
+    let j: Box<_> = box 200;
     let j = i;
     assert_eq!(*j, 100);
 }
index b6c24f5be289a7a6e4b4f1c8532af04a1369eadb..9ac5e86f87b54af426e54b9182a065020a2e9d13 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let mut i;
+    let mut i: Box<_>;
     i = box 100;
     assert_eq!(*i, 100);
 }
index ed13bf6a5c4f931378ba65f57ad14dd47bbea572..a54b343f2fa3d21862d88f6b412bdc9ea358fe6d 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let i = box 100;
+    let i: Box<_> = box 100;
     let mut j;
     j = i;
     assert_eq!(*j, 100);
index 403b8bf18b823f31d357995039bf33318ad3ec23..ca01c07ab80431e73f6dabfe2866e71a16eab114 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let mut i = box 0;
+    let mut i: Box<_> = box 0;
     *i = 1;
     assert_eq!(*i, 1);
 }
index 756911d29fc8c3b3da3390898922bb17442186a6..c20604406b94c823769c184dbb1287848f003279 100644 (file)
@@ -14,7 +14,7 @@
 struct X { x: int }
 
 pub fn main() {
-    let x = box X {x: 1};
+    let x: Box<_> = box X {x: 1};
     let bar = x;
     assert_eq!(bar.x, 1);
 }
index 2a462e9cdd83ca72b35e99835e14e29e19b09eb2..72022afe5fd99a489415f631fd9a1ea35e3ac0ce 100644 (file)
@@ -14,7 +14,7 @@
 use std::sync::mpsc::channel;
 
 pub fn main() {
-    let (tx, rx) = channel();
+    let (tx, rx) = channel::<Box<_>>();
     tx.send(box 100).unwrap();
     let v = rx.recv().unwrap();
     assert_eq!(v, box 100);
index 2adb9c22f60c1563aebde48ccd08c6e3ac9b3640..1315e443816228c61613df4cf6a0eace2977d742 100644 (file)
@@ -14,8 +14,8 @@
 use std::mem::swap;
 
 pub fn main() {
-    let mut i = box 100;
-    let mut j = box 200;
+    let mut i: Box<_> = box 100;
+    let mut j: Box<_> = box 200;
     swap(&mut i, &mut j);
     assert_eq!(i, box 200);
     assert_eq!(j, box 100);
index 983152cd056d9ba7747bc856f5fed89c8323f275..c9a9d6ad1474ee6e86e8863685296aad740cdf53 100644 (file)
@@ -66,7 +66,7 @@ struct Foo_<T> {
             f: [T; 3]
         }
 
-        let data = box Foo_{f: [1i32, 2, 3] };
+        let data: Box<_> = box Foo_{f: [1i32, 2, 3] };
         let x: &Foo<i32> = mem::transmute(raw::Slice { len: 3, data: &*data });
         assert!(x.f.len() == 3);
         assert!(x.f[0] == 1);
@@ -78,7 +78,8 @@ struct Baz_ {
             f2: [u8; 5],
         }
 
-        let data = box Baz_{ f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] };
+        let data: Box<_> = box Baz_ {
+            f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] };
         let x: &Baz = mem::transmute( raw::Slice { len: 5, data: &*data } );
         assert!(x.f1 == 42);
         let chs: Vec<char> = x.f2.chars().collect();
@@ -96,7 +97,7 @@ struct Qux_ {
         let obj: Box<St> = box St { f: 42 };
         let obj: &Tr = &*obj;
         let obj: raw::TraitObject = mem::transmute(&*obj);
-        let data = box Qux_{ f: St { f: 234 } };
+        let data: Box<_> = box Qux_{ f: St { f: 234 } };
         let x: &Qux = mem::transmute(raw::TraitObject { vtable: obj.vtable,
                                                         data: mem::transmute(&*data) });
         assert!(x.f.foo() == 234);
index 4e8fdda95631185c9fc4541c41e4af2b947c3491..9f20426aa218ecbb1ddb4e62558d6201a87e0198 100644 (file)
@@ -12,7 +12,7 @@
 #![feature(box_syntax)]
 
 pub fn main() {
-    let _x = box 1;
+    let _x: Box<_> = box 1;
     let lam_move = || {};
     lam_move();
 }
index d053b03a2ca8a298da6942129e7ce943cfbbd2fc..57534feec31214ac1377fae6bc1ad209cd19bd35 100644 (file)
@@ -18,6 +18,6 @@
 
 pub fn main()
 {
-    let y = box 1;
+    let y: Box<_> = box 1;
     y;
 }
index 4d90f71c830ba6db56bf83758047fb6119f50d78..b7229a00480cb0c112e73b150090b3197fed1eec 100644 (file)
@@ -14,7 +14,7 @@
 use std::thread;
 
 fn f() {
-    let _a = box 0;
+    let _a: Box<_> = box 0;
     panic!();
 }