diff --git a/AUTHORS.txt b/AUTHORS.txt index 628fa4c86da00..92903a26093f9 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -161,4 +161,4 @@ Wade Mealing William Ting Yasuhiro Fujii Youngsoo Son -Zack Corr +Zack Corr diff --git a/Makefile.in b/Makefile.in index e476ac1dba2d1..cf6fcd42021ed 100644 --- a/Makefile.in +++ b/Makefile.in @@ -131,7 +131,7 @@ CFG_STDLIB :=$(call CFG_LIB_NAME,std) CFG_LIBRUSTC :=$(call CFG_LIB_NAME,rustc) CFG_LIBSYNTAX :=$(call CFG_LIB_NAME,syntax) CFG_LIBFUZZER :=$(call CFG_LIB_NAME,fuzzer) -CFG_LIBCARGO :=$(call CFG_LIB_NAME,cargo) +CFG_LIBRUSTPKG :=$(call CFG_LIB_NAME,rustpkg) CFG_LIBRUSTDOC :=$(call CFG_LIB_NAME,rustdoc) CFG_LIBRUSTI :=$(call CFG_LIB_NAME,rusti) @@ -140,7 +140,7 @@ CORELIB_GLOB :=$(call CFG_LIB_GLOB,core) LIBRUSTC_GLOB :=$(call CFG_LIB_GLOB,rustc) LIBSYNTAX_GLOB :=$(call CFG_LIB_GLOB,syntax) LIBFUZZER_GLOB :=$(call CFG_LIB_GLOB,fuzzer) -LIBCARGO_GLOB :=$(call CFG_LIB_GLOB,cargo) +LIBRUSTPKG_GLOB :=$(call CFG_LIB_GLOB,rustpkg) LIBRUSTDOC_GLOB :=$(call CFG_LIB_GLOB,rustdoc) LIBRUSTI_GLOB :=$(call CFG_LIB_GLOB,rusti) STDLIB_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,std) @@ -148,7 +148,7 @@ CORELIB_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,core) LIBRUSTC_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,rustc) LIBSYNTAX_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,syntax) LIBFUZZER_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,fuzzer) -LIBCARGO_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,cargo) +LIBRUSTPKG_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,rustpkg) LIBRUSTDOC_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,rustdoc) LIBRUSTI_DSYM_GLOB :=$(call CFG_LIB_DSYM_GLOB,rusti) @@ -371,11 +371,11 @@ SREQ$(1)_T_$(2)_H_$(3) = \ CSREQ$(1)_T_$(2)_H_$(3) = \ $$(TSREQ$(1)_T_$(2)_H_$(3)) \ $$(HBIN$(1)_H_$(3))/fuzzer$$(X) \ - $$(HBIN$(1)_H_$(3))/cargo$$(X) \ + $$(HBIN$(1)_H_$(3))/rustpkg$$(X) \ $$(HBIN$(1)_H_$(3))/rustdoc$$(X) \ $$(HBIN$(1)_H_$(3))/rusti$$(X) \ $$(HLIB$(1)_H_$(3))/$$(CFG_LIBFUZZER) \ - $$(HLIB$(1)_H_$(3))/$$(CFG_LIBCARGO) \ + $$(HLIB$(1)_H_$(3))/$$(CFG_LIBRUSTPKG) \ $$(HLIB$(1)_H_$(3))/$$(CFG_LIBRUSTDOC) \ $$(HLIB$(1)_H_$(3))/$$(CFG_LIBRUSTI) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_CORELIB) \ @@ -383,7 +383,7 @@ CSREQ$(1)_T_$(2)_H_$(3) = \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBSYNTAX) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBRUSTC) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBFUZZER) \ - $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBCARGO) \ + $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBRUSTPKG) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBRUSTDOC) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBRUSTI) diff --git a/README.md b/README.md index 27b63c1080bd4..a34f8814f020d 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ for more information on them. When complete, `make install` will place several programs into `/usr/local/bin`: `rustc`, the Rust compiler; `rustdoc`, the -API-documentation tool, and `cargo`, the Rust package manager. +API-documentation tool, and `rustpkg`, the Rust package manager and build system. [wiki-start]: https://github.com/mozilla/rust/wiki/Note-getting-started-developing-Rust [tarball]: http://static.rust-lang.org/dist/rust-0.5.tar.gz diff --git a/doc/rust.md b/doc/rust.md index 30896307aeebf..06840fd0215a9 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -213,7 +213,7 @@ else enum extern false fn for if impl let log loop -match mod move mut +match mod mut priv pub pure ref return self static struct super @@ -686,15 +686,15 @@ mod math { type complex = (f64, f64); fn sin(f: f64) -> f64 { ... -# die!(); +# fail!(); } fn cos(f: f64) -> f64 { ... -# die!(); +# fail!(); } fn tan(f: f64) -> f64 { ... -# die!(); +# fail!(); } } ~~~~~~~~ @@ -986,7 +986,7 @@ output slot type would normally be. For example: ~~~~ fn my_err(s: &str) -> ! { log(info, s); - die!(); + fail!(); } ~~~~ @@ -1004,7 +1004,7 @@ were declared without the `!` annotation, the following code would not typecheck: ~~~~ -# fn my_err(s: &str) -> ! { die!() } +# fn my_err(s: &str) -> ! { fail!() } fn f(i: int) -> int { if i == 42 { @@ -1117,6 +1117,7 @@ a = Cat{ name: ~"Spotty", weight: 2.7 }; In this example, `Cat` is a _struct-like enum variant_, whereas `Dog` is simply called an enum variant. + ### Constants ~~~~~~~~ {.ebnf .gram} @@ -2284,9 +2285,9 @@ enum List { Nil, Cons(X, @List) } let x: List = Cons(10, @Cons(11, @Nil)); match x { - Cons(_, @Nil) => die!(~"singleton list"), + Cons(_, @Nil) => fail!(~"singleton list"), Cons(*) => return, - Nil => die!(~"empty list") + Nil => fail!(~"empty list") } ~~~~ @@ -2323,7 +2324,7 @@ match x { return; } _ => { - die!(); + fail!(); } } ~~~~ @@ -2411,7 +2412,7 @@ guard may refer to the variables bound within the pattern they follow. let message = match maybe_digit { Some(x) if x < 10 => process_digit(x), Some(x) => process_other(x), - None => die!() + None => fail!() }; ~~~~ diff --git a/doc/tutorial-borrowed-ptr.md b/doc/tutorial-borrowed-ptr.md index 939051ca6058d..c13b2528598c1 100644 --- a/doc/tutorial-borrowed-ptr.md +++ b/doc/tutorial-borrowed-ptr.md @@ -431,7 +431,7 @@ fn example5c(x: @S) -> int { let y = &v.g; ... } - x.f = move v; // Replace x.f + x.f = v; // Replace x.f ... # return 0; } diff --git a/doc/tutorial-macros.md b/doc/tutorial-macros.md index e2813e0809fc7..42bd319a2a4bd 100644 --- a/doc/tutorial-macros.md +++ b/doc/tutorial-macros.md @@ -218,7 +218,7 @@ match x { // complicated stuff goes here return result + val; }, - _ => die!(~"Didn't get good_2") + _ => fail!(~"Didn't get good_2") } } _ => return 0 // default value @@ -260,7 +260,7 @@ macro_rules! biased_match ( biased_match!((x) ~ (good_1(g1, val)) else { return 0 }; binds g1, val ) biased_match!((g1.body) ~ (good_2(result) ) - else { die!(~"Didn't get good_2") }; + else { fail!(~"Didn't get good_2") }; binds result ) // complicated stuff goes here return result + val; @@ -362,7 +362,7 @@ macro_rules! biased_match ( # fn f(x: t1) -> uint { biased_match!( (x) ~ (good_1(g1, val)) else { return 0 }; - (g1.body) ~ (good_2(result) ) else { die!(~"Didn't get good_2") }; + (g1.body) ~ (good_2(result) ) else { fail!(~"Didn't get good_2") }; binds val, result ) // complicated stuff goes here return result + val; diff --git a/doc/tutorial-tasks.md b/doc/tutorial-tasks.md index f814970375a7d..a3d0ecaa4ba65 100644 --- a/doc/tutorial-tasks.md +++ b/doc/tutorial-tasks.md @@ -161,7 +161,7 @@ use pipes::{stream, Port, Chan}; let (port, chan): (Port, Chan) = stream(); -do spawn |move chan| { +do spawn || { let result = some_expensive_computation(); chan.send(result); } @@ -192,7 +192,7 @@ spawns the child task. # use pipes::{stream, Port, Chan}; # fn some_expensive_computation() -> int { 42 } # let (port, chan) = stream(); -do spawn |move chan| { +do spawn || { let result = some_expensive_computation(); chan.send(result); } @@ -229,7 +229,7 @@ following program is ill-typed: # fn some_expensive_computation() -> int { 42 } let (port, chan) = stream(); -do spawn |move chan| { +do spawn { chan.send(some_expensive_computation()); } @@ -248,12 +248,12 @@ Instead we can use a `SharedChan`, a type that allows a single use pipes::{stream, SharedChan}; let (port, chan) = stream(); -let chan = SharedChan(move chan); +let chan = SharedChan(chan); for uint::range(0, 3) |init_val| { // Create a new channel handle to distribute to the child task let child_chan = chan.clone(); - do spawn |move child_chan| { + do spawn { child_chan.send(some_expensive_computation(init_val)); } } @@ -283,10 +283,10 @@ might look like the example below. // Create a vector of ports, one for each child task let ports = do vec::from_fn(3) |init_val| { let (port, chan) = stream(); - do spawn |move chan| { + do spawn { chan.send(some_expensive_computation(init_val)); } - move port + port }; // Wait on each port, accumulating the results @@ -313,7 +313,7 @@ of all tasks are intertwined: if one fails, so do all the others. # fn do_some_work() { loop { task::yield() } } # do task::try { // Create a child task that fails -do spawn { die!() } +do spawn { fail!() } // This will also fail because the task we spawned failed do_some_work(); @@ -337,7 +337,7 @@ let result: Result = do task::try { if some_condition() { calculate_result() } else { - die!(~"oops!"); + fail!(~"oops!"); } }; assert result.is_err(); @@ -370,14 +370,14 @@ proceed). Hence, you will need different _linked failure modes_. ## Failure modes By default, task failure is _bidirectionally linked_, which means that if -either task dies, it kills the other one. +either task fails, it kills the other one. ~~~ # fn sleep_forever() { loop { task::yield() } } # do task::try { do task::spawn { do task::spawn { - die!(); // All three tasks will die. + fail!(); // All three tasks will fail. } sleep_forever(); // Will get woken up by force, then fail } @@ -386,7 +386,7 @@ sleep_forever(); // Will get woken up by force, then fail ~~~ If you want parent tasks to be able to kill their children, but do not want a -parent to die automatically if one of its child task dies, you can call +parent to fail automatically if one of its child task fails, you can call `task::spawn_supervised` for _unidirectionally linked_ failure. The function `task::try`, which we saw previously, uses `spawn_supervised` internally, with additional logic to wait for the child task to finish @@ -398,13 +398,13 @@ before returning. Hence: # fn sleep_forever() { loop { task::yield() } } # do task::try { let (receiver, sender): (Port, Chan) = stream(); -do spawn |move receiver| { // Bidirectionally linked +do spawn { // Bidirectionally linked // Wait for the supervised child task to exist. let message = receiver.recv(); // Kill both it and the parent task. assert message != 42; } -do try |move sender| { // Unidirectionally linked +do try { // Unidirectionally linked sender.send(42); sleep_forever(); // Will get woken up by force } @@ -432,7 +432,7 @@ do task::spawn_supervised { // Intermediate task immediately exits } wait_for_a_while(); -die!(); // Will kill grandchild even if child has already exited +fail!(); // Will kill grandchild even if child has already exited # }; ~~~ @@ -446,10 +446,10 @@ other at all, using `task::spawn_unlinked` for _isolated failure_. let (time1, time2) = (random(), random()); do task::spawn_unlinked { sleep_for(time2); // Won't get forced awake - die!(); + fail!(); } sleep_for(time1); // Won't get forced awake -die!(); +fail!(); // It will take MAX(time1,time2) for the program to finish. # }; ~~~ @@ -505,7 +505,7 @@ Here is the code for the parent task: let (from_child, to_child) = DuplexStream(); -do spawn |move to_child| { +do spawn { stringifier(&to_child); }; diff --git a/doc/tutorial.md b/doc/tutorial.md index a825b7f535f72..9550dd927fac3 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1260,7 +1260,7 @@ Moving it into a mutable slot makes the elements assignable. let crayons: ~[Crayon] = ~[BananaMania, Beaver, Bittersweet]; // Put the vector into a mutable slot -let mut mutable_crayons = move crayons; +let mut mutable_crayons = crayons; // Now it's mutable to the bone mutable_crayons[0] = Apricot; diff --git a/man/rustc.1 b/man/rustc.1 index bb6457dd493e7..14d2cad86d017 100644 --- a/man/rustc.1 +++ b/man/rustc.1 @@ -1,9 +1,9 @@ -.TH RUSTC "1" "October 2012" "rustc 0.4" "User Commands" +.TH RUSTC "1" "February 2013" "rustc 0.6" "User Commands" .SH NAME rustc \- rust compiler .SH SYNOPSIS .B rustc -[\fIoptions\fR] \fI\fR +[\fIOPTIONS\fR] \fIINPUT\fR .SH DESCRIPTION This program is a compiler for the Rust language, available at @@ -18,88 +18,134 @@ Compile an executable crate (default) \fB\-c\fR Compile and assemble, but do not link .TP -\fB\-\-cfg\fR +\fB\-\-cfg\fR SPEC Configure the compilation environment .TP \fB\-\-emit\-llvm\fR Produce an LLVM bitcode file .TP -\fB\-g\fR -Produce debug info (experimental) -.TP -\fB\-\-gc\fR -Garbage collect shared data (experimental/temporary) -.TP -\fB\-h\fR \fB\-\-help\fR +\fB\-h\fR, \fB\-\-help\fR Display this message .TP -\fB\-L\fR +\fB\-L\fR PATH Add a directory to the library search path .TP \fB\-\-lib\fR Compile a library crate .TP \fB\-\-ls\fR -List the symbols defined by a compiled library crate -.TP -\fB\-\-jit\fR -Execute using JIT (experimental) +List the symbols defined by a library crate .TP \fB\-\-no\-trans\fR Run all passes except translation; no output .TP \fB\-O\fR -Equivalent to \fB\-\-opt\-level\fR=\fI2\fR +Equivalent to \fI\-\-opt\-level=2\fR .TP -\fB\-o\fR +\fB\-o\fR FILENAME Write output to .TP -\fB\-\-opt\-level\fR -Optimize with possible levels 0\-3 +\fB\-\-opt\-level\fR LEVEL +Optimize with possible levels 0-3 .TP -\fB\-\-out\-dir\fR -Write output to compiler\-chosen filename in +\fB\-\-out\-dir\fR DIR +Write output to compiler-chosen filename in .TP \fB\-\-parse\-only\fR Parse only; do not compile, assemble, or link .TP -\fB\-\-pretty\fR [type] -Pretty\-print the input instead of compiling; -valid types are: normal (un\-annotated source), -expanded (crates expanded), typed (crates expanded, -with type annotations), or identified (fully -parenthesized, AST nodes and blocks with IDs) +\fB\-\-pretty\fR [TYPE] +Pretty-print the input instead of compiling; valid types are: normal +(un-annotated source), expanded (crates expanded), typed (crates +expanded, with type annotations), or identified (fully parenthesized, +AST nodes and blocks with IDs) .TP \fB\-S\fR Compile only; do not assemble or link .TP \fB\-\-save\-temps\fR -Write intermediate files (.bc, .opt.bc, .o) -in addition to normal output +Write intermediate files (.bc, .opt.bc, .o) in addition to normal output .TP -\fB\-\-static\fR -Use or produce static libraries or binaries -(experimental) -.TP -\fB\-\-sysroot\fR +\fB\-\-sysroot\fR PATH Override the system root .TP \fB\-\-test\fR Build a test harness .TP -\fB\-\-target\fR -Target cpu\-manufacturer\-kernel[\-os] to compile for -(default: host triple) -(see http://sources.redhat.com/autobook/autobook/ -autobook_17.html for detail) +\fB\-\-target\fR TRIPLE +Target triple cpu-manufacturer-kernel[-os] to compile for (see +http://sources.redhat.com/autobook/autobook/autobook_17.html +for detail) .TP -\fB\-W help\fR +\fB\-W\fR help Print 'lint' options and default settings .TP -\fB\-Z help\fR -Print internal options for debugging rustc +\fB\-W\fR OPT, \fB\-\-warn\fR OPT +Set lint warnings +.TP +\fB\-A\fR OPT, \fB\-\-allow\fR OPT +Set lint allowed .TP -\fB\-v\fR \fB\-\-version\fR +\fB\-D\fR OPT, \fB\-\-deny\fR OPT +Set lint denied +.TP +\fB\-F\fR OPT, \fB\-\-forbid\fR OPT +Set lint forbidden +.TP +\fB\-Z\fR FLAG +Set internal debugging options. Use "-Z help" to print available options. + +Available debug flags are: +.RS +.IP \[bu] +\fBverbose\fR - in general, enable more debug printouts +.IP \[bu] +\fBtime\-passes\fR - measure time of each rustc pass +.IP \[bu] +\fBcount\-llvm\-insns\fR - count where LLVM instrs originate +.IP \[bu] +\fBtime\-llvm\-passes\fR - measure time of each LLVM pass +.IP \[bu] +\fBtrans\-stats\fR - gather trans statistics +.IP \[bu] +\fBno\-asm\-comments\fR - omit comments when using \fI\-S\fR +.IP \[bu] +\fBno\-verify\fR - skip LLVM verification +.IP \[bu] +\fBtrace\fR - emit trace logs +.IP \[bu] +\fBcoherence\fR - perform coherence checking +.IP \[bu] +\fBborrowck\-stats\fR - gather borrowck statistics +.IP \[bu] +\fBborrowck\-note\-pure\fR - note where purity is req'd +.IP \[bu] +\fBborrowck\-note\-loan\fR - note where loans are req'd +.IP \[bu] +\fBno\-landing\-pads\fR - omit landing pads for unwinding +.IP \[bu] +\fBdebug\-llvm\fR - enable debug output from LLVM +.IP \[bu] +\fBcount\-type\-sizes\fR - count the sizes of aggregate types +.IP \[bu] +\fBmeta\-stats\fR - gather metadata statistics +.IP \[bu] +\fBno\-opt\fR - do not optimize, even if \fI\-O\fR is passed +.IP \[bu] +\fBno\-monomorphic\-collapse\fR - do not collapse template instantiations +.IP \[bu] +\fBgc\fR - Garbage collect shared data (experimental) +.IP \[bu] +\fBjit\fR - Execute using JIT (experimental) +.IP \[bu] +\fBextra\-debug\-info\fR - Extra debugging info (experimental) +.IP \[bu] +\fBdebug\-info\fR - Produce debug info (experimental) +.IP \[bu] +\fBstatic\fR - Use or produce static libraries or binaries (experimental) +.RE +.TP +\fB\-v\fR, \fB\-\-version\fR Print version info and exit .SH "EXAMPLES" @@ -112,6 +158,10 @@ To build a library from a source file: To build either with a crate (.rc) file: $ rustc hello.rc +To build an executable with debug info (experimental): + $ rustc -Z debug-info -o hello hello.rs + + .SH "BUGS" See <\fBhttps://github.com/mozilla/rust/issues\fR> for issues. diff --git a/mk/clean.mk b/mk/clean.mk index 57c14b0afc8a2..3b35071c818e9 100644 --- a/mk/clean.mk +++ b/mk/clean.mk @@ -64,12 +64,12 @@ define CLEAN_HOST_STAGE_N clean$(1)_H_$(2): $(Q)rm -f $$(HBIN$(1)_H_$(2))/rustc$(X) $(Q)rm -f $$(HBIN$(1)_H_$(2))/fuzzer$(X) - $(Q)rm -f $$(HBIN$(1)_H_$(2))/cargo$(X) + $(Q)rm -f $$(HBIN$(1)_H_$(2))/rustpkg$(X) $(Q)rm -f $$(HBIN$(1)_H_$(2))/serializer$(X) $(Q)rm -f $$(HBIN$(1)_H_$(2))/rustdoc$(X) $(Q)rm -f $$(HBIN$(1)_H_$(2))/rusti$(X) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBFUZZER) - $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBCARGO) + $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBRUSTPKG) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBRUSTDOC) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_RUNTIME) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_CORELIB) @@ -82,7 +82,7 @@ clean$(1)_H_$(2): $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBRUSTC_GLOB) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBSYNTAX_GLOB) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBFUZZER_GLOB) - $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBCARGO_GLOB) + $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBRUSTPKG_GLOB) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBRUSTDOC_GLOB) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBRUSTI_GLOB) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_RUSTLLVM) @@ -99,11 +99,11 @@ define CLEAN_TARGET_STAGE_N clean$(1)_T_$(2)_H_$(3): $(Q)rm -f $$(TBIN$(1)_T_$(2)_H_$(3))/rustc$(X) $(Q)rm -f $$(TBIN$(1)_T_$(2)_H_$(3))/fuzzer$(X) - $(Q)rm -f $$(TBIN$(1)_T_$(2)_H_$(3))/cargo$(X) + $(Q)rm -f $$(TBIN$(1)_T_$(2)_H_$(3))/rustpkg$(X) $(Q)rm -f $$(TBIN$(1)_T_$(2)_H_$(3))/serializer$(X) $(Q)rm -f $$(TBIN$(1)_T_$(2)_H_$(3))/rustdoc$(X) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBFUZZER) - $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBCARGO) + $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBRUSTPKG) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBRUSTDOC) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_RUNTIME) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_CORELIB) @@ -115,7 +115,7 @@ clean$(1)_T_$(2)_H_$(3): $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBRUSTC_GLOB) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBSYNTAX_GLOB) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBFUZZER_GLOB) - $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBCARGO_GLOB) + $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBRUSTPKG_GLOB) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBRUSTDOC_GLOB) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_RUSTLLVM) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/libstd.rlib diff --git a/mk/dist.mk b/mk/dist.mk index dd9b201170781..5b6740461e6e5 100644 --- a/mk/dist.mk +++ b/mk/dist.mk @@ -25,7 +25,7 @@ PKG_FILES := \ $(addprefix $(S)src/, \ README.txt \ driver \ - libcargo \ + librustpkg \ librusti \ librustc \ compiletest \ diff --git a/mk/install.mk b/mk/install.mk index 555b28e96976b..7f3ec816e0206 100644 --- a/mk/install.mk +++ b/mk/install.mk @@ -55,7 +55,7 @@ install-target-$(1)-host-$(2): $$(CSREQ$$(ISTAGE)_T_$(1)_H_$(2)) $$(Q)$$(call INSTALL_LIB, \ $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(LIBSYNTAX_GLOB)) $$(Q)$$(call INSTALL_LIB, \ - $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(LIBCARGO_GLOB)) + $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(LIBRUSTPKG_GLOB)) $$(Q)$$(call INSTALL_LIB, \ $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(LIBRUSTDOC_GLOB)) $$(Q)$$(call INSTALL_LIB, \ @@ -87,11 +87,11 @@ install-host: $(CSREQ$(ISTAGE)_T_$(CFG_HOST_TRIPLE)_H_$(CFG_HOST_TRIPLE)) $(Q)mkdir -p $(PREFIX_LIB) $(Q)mkdir -p $(PREFIX_ROOT)/share/man/man1 $(Q)$(call INSTALL,$(HB2),$(PHB),rustc$(X)) - $(Q)$(call INSTALL,$(HB2),$(PHB),cargo$(X)) + $(Q)$(call INSTALL,$(HB2),$(PHB),rustpkg$(X)) $(Q)$(call INSTALL,$(HB2),$(PHB),rustdoc$(X)) $(Q)$(call INSTALL,$(HB2),$(PHB),rusti$(X)) $(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_LIBRUSTC)) - $(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_LIBCARGO)) + $(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_LIBRUSTPKG)) $(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_LIBRUSTDOC)) $(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_LIBRUSTI)) $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(CORELIB_GLOB)) @@ -112,11 +112,11 @@ HOST_LIB_FROM_HL_GLOB = \ uninstall: $(Q)rm -f $(PHB)/rustc$(X) - $(Q)rm -f $(PHB)/cargo$(X) + $(Q)rm -f $(PHB)/rustpkg$(X) $(Q)rm -f $(PHB)/rusti$(X) $(Q)rm -f $(PHB)/rustdoc$(X) $(Q)rm -f $(PHL)/$(CFG_RUSTLLVM) - $(Q)rm -f $(PHL)/$(CFG_LIBCARGO) + $(Q)rm -f $(PHL)/$(CFG_LIBRUSTPKG) $(Q)rm -f $(PHL)/$(CFG_LIBRUSTC) $(Q)rm -f $(PHL)/$(CFG_LIBRUSTDOC) $(Q)rm -f $(PHL)/$(CFG_LIBRUSTI) @@ -126,7 +126,7 @@ uninstall: $(call HOST_LIB_FROM_HL_GLOB,$(STDLIB_GLOB)) \ $(call HOST_LIB_FROM_HL_GLOB,$(LIBRUSTC_GLOB)) \ $(call HOST_LIB_FROM_HL_GLOB,$(LIBSYNTAX_GLOB)) \ - $(call HOST_LIB_FROM_HL_GLOB,$(LIBCARGO_GLOB)) \ + $(call HOST_LIB_FROM_HL_GLOB,$(LIBRUSTPKG_GLOB)) \ $(call HOST_LIB_FROM_HL_GLOB,$(LIBRUSTDOC_GLOB)) \ $(call HOST_LIB_FROM_HL_GLOB,$(LIBRUSTI_GLOB)) \ ; \ diff --git a/mk/pp.mk b/mk/pp.mk index 4d8baa2ea32c2..772365b105819 100644 --- a/mk/pp.mk +++ b/mk/pp.mk @@ -18,7 +18,7 @@ else $(wildcard $(S)src/test/*/*.rs \ $(S)src/test/*/*/*.rs) \ $(wildcard $(S)src/fuzzer/*.rs) \ - $(wildcard $(S)src/cargo/*.rs) \ + $(wildcard $(S)src/rustpkg/*.rs) \ $(wildcard $(S)src/rusti/*.rs) PP_INPUTS_FILTERED = $(shell echo $(PP_INPUTS) | xargs grep -L \ diff --git a/mk/rt.mk b/mk/rt.mk index 23dc64dbca52e..e6e0f1e0cd759 100644 --- a/mk/rt.mk +++ b/mk/rt.mk @@ -50,6 +50,7 @@ RUNTIME_CXXS_$(1) := \ rt/rust_builtin.cpp \ rt/rust_run_program.cpp \ rt/rust_env.cpp \ + rt/rust_rng.cpp \ rt/rust_sched_loop.cpp \ rt/rust_sched_launcher.cpp \ rt/rust_sched_driver.cpp \ diff --git a/mk/tests.mk b/mk/tests.mk index abe9ba60ecda4..8bcf5d5ad10ca 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -14,7 +14,7 @@ ###################################################################### # The names of crates that must be tested -TEST_CRATES = core std syntax rustc rustdoc rusti cargo +TEST_CRATES = core std syntax rustc rustdoc rusti rustpkg # Markdown files under doc/ that should have their code extracted and run DOC_TEST_NAMES = tutorial tutorial-ffi tutorial-macros tutorial-borrowed-ptr tutorial-tasks rust @@ -229,8 +229,8 @@ $(3)/test/rustctest.stage$(1)-$(2)$$(X): \ @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(2)_H_$(3)) -o $$@ $$< --test -$(3)/test/cargotest.stage$(1)-$(2)$$(X): \ - $$(CARGO_LIB) $$(CARGO_INPUTS) \ +$(3)/test/rustpkgtest.stage$(1)-$(2)$$(X): \ + $$(RUSTPKG_LIB) $$(RUSTPKG_INPUTS) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBRUSTC) @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(2)_H_$(3)) -o $$@ $$< --test diff --git a/mk/tools.mk b/mk/tools.mk index 31956eda24686..1554d760a49cc 100644 --- a/mk/tools.mk +++ b/mk/tools.mk @@ -14,13 +14,13 @@ FUZZER_LIB := $(S)src/libfuzzer/fuzzer.rc FUZZER_INPUTS := $(wildcard $(addprefix $(S)src/libfuzzer/, *.rs)) -# The test runner that runs the cfail/rfail/rpass and bench tests +# The test runner that runs the cfail/rfail/rpass and bxench tests COMPILETEST_CRATE := $(S)src/compiletest/compiletest.rc COMPILETEST_INPUTS := $(wildcard $(S)src/compiletest/*rs) -# Cargo, the package manager -CARGO_LIB := $(S)src/libcargo/cargo.rc -CARGO_INPUTS := $(wildcard $(S)src/libcargo/*rs) +# Rustpkg, the package manager and build system +RUSTPKG_LIB := $(S)src/librustpkg/rustpkg.rc +RUSTPKG_INPUTS := $(wildcard $(S)src/librustpkg/*rs) # Rustdoc, the documentation tool RUSTDOC_LIB := $(S)src/librustdoc/rustdoc.rc @@ -57,8 +57,8 @@ $$(TBIN$(1)_T_$(4)_H_$(3))/compiletest$$(X): \ @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(4)_H_$(3)) -o $$@ $$< -$$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_LIBCARGO): \ - $$(CARGO_LIB) $$(CARGO_INPUTS) \ +$$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_LIBRUSTPKG): \ + $$(RUSTPKG_LIB) $$(RUSTPKG_INPUTS) \ $$(TSREQ$(1)_T_$(4)_H_$(3)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_CORELIB) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_STDLIB) \ @@ -66,11 +66,11 @@ $$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_LIBCARGO): \ @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(4)_H_$(3)) -o $$@ $$< && touch $$@ -$$(TBIN$(1)_T_$(4)_H_$(3))/cargo$$(X): \ +$$(TBIN$(1)_T_$(4)_H_$(3))/rustpkg$$(X): \ $$(DRIVER_CRATE) \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_LIBCARGO) + $$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_LIBRUSTPKG) @$$(call E, compile_and_link: $$@) - $$(STAGE$(1)_T_$(4)_H_$(3)) --cfg cargo -o $$@ $$< + $$(STAGE$(1)_T_$(4)_H_$(3)) --cfg rustpkg -o $$@ $$< $$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_LIBRUSTDOC): \ $$(RUSTDOC_LIB) $$(RUSTDOC_INPUTS) \ @@ -134,19 +134,19 @@ $$(HBIN$(2)_H_$(4))/compiletest$$(X): \ $$(Q)cp $$< $$@ -$$(HLIB$(2)_H_$(4))/$$(CFG_LIBCARGO): \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_LIBCARGO) \ +$$(HLIB$(2)_H_$(4))/$$(CFG_LIBRUSTPKG): \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$$(CFG_LIBRUSTPKG) \ $$(HLIB$(2)_H_$(4))/$$(CFG_LIBRUSTC) \ $$(HSREQ$(2)_H_$(4)) @$$(call E, cp: $$@) $$(Q)cp $$< $$@ - $$(Q)cp -R $$(TLIB$(1)_T_$(4)_H_$(3))/$(LIBCARGO_GLOB) \ - $$(wildcard $$(TLIB$(1)_T_$(4)_H_$(3))/$(LIBCARGO_DSYM_GLOB)) \ + $$(Q)cp -R $$(TLIB$(1)_T_$(4)_H_$(3))/$(LIBRUSTPKG_GLOB) \ + $$(wildcard $$(TLIB$(1)_T_$(4)_H_$(3))/$(LIBRUSTPKG_DSYM_GLOB)) \ $$(HLIB$(2)_H_$(4)) -$$(HBIN$(2)_H_$(4))/cargo$$(X): \ - $$(TBIN$(1)_T_$(4)_H_$(3))/cargo$$(X) \ - $$(HLIB$(2)_H_$(4))/$$(CFG_LIBCARGO) \ +$$(HBIN$(2)_H_$(4))/rustpkg$$(X): \ + $$(TBIN$(1)_T_$(4)_H_$(3))/rustpkg$$(X) \ + $$(HLIB$(2)_H_$(4))/$$(CFG_LIBRUSTPKG) \ $$(HSREQ$(2)_H_$(4)) @$$(call E, cp: $$@) $$(Q)cp $$< $$@ diff --git a/src/README.txt b/src/README.txt index c8029098cfaf4..1b06c4259fc6f 100644 --- a/src/README.txt +++ b/src/README.txt @@ -29,7 +29,7 @@ test/auxiliary - Dependencies of tests compiletest/ The test runner -libcargo/ The package manager +librustpkg/ The package manager and build system librusti/ The JIT REPL diff --git a/src/compiletest/compiletest.rc b/src/compiletest/compiletest.rc index 5557b1131766b..5ad616963fa66 100644 --- a/src/compiletest/compiletest.rc +++ b/src/compiletest/compiletest.rc @@ -177,7 +177,7 @@ pub fn make_tests(config: config) -> ~[test::TestDescAndFn] { tests.push(make_test(config, file)) } } - move tests + tests } pub fn is_test(config: config, testfile: &Path) -> bool { diff --git a/src/compiletest/procsrv.rs b/src/compiletest/procsrv.rs index 304266f0f7966..432258b26a638 100644 --- a/src/compiletest/procsrv.rs +++ b/src/compiletest/procsrv.rs @@ -78,12 +78,12 @@ pub fn run(lib_path: ~str, writeclose(pipe_in.out, input); let p = pipes::PortSet(); let ch = p.chan(); - do task::spawn_sched(task::SingleThreaded) |move ch| { + do task::spawn_sched(task::SingleThreaded) || { let errput = readclose(pipe_err.in); ch.send((2, errput)); } let ch = p.chan(); - do task::spawn_sched(task::SingleThreaded) |move ch| { + do task::spawn_sched(task::SingleThreaded) || { let output = readclose(pipe_out.in); ch.send((1, output)); } diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index fe03ccbb3f8e8..3213a11cbb51c 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -570,7 +570,8 @@ fn make_run_args(config: config, _props: TestProps, testfile: &Path) -> }; let args = toolargs + ~[make_exe_name(config, testfile).to_str()]; - return ProcArgs {prog: args[0], args: vec::slice(args, 1, args.len())}; + return ProcArgs {prog: args[0], + args: vec::slice(args, 1, args.len()).to_vec()}; } fn split_maybe_args(argstr: Option<~str>) -> ~[~str] { diff --git a/src/driver/driver.rs b/src/driver/driver.rs index 0c1cc566fe2ec..b2c4f69d3029b 100644 --- a/src/driver/driver.rs +++ b/src/driver/driver.rs @@ -11,8 +11,8 @@ #[no_core]; extern mod core(vers = "0.6"); -#[cfg(cargo)] -extern mod this(name = "cargo", vers = "0.6"); +#[cfg(rustpkg)] +extern mod this(name = "rustpkg", vers = "0.6"); #[cfg(fuzzer)] extern mod this(name = "fuzzer", vers = "0.6"); diff --git a/src/etc/emacs/rust-mode.el b/src/etc/emacs/rust-mode.el index ef98fa669e346..5fbd2ab67c29d 100644 --- a/src/etc/emacs/rust-mode.el +++ b/src/etc/emacs/rust-mode.el @@ -7,7 +7,6 @@ (require 'cm-mode) (require 'cc-mode) -(eval-when-compile (require 'cl)) (defun rust-electric-brace (arg) (interactive "*P") @@ -17,6 +16,12 @@ '(font-lock-comment-face font-lock-string-face)))) (cm-indent))) +(defcustom rust-capitalized-idents-are-types t + "If non-nil, capitalized identifiers will be treated as types for the purposes of font-lock mode" + :type 'boolean + :require 'rust-mode + :group 'rust-mode) + (defvar rust-indent-unit 4) (defvar rust-syntax-table (let ((table (make-syntax-table))) (c-populate-syntax-table table) @@ -101,14 +106,7 @@ (rust-push-context st 'string (current-column) t) (setf (rust-state-tokenize st) 'rust-token-string) (rust-token-string st)) - (def ?\' (forward-char) - (setf rust-tcat 'atom) - (let ((is-escape (eq (char-after) ?\\)) - (start (point))) - (if (not (rust-eat-until-unescaped ?\')) - 'font-lock-warning-face - (if (or is-escape (= (point) (+ start 2))) - 'font-lock-string-face 'font-lock-warning-face)))) + (def ?\' (rust-single-quote)) (def ?/ (forward-char) (case (char-after) (?/ (end-of-line) 'font-lock-comment-face) @@ -122,12 +120,7 @@ ((rust-eat-re "[a-z_]+") (setf rust-tcat 'macro))) 'font-lock-preprocessor-face) (def ((?a . ?z) (?A . ?Z) ?_) - (rust-eat-re "[a-zA-Z_][a-zA-Z0-9_]*") - (setf rust-tcat 'ident) - (if (and (eq (char-after) ?:) (eq (char-after (+ (point) 1)) ?:) - (not (eq (char-after (+ (point) 2)) ?:))) - (progn (forward-char 2) 'font-lock-builtin-face) - (match-string 0))) + (rust-token-identifier)) (def ((?0 . ?9)) (rust-eat-re "0x[0-9a-fA-F_]+\\|0b[01_]+\\|[0-9_]+\\(\\.[0-9_]+\\)?\\(e[+\\-]?[0-9_]+\\)?") (setf rust-tcat 'atom) @@ -150,6 +143,31 @@ (setf rust-tcat 'op) nil) table))) +(defun rust-token-identifier () + (rust-eat-re "[a-zA-Z_][a-zA-Z0-9_]*") + (setf rust-tcat 'ident) + (if (and (eq (char-after) ?:) (eq (char-after (+ (point) 1)) ?:) + (not (eq (char-after (+ (point) 2)) ?:))) + (progn (forward-char 2) 'font-lock-builtin-face) + (match-string 0))) + +(defun rust-single-quote () + (forward-char) + (setf rust-tcat 'atom) + ; Is this a lifetime? + (if (or (looking-at "[a-zA-Z_]$") + (looking-at "[a-zA-Z_][^']")) + ; If what we see is 'abc, use font-lock-builtin-face: + (progn (rust-eat-re "[a-zA-Z_][a-zA-Z_0-9]*") + 'font-lock-builtin-face) + ; Otherwise, handle as a character constant: + (let ((is-escape (eq (char-after) ?\\)) + (start (point))) + (if (not (rust-eat-until-unescaped ?\')) + 'font-lock-warning-face + (if (or is-escape (= (point) (+ start 2))) + 'font-lock-string-face 'font-lock-warning-face))))) + (defun rust-token-base (st) (funcall (char-table-range rust-char-table (char-after)) st)) @@ -190,6 +208,10 @@ (dolist (cx (rust-state-context st)) (when (eq (rust-context-type cx) ?\}) (return (rust-context-info cx))))) +(defun rust-is-capitalized (string) + (let ((case-fold-search nil)) + (string-match-p "[A-Z]" string))) + (defun rust-token (st) (let ((cx (car (rust-state-context st)))) (when (bolp) @@ -206,6 +228,8 @@ (setf tok (cond ((eq tok-id 'atom) 'font-lock-constant-face) (tok-id 'font-lock-keyword-face) ((equal (rust-state-last-token st) 'def) 'font-lock-function-name-face) + ((and rust-capitalized-idents-are-types + (rust-is-capitalized tok)) 'font-lock-type-face) (t nil)))) (when rust-tcat (when (eq (rust-context-align cx) 'unset) diff --git a/src/etc/licenseck.py b/src/etc/licenseck.py index 5e53eef7ef2b8..973b7deb960db 100644 --- a/src/etc/licenseck.py +++ b/src/etc/licenseck.py @@ -8,7 +8,8 @@ # option. This file may not be copied, modified, or distributed # except according to those terms. -license0 = """// Copyright 2012-2013 The Rust Project Developers. See the +license0 = """\ +// Copyright 2012-2013 The Rust Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -19,7 +20,8 @@ // except according to those terms. """ -license1 = """// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +license1 = """\ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -30,7 +32,8 @@ // except according to those terms. """ -license2 = """// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +license2 = """\ +// 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. // @@ -41,7 +44,8 @@ // except according to those terms. """ -license3 = """# Copyright 2013 The Rust Project Developers. See the COPYRIGHT +license3 = """\ +# 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. # @@ -52,7 +56,19 @@ # except according to those terms. """ -licenses = [license0, license1, license2, license3] +license4 = """\ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +""" + +licenses = [license0, license1, license2, license3, license4] exceptions = [ "rt/rust_android_dummy.cpp", # BSD, chromium diff --git a/src/etc/vim/syntax/rust.vim b/src/etc/vim/syntax/rust.vim index 4ff7783888f8d..8893608cda65b 100644 --- a/src/etc/vim/syntax/rust.vim +++ b/src/etc/vim/syntax/rust.vim @@ -14,7 +14,7 @@ syn match rustAssert "\ or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - - -// cargo.rs - Rust package manager - -// Local Variables: -// fill-column: 78; -// indent-tabs-mode: nil -// c-basic-offset: 4 -// buffer-file-coding-system: utf-8-unix -// End: - -#[link(name = "cargo", - vers = "0.6", - uuid = "9ff87a04-8fed-4295-9ff8-f99bb802650b", - url = "https://github.com/mozilla/rust/tree/master/src/cargo")]; - -#[crate_type = "lib"]; - -#[no_core]; - -#[legacy_modes]; - -#[allow(vecs_implicitly_copyable, - non_implicitly_copyable_typarams)]; -#[allow(non_camel_case_types)]; -#[allow(deprecated_mode)]; -#[allow(deprecated_pattern)]; -#[allow(deprecated_self)]; - -extern mod core(vers = "0.6"); -extern mod std(vers = "0.6"); -extern mod rustc(vers = "0.6"); -extern mod syntax(vers = "0.6"); - -mod pgp; - -use rustc::metadata::filesearch::{get_cargo_root, get_cargo_root_nearest}; -use rustc::metadata::filesearch::{get_cargo_sysroot, libdir}; - -use core::*; - -use core::dvec::DVec; -use core::io::WriterUtil; -use core::result::{Ok, Err}; -use core::hashmap::linear::LinearMap; -use std::getopts::{optflag, optopt, opt_present}; -use std::oldmap::HashMap; -use std::{oldmap, json, tempfile, term, sort, getopts}; -use syntax::codemap::span; -use syntax::diagnostic::span_handler; -use syntax::diagnostic; -use syntax::{ast, codemap, parse, visit, attr}; - -pub struct Package { - name: ~str, - uuid: ~str, - url: ~str, - method: ~str, - description: ~str, - reference: Option<~str>, - tags: ~[~str], - versions: ~[(~str, ~str)] -} - -pub impl Package : cmp::Ord { - pure fn lt(&self, other: &Package) -> bool { - if (*self).name.lt(&(*other).name) { return true; } - if (*other).name.lt(&(*self).name) { return false; } - if (*self).uuid.lt(&(*other).uuid) { return true; } - if (*other).uuid.lt(&(*self).uuid) { return false; } - if (*self).url.lt(&(*other).url) { return true; } - if (*other).url.lt(&(*self).url) { return false; } - if (*self).method.lt(&(*other).method) { return true; } - if (*other).method.lt(&(*self).method) { return false; } - if (*self).description.lt(&(*other).description) { return true; } - if (*other).description.lt(&(*self).description) { return false; } - if (*self).tags.lt(&(*other).tags) { return true; } - if (*other).tags.lt(&(*self).tags) { return false; } - if (*self).versions.lt(&(*other).versions) { return true; } - return false; - } - pure fn le(&self, other: &Package) -> bool { !(*other).lt(&(*self)) } - pure fn ge(&self, other: &Package) -> bool { !(*self).lt(other) } - pure fn gt(&self, other: &Package) -> bool { (*other).lt(&(*self)) } -} - -pub struct Source { - name: ~str, - mut url: ~str, - mut method: ~str, - mut key: Option<~str>, - mut keyfp: Option<~str>, - packages: DVec -} - -pub struct Cargo { - pgp: bool, - root: Path, - installdir: Path, - bindir: Path, - libdir: Path, - workdir: Path, - sourcedir: Path, - sources: oldmap::HashMap<~str, @Source>, - mut current_install: ~str, - dep_cache: oldmap::HashMap<~str, bool>, - opts: Options -} - -pub struct Crate { - name: ~str, - vers: ~str, - uuid: ~str, - desc: Option<~str>, - sigs: Option<~str>, - crate_type: Option<~str>, - deps: ~[~str] -} - -pub struct Options { - test: bool, - mode: Mode, - free: ~[~str], - help: bool, -} - -#[deriving_eq] -pub enum Mode { SystemMode, UserMode, LocalMode } - -pub fn opts() -> ~[getopts::Opt] { - ~[optflag(~"g"), optflag(~"G"), optflag(~"test"), - optflag(~"h"), optflag(~"help")] -} - -pub fn info(msg: ~str) { - let out = io::stdout(); - - if term::color_supported() { - term::fg(out, term::color_green); - out.write_str(~"info: "); - term::reset(out); - out.write_line(msg); - } else { out.write_line(~"info: " + msg); } -} - -pub fn warn(msg: ~str) { - let out = io::stdout(); - - if term::color_supported() { - term::fg(out, term::color_yellow); - out.write_str(~"warning: "); - term::reset(out); - out.write_line(msg); - }else { out.write_line(~"warning: " + msg); } -} - -pub fn error(msg: ~str) { - let out = io::stdout(); - - if term::color_supported() { - term::fg(out, term::color_red); - out.write_str(~"error: "); - term::reset(out); - out.write_line(msg); - } - else { out.write_line(~"error: " + msg); } -} - -pub fn is_uuid(id: ~str) -> bool { - let parts = str::split_str(id, ~"-"); - if vec::len(parts) == 5u { - let mut correct = 0u; - for vec::eachi(parts) |i, part| { - fn is_hex_digit(+ch: char) -> bool { - ('0' <= ch && ch <= '9') || - ('a' <= ch && ch <= 'f') || - ('A' <= ch && ch <= 'F') - } - - if !part.all(is_hex_digit) { - return false; - } - - match i { - 0u => { - if part.len() == 8u { - correct += 1u; - } - } - 1u | 2u | 3u => { - if part.len() == 4u { - correct += 1u; - } - } - 4u => { - if part.len() == 12u { - correct += 1u; - } - } - _ => { } - } - } - if correct >= 5u { - return true; - } - } - return false; -} - -#[test] -pub fn test_is_uuid() { - assert is_uuid(~"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaafAF09"); - assert !is_uuid(~"aaaaaaaa-aaaa-aaaa-aaaaa-aaaaaaaaaaaa"); - assert !is_uuid(~""); - assert !is_uuid(~"aaaaaaaa-aaa -aaaa-aaaa-aaaaaaaaaaaa"); - assert !is_uuid(~"aaaaaaaa-aaa!-aaaa-aaaa-aaaaaaaaaaaa"); - assert !is_uuid(~"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa-a"); - assert !is_uuid(~"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaป"); -} - -// FIXME (#2661): implement url/URL parsing so we don't have to resort -// to weak checks - -pub fn has_archive_extension(p: ~str) -> bool { - str::ends_with(p, ~".tar") || - str::ends_with(p, ~".tar.gz") || - str::ends_with(p, ~".tar.bz2") || - str::ends_with(p, ~".tar.Z") || - str::ends_with(p, ~".tar.lz") || - str::ends_with(p, ~".tar.xz") || - str::ends_with(p, ~".tgz") || - str::ends_with(p, ~".tbz") || - str::ends_with(p, ~".tbz2") || - str::ends_with(p, ~".tb2") || - str::ends_with(p, ~".taz") || - str::ends_with(p, ~".tlz") || - str::ends_with(p, ~".txz") -} - -pub fn is_archive_path(u: ~str) -> bool { - has_archive_extension(u) && os::path_exists(&Path(u)) -} - -pub fn is_archive_url(u: ~str) -> bool { - // FIXME (#2661): this requires the protocol bit - if we had proper - // url parsing, we wouldn't need it - - match str::find_str(u, ~"://") { - option::Some(_) => has_archive_extension(u), - _ => false - } -} - -pub fn is_git_url(url: ~str) -> bool { - if str::ends_with(url, ~"/") { str::ends_with(url, ~".git/") } - else { - str::starts_with(url, ~"git://") || str::ends_with(url, ~".git") - } -} - -pub fn assume_source_method(url: ~str) -> ~str { - if is_git_url(url) { - return ~"git"; - } - if str::starts_with(url, ~"file://") || os::path_exists(&Path(url)) { - return ~"file"; - } - - ~"curl" -} - -pub fn load_link(mis: ~[@ast::meta_item]) -> (Option<~str>, - Option<~str>, - Option<~str>) { - let mut name = None; - let mut vers = None; - let mut uuid = None; - for mis.each |a| { - match a.node { - ast::meta_name_value(v, codemap::spanned { node: ast::lit_str(s), - _ }) => { - match v { - ~"name" => name = Some(*s), - ~"vers" => vers = Some(*s), - ~"uuid" => uuid = Some(*s), - _ => { } - } - } - _ => fail!(~"load_link: meta items must be name-values") - } - } - (name, vers, uuid) -} - -pub fn load_crate(filename: &Path) -> Option { - let sess = parse::new_parse_sess(None); - let c = parse::parse_crate_from_file(filename, ~[], sess); - - let mut name = None; - let mut vers = None; - let mut uuid = None; - let mut desc = None; - let mut sigs = None; - let mut crate_type = None; - - for c.node.attrs.each |a| { - match a.node.value.node { - ast::meta_name_value(v, codemap::spanned { node: ast::lit_str(_), - _ }) => { - match v { - ~"desc" => desc = Some(v), - ~"sigs" => sigs = Some(v), - ~"crate_type" => crate_type = Some(v), - _ => { } - } - } - ast::meta_list(v, mis) => { - if v == ~"link" { - let (n, v, u) = load_link(mis); - name = n; - vers = v; - uuid = u; - } - } - _ => { - fail!(~"crate attributes may not contain " + - ~"meta_words"); - } - } - } - - struct Env { - mut deps: ~[~str] - } - - fn goto_view_item(ps: syntax::parse::parse_sess, e: @Env, - i: @ast::view_item) { - match i.node { - ast::view_item_use(ident, metas, _) => { - let name_items = - attr::find_meta_items_by_name(metas, ~"name"); - let m = if name_items.is_empty() { - metas + ~[attr::mk_name_value_item_str( - ~"name", *ps.interner.get(ident))] - } else { - metas - }; - let mut attr_name = ident; - let mut attr_vers = ~""; - let mut attr_from = ~""; - - for m.each |item| { - match attr::get_meta_item_value_str(*item) { - Some(value) => { - let name = attr::get_meta_item_name(*item); - - match name { - ~"vers" => attr_vers = value, - ~"from" => attr_from = value, - _ => () - } - } - None => () - } - } - - let query = if !str::is_empty(attr_from) { - attr_from - } else { - if !str::is_empty(attr_vers) { - ps.interner.get(attr_name) + ~"@" + attr_vers - } else { *ps.interner.get(attr_name) } - }; - - match *ps.interner.get(attr_name) { - ~"std" | ~"core" => (), - _ => e.deps.push(query) - } - } - _ => () - } - } - fn goto_item(_e: @Env, _i: @ast::item) { - } - - let e = @Env { - mut deps: ~[] - }; - let v = visit::mk_simple_visitor(@visit::SimpleVisitor { - visit_view_item: |a| goto_view_item(sess, e, a), - visit_item: |a| goto_item(e, a), - .. *visit::default_simple_visitor() - }); - - visit::visit_crate(*c, (), v); - - let deps = copy e.deps; - - match (name, vers, uuid) { - (Some(name0), Some(vers0), Some(uuid0)) => { - Some(Crate { - name: name0, - vers: vers0, - uuid: uuid0, - desc: desc, - sigs: sigs, - crate_type: crate_type, - deps: deps }) - } - _ => return None - } -} - -pub fn print(s: ~str) { - io::stdout().write_line(s); -} - -pub fn rest(s: ~str, start: uint) -> ~str { - if (start >= str::len(s)) { - ~"" - } else { - str::slice(s, start, str::len(s)) - } -} - -pub fn need_dir(s: &Path) { - if os::path_is_dir(s) { return; } - if !os::make_dir(s, 493_i32 /* oct: 755 */) { - fail!(fmt!("can't make_dir %s", s.to_str())); - } -} - -pub fn valid_pkg_name(s: &str) -> bool { - fn is_valid_digit(+c: char) -> bool { - ('0' <= c && c <= '9') || - ('a' <= c && c <= 'z') || - ('A' <= c && c <= 'Z') || - c == '-' || - c == '_' - } - - s.all(is_valid_digit) -} - -pub fn parse_source(name: ~str, j: &json::Json) -> @Source { - if !valid_pkg_name(name) { - fail!(fmt!("'%s' is an invalid source name", name)); - } - - match *j { - json::Object(ref j) => { - let mut url = match j.find(&~"url") { - Some(&json::String(u)) => copy u, - _ => fail!(~"needed 'url' field in source") - }; - let method = match j.find(&~"method") { - Some(&json::String(u)) => copy u, - _ => assume_source_method(url) - }; - let key = match j.find(&~"key") { - Some(&json::String(u)) => Some(copy u), - _ => None - }; - let keyfp = match j.find(&~"keyfp") { - Some(&json::String(u)) => Some(copy u), - _ => None - }; - if method == ~"file" { - url = os::make_absolute(&Path(url)).to_str(); - } - return @Source { - name: name, - mut url: url, - mut method: method, - mut key: key, - mut keyfp: keyfp, - packages: DVec() }; - } - _ => fail!(~"needed dict value in source") - }; -} - -pub fn try_parse_sources(filename: &Path, - sources: oldmap::HashMap<~str, @Source>) { - if !os::path_exists(filename) { return; } - let c = io::read_whole_file_str(filename); - match json::from_str(c.get()) { - Ok(json::Object(j)) => { - for j.each |&(k, v)| { - sources.insert(copy *k, parse_source(*k, v)); - debug!("source: %s", *k); - } - } - Ok(_) => fail!(~"malformed sources.json"), - Err(e) => fail!(fmt!("%s:%s", filename.to_str(), e.to_str())) - } -} - -pub fn load_one_source_package(src: @Source, p: &json::Object) { - let name = match p.find(&~"name") { - Some(&json::String(n)) => { - if !valid_pkg_name(n) { - warn(~"malformed source json: " - + src.name + ~", '" + n + ~"'"+ - ~" is an invalid name (alphanumeric, underscores and" + - ~" dashes only)"); - return; - } - n - } - _ => { - warn(~"malformed source json: " + src.name + ~" (missing name)"); - return; - } - }; - - let uuid = match p.find(&~"uuid") { - Some(&json::String(n)) => { - if !is_uuid(n) { - warn(~"malformed source json: " - + src.name + ~", '" + n + ~"'"+ - ~" is an invalid uuid"); - return; - } - copy n - } - _ => { - warn(~"malformed source json: " + src.name + ~" (missing uuid)"); - return; - } - }; - - let url = match p.find(&~"url") { - Some(&json::String(n)) => copy n, - _ => { - warn(~"malformed source json: " + src.name + ~" (missing url)"); - return; - } - }; - - let method = match p.find(&~"method") { - Some(&json::String(n)) => copy n, - _ => { - warn(~"malformed source json: " - + src.name + ~" (missing method)"); - return; - } - }; - - let reference = match p.find(&~"ref") { - Some(&json::String(n)) => Some(copy n), - _ => None - }; - - let mut tags = ~[]; - match p.find(&~"tags") { - Some(&json::List(ref js)) => { - for js.each |j| { - match *j { - json::String(ref j) => tags.grow(1u, j), - _ => () - } - } - } - _ => () - } - - let description = match p.find(&~"description") { - Some(&json::String(n)) => copy n, - _ => { - warn(~"malformed source json: " + src.name - + ~" (missing description)"); - return; - } - }; - - let newpkg = Package { - name: name, - uuid: uuid, - url: url, - method: method, - description: description, - reference: reference, - tags: tags, - versions: ~[] - }; - - match src.packages.position(|pkg| pkg.uuid == uuid) { - Some(idx) => { - src.packages.set_elt(idx, newpkg); - log(debug, ~" updated package: " + src.name + ~"/" + name); - } - None => { - src.packages.push(newpkg); - } - } - - log(debug, ~" loaded package: " + src.name + ~"/" + name); -} - -pub fn load_source_info(c: &Cargo, src: @Source) { - let dir = c.sourcedir.push(src.name); - let srcfile = dir.push("source.json"); - if !os::path_exists(&srcfile) { return; } - let srcstr = io::read_whole_file_str(&srcfile); - match json::from_str(srcstr.get()) { - Ok(ref json @ json::Object(_)) => { - let o = parse_source(src.name, json); - - src.key = o.key; - src.keyfp = o.keyfp; - } - Ok(_) => { - warn(~"malformed source.json: " + src.name + - ~"(source info is not a dict)"); - } - Err(e) => { - warn(fmt!("%s:%s", src.name, e.to_str())); - } - }; -} -pub fn load_source_packages(c: &Cargo, src: @Source) { - log(debug, ~"loading source: " + src.name); - let dir = c.sourcedir.push(src.name); - let pkgfile = dir.push("packages.json"); - if !os::path_exists(&pkgfile) { return; } - let pkgstr = io::read_whole_file_str(&pkgfile); - match json::from_str(pkgstr.get()) { - Ok(json::List(ref js)) => { - for js.each |j| { - match *j { - json::Object(ref p) => { - load_one_source_package(src, *p); - } - _ => { - warn(~"malformed source json: " + src.name + - ~" (non-dict pkg)"); - } - } - } - } - Ok(_) => { - warn(~"malformed packages.json: " + src.name + - ~"(packages is not a list)"); - } - Err(e) => { - warn(fmt!("%s:%s", src.name, e.to_str())); - } - }; -} - -pub fn build_cargo_options(argv: ~[~str]) -> Options { - let matches = &match getopts::getopts(argv, opts()) { - result::Ok(m) => m, - result::Err(f) => { - fail!(fmt!("%s", getopts::fail_str(f))); - } - }; - - let test = opt_present(matches, ~"test"); - let G = opt_present(matches, ~"G"); - let g = opt_present(matches, ~"g"); - let help = opt_present(matches, ~"h") || opt_present(matches, ~"help"); - let len = vec::len(matches.free); - - let is_install = len > 1u && matches.free[1] == ~"install"; - let is_uninstall = len > 1u && matches.free[1] == ~"uninstall"; - - if G && g { fail!(~"-G and -g both provided"); } - - if !is_install && !is_uninstall && (g || G) { - fail!(~"-g and -G are only valid for `install` and `uninstall|rm`"); - } - - let mode = - if (!is_install && !is_uninstall) || g { UserMode } - else if G { SystemMode } - else { LocalMode }; - - Options {test: test, mode: mode, free: matches.free, help: help} -} - -pub fn configure(opts: Options) -> Cargo { - let home = match get_cargo_root() { - Ok(home) => home, - Err(_err) => get_cargo_sysroot().get() - }; - - let get_cargo_dir = match opts.mode { - SystemMode => get_cargo_sysroot, - UserMode => get_cargo_root, - LocalMode => get_cargo_root_nearest - }; - - let p = get_cargo_dir().get(); - - let sources = HashMap(); - try_parse_sources(&home.push("sources.json"), sources); - try_parse_sources(&home.push("local-sources.json"), sources); - - let dep_cache = HashMap(); - - let mut c = Cargo { - pgp: pgp::supported(), - root: home, - installdir: p, - bindir: p.push("bin"), - libdir: p.push("lib"), - workdir: p.push("work"), - sourcedir: home.push("sources"), - sources: sources, - mut current_install: ~"", - dep_cache: dep_cache, - opts: opts - }; - - need_dir(&c.root); - need_dir(&c.installdir); - need_dir(&c.sourcedir); - need_dir(&c.workdir); - need_dir(&c.libdir); - need_dir(&c.bindir); - - for sources.each_key |&k| { - let mut s = sources.get(&k); - load_source_packages(&c, s); - sources.insert(k, s); - } - - if c.pgp { - pgp::init(&c.root); - } else { - warn(~"command `gpg` was not found"); - warn(~"you have to install gpg from source " + - ~" or package manager to get it to work correctly"); - } - - move c -} - -pub fn for_each_package(c: &Cargo, b: fn(s: @Source, p: &Package)) { - for c.sources.each_value |&v| { - for v.packages.each |p| { - b(v, p); - } - } -} - -// Runs all programs in directory -pub fn run_programs(buildpath: &Path) { - let newv = os::list_dir_path(buildpath); - for newv.each |ct| { - run::run_program(ct.to_str(), ~[]); - } -} - -// Runs rustc in with the given flags -// and returns -pub fn run_in_buildpath(what: &str, path: &Path, subdir: &Path, cf: &Path, - extra_flags: ~[~str]) -> Option { - let buildpath = path.push_rel(subdir); - need_dir(&buildpath); - debug!("%s: %s -> %s", what, cf.to_str(), buildpath.to_str()); - let p = run::program_output(rustc_sysroot(), - ~[~"--out-dir", - buildpath.to_str(), - cf.to_str()] + extra_flags); - if p.status != 0 { - error(fmt!("rustc failed: %d\n%s\n%s", p.status, p.err, p.out)); - return None; - } - Some(buildpath) -} - -pub fn test_one_crate(_c: &Cargo, path: &Path, cf: &Path) { - let buildpath = match run_in_buildpath(~"testing", path, - &Path("test"), - cf, - ~[ ~"--test"]) { - None => return, - Some(bp) => bp - }; - run_programs(&buildpath); -} - -pub fn install_one_crate(c: &Cargo, path: &Path, cf: &Path) { - let buildpath = match run_in_buildpath(~"installing", path, - &Path("build"), - cf, ~[]) { - None => return, - Some(bp) => bp - }; - let newv = os::list_dir_path(&buildpath); - let exec_suffix = str::from_slice(os::EXE_SUFFIX); - for newv.each |ct| { - if (exec_suffix != ~"" && str::ends_with(ct.to_str(), - exec_suffix)) || - (exec_suffix == ~"" && - !str::starts_with(ct.filename().get(), - ~"lib")) { - debug!(" bin: %s", ct.to_str()); - install_to_dir(*ct, &c.bindir); - if c.opts.mode == SystemMode { - // FIXME (#2662): Put this file in PATH / symlink it so it can - // be used as a generic executable - // `cargo install -G rustray` and `rustray file.obj` - } - } else { - debug!(" lib: %s", ct.to_str()); - install_to_dir(*ct, &c.libdir); - } - } -} - - -pub fn rustc_sysroot() -> ~str { - match os::self_exe_path() { - Some(path) => { - let rustc = path.push_many([~"..", ~"bin", ~"rustc"]); - debug!(" rustc: %s", rustc.to_str()); - rustc.to_str() - } - None => ~"rustc" - } -} - -pub fn install_source(c: &mut Cargo, path: &Path) { - debug!("source: %s", path.to_str()); - os::change_dir(path); - - let mut cratefiles = ~[]; - for os::walk_dir(&Path(".")) |p| { - if p.filetype() == Some(~".rc") { - cratefiles.push(*p); - } - } - - if vec::is_empty(cratefiles) { - fail!(~"this doesn't look like a rust package (no .rc files)"); - } - - for cratefiles.each |cf| { - match load_crate(cf) { - None => loop, - Some(crate) => { - for crate.deps.each |query| { - // FIXME (#1356): handle cyclic dependencies - // (n.b. #1356 says "Cyclic dependency is an error - // condition") - - let wd = get_temp_workdir(c); - install_query(c, &wd, *query); - } - - os::change_dir(path); - - if c.opts.test { - test_one_crate(c, path, cf); - } - install_one_crate(c, path, cf); - } - } - } -} - -pub fn install_git(c: &mut Cargo, wd: &Path, url: ~str, - reference: Option<~str>) { - run::program_output(~"git", ~[~"clone", url, wd.to_str()]); - if reference.is_some() { - let r = reference.get(); - os::change_dir(wd); - run::run_program(~"git", ~[~"checkout", r]); - } - - install_source(c, wd); -} - -pub fn install_curl(c: &mut Cargo, wd: &Path, url: ~str) { - let tarpath = wd.push("pkg.tar"); - let p = run::program_output(~"curl", ~[~"-f", ~"-s", ~"-o", - tarpath.to_str(), url]); - if p.status != 0 { - fail!(fmt!("fetch of %s failed: %s", url, p.err)); - } - run::run_program(~"tar", ~[~"-x", ~"--strip-components=1", - ~"-C", wd.to_str(), - ~"-f", tarpath.to_str()]); - install_source(c, wd); -} - -pub fn install_file(c: &mut Cargo, wd: &Path, path: &Path) { - run::program_output(~"tar", ~[~"-x", ~"--strip-components=1", - ~"-C", wd.to_str(), - ~"-f", path.to_str()]); - install_source(c, wd); -} - -pub fn install_package(c: &mut Cargo, src: ~str, wd: &Path, pkg: Package) { - let url = copy pkg.url; - let method = match pkg.method { - ~"git" => ~"git", - ~"file" => ~"file", - _ => ~"curl" - }; - - info(fmt!("installing %s/%s via %s...", src, pkg.name, method)); - - match method { - ~"git" => install_git(c, wd, url, copy pkg.reference), - ~"file" => install_file(c, wd, &Path(url)), - ~"curl" => install_curl(c, wd, url), - _ => () - } -} - -pub fn cargo_suggestion(c: &Cargo, fallback: fn()) { - if c.sources.is_empty() { - error(~"no sources defined - you may wish to run " + - ~"`cargo init`"); - return; - } - fallback(); -} - -pub fn install_uuid(c: &mut Cargo, wd: &Path, uuid: ~str) { - let mut ps = ~[]; - for_each_package(c, |s, p| { - if p.uuid == uuid { - vec::push(&mut ps, (s.name, copy *p)); - } - }); - if vec::len(ps) == 1u { - let (sname, p) = copy ps[0]; - install_package(c, sname, wd, p); - return; - } else if vec::len(ps) == 0u { - cargo_suggestion(c, || { - error(~"can't find package: " + uuid); - }); - return; - } - error(~"found multiple packages:"); - for ps.each |elt| { - let (sname,p) = copy *elt; - info(~" " + sname + ~"/" + p.uuid + ~" (" + p.name + ~")"); - } -} - -pub fn install_named(c: &mut Cargo, wd: &Path, name: ~str) { - let mut ps = ~[]; - for_each_package(c, |s, p| { - if p.name == name { - vec::push(&mut ps, (s.name, copy *p)); - } - }); - if vec::len(ps) == 1u { - let (sname, p) = copy ps[0]; - install_package(c, sname, wd, p); - return; - } else if vec::len(ps) == 0u { - cargo_suggestion(c, || { - error(~"can't find package: " + name); - }); - return; - } - error(~"found multiple packages:"); - for ps.each |elt| { - let (sname,p) = copy *elt; - info(~" " + sname + ~"/" + p.uuid + ~" (" + p.name + ~")"); - } -} - -pub fn install_uuid_specific(c: &mut Cargo, wd: &Path, src: ~str, - uuid: ~str) { - match c.sources.find(&src) { - Some(s) => { - for s.packages.each |p| { - if p.uuid == uuid { - install_package(c, src, wd, *p); - return; - } - } - } - _ => () - } - error(~"can't find package: " + src + ~"/" + uuid); -} - -pub fn install_named_specific(c: &mut Cargo, wd: &Path, src: ~str, - name: ~str) { - match c.sources.find(&src) { - Some(s) => { - for s.packages.each |p| { - if p.name == name { - install_package(c, src, wd, *p); - return; - } - } - } - _ => () - } - error(~"can't find package: " + src + ~"/" + name); -} - -pub fn cmd_uninstall(c: &Cargo) { - if vec::len(c.opts.free) < 3u { - cmd_usage(); - return; - } - - let lib = &c.libdir; - let bin = &c.bindir; - let target = c.opts.free[2u]; - - // FIXME (#2662): needs stronger pattern matching - // FIXME (#2662): needs to uninstall from a specified location in a - // cache instead of looking for it (binaries can be uninstalled by - // name only) - - fn try_uninstall(p: &Path) -> bool { - if os::remove_file(p) { - info(~"uninstalled: '" + p.to_str() + ~"'"); - true - } else { - error(~"could not uninstall: '" + - p.to_str() + ~"'"); - false - } - } - - if is_uuid(target) { - for os::list_dir(lib).each |file| { - match str::find_str(*file, ~"-" + target + ~"-") { - Some(_) => if !try_uninstall(&lib.push(*file)) { return }, - None => () - } - } - error(~"can't find package with uuid: " + target); - } else { - for os::list_dir(lib).each |file| { - match str::find_str(*file, ~"lib" + target + ~"-") { - Some(_) => if !try_uninstall(&lib.push(*file)) { return }, - None => () - } - } - for os::list_dir(bin).each |file| { - match str::find_str(*file, target) { - Some(_) => if !try_uninstall(&lib.push(*file)) { return }, - None => () - } - } - - error(~"can't find package with name: " + target); - } -} - -pub fn install_query(c: &mut Cargo, wd: &Path, target: ~str) { - match c.dep_cache.find(&target) { - Some(inst) => { - if inst { - return; - } - } - None => () - } - - c.dep_cache.insert(target, true); - - if is_archive_path(target) { - install_file(c, wd, &Path(target)); - return; - } else if is_git_url(target) { - let reference = if c.opts.free.len() >= 4u { - Some(c.opts.free[3u]) - } else { - None - }; - install_git(c, wd, target, reference); - } else if !valid_pkg_name(target) && has_archive_extension(target) { - install_curl(c, wd, target); - return; - } else { - let mut ps = copy target; - - match str::find_char(ps, '/') { - option::Some(idx) => { - let source = str::slice(ps, 0u, idx); - ps = str::slice(ps, idx + 1u, str::len(ps)); - if is_uuid(ps) { - install_uuid_specific(c, wd, source, ps); - } else { - install_named_specific(c, wd, source, ps); - } - } - option::None => { - if is_uuid(ps) { - install_uuid(c, wd, ps); - } else { - install_named(c, wd, ps); - } - } - } - } - - // FIXME (#2662): This whole dep_cache and current_install thing is - // a bit of a hack. It should be cleaned up in the future. - - if target == c.current_install { - c.dep_cache.clear(); - c.current_install = ~""; - } -} - -pub fn get_temp_workdir(c: &Cargo) -> Path { - match tempfile::mkdtemp(&c.workdir, "cargo") { - Some(wd) => wd, - None => fail!(fmt!("needed temp dir: %s", - c.workdir.to_str())) - } -} - -pub fn cmd_install(c: &mut Cargo) { - unsafe { - let wd = get_temp_workdir(c); - - if vec::len(c.opts.free) == 2u { - let cwd = os::getcwd(); - let status = run::run_program(~"cp", ~[~"-R", cwd.to_str(), - wd.to_str()]); - - if status != 0 { - fail!(fmt!("could not copy directory: %s", cwd.to_str())); - } - - install_source(c, &wd); - return; - } - - sync(c); - - let query = c.opts.free[2]; - c.current_install = query.to_str(); - - install_query(c, &wd, query); - } -} - -pub fn sync(c: &Cargo) { - for c.sources.each_key |&k| { - let mut s = c.sources.get(&k); - sync_one(c, s); - c.sources.insert(k, s); - } -} - -pub fn sync_one_file(c: &Cargo, dir: &Path, src: @Source) -> bool { - let name = src.name; - let srcfile = dir.push("source.json.new"); - let destsrcfile = dir.push("source.json"); - let pkgfile = dir.push("packages.json.new"); - let destpkgfile = dir.push("packages.json"); - let keyfile = dir.push("key.gpg"); - let srcsigfile = dir.push("source.json.sig"); - let sigfile = dir.push("packages.json.sig"); - let url = Path(src.url); - let mut has_src_file = false; - - if !os::copy_file(&url.push("packages.json"), &pkgfile) { - error(fmt!("fetch for source %s (url %s) failed", - name, url.to_str())); - return false; - } - - if os::copy_file(&url.push("source.json"), &srcfile) { - has_src_file = false; - } - - os::copy_file(&url.push("source.json.sig"), &srcsigfile); - os::copy_file(&url.push("packages.json.sig"), &sigfile); - - match copy src.key { - Some(u) => { - let p = run::program_output(~"curl", - ~[~"-f", ~"-s", - ~"-o", keyfile.to_str(), u]); - if p.status != 0 { - error(fmt!("fetch for source %s (key %s) failed", name, u)); - return false; - } - pgp::add(&c.root, &keyfile); - } - _ => () - } - match (src.key, src.keyfp) { - (Some(_), Some(f)) => { - let r = pgp::verify(&c.root, &pkgfile, &sigfile); - - if !r { - error(fmt!("signature verification failed for source %s with \ - key %s", name, f)); - return false; - } - - if has_src_file { - let e = pgp::verify(&c.root, &srcfile, &srcsigfile); - - if !e { - error(fmt!("signature verification failed for source %s \ - with key %s", name, f)); - return false; - } - } - } - _ => () - } - - copy_warn(&pkgfile, &destpkgfile); - - if has_src_file { - copy_warn(&srcfile, &destsrcfile); - } - - os::remove_file(&keyfile); - os::remove_file(&srcfile); - os::remove_file(&srcsigfile); - os::remove_file(&pkgfile); - os::remove_file(&sigfile); - - info(fmt!("synced source: %s", name)); - - return true; -} - -pub fn sync_one_git(c: &Cargo, dir: &Path, src: @Source) -> bool { - let name = src.name; - let srcfile = dir.push("source.json"); - let pkgfile = dir.push("packages.json"); - let keyfile = dir.push("key.gpg"); - let srcsigfile = dir.push("source.json.sig"); - let sigfile = dir.push("packages.json.sig"); - let url = src.url; - - fn rollback(name: ~str, dir: &Path, insecure: bool) { - fn msg(name: ~str, insecure: bool) { - error(fmt!("could not rollback source: %s", name)); - - if insecure { - warn(~"a past security check failed on source " + - name + ~" and rolling back the source failed -" - + ~" this source may be compromised"); - } - } - - if !os::change_dir(dir) { - msg(name, insecure); - } - else { - let p = run::program_output(~"git", ~[~"reset", ~"--hard", - ~"HEAD@{1}"]); - - if p.status != 0 { - msg(name, insecure); - } - } - } - - if !os::path_exists(&dir.push(".git")) { - let p = run::program_output(~"git", ~[~"clone", url, dir.to_str()]); - - if p.status != 0 { - error(fmt!("fetch for source %s (url %s) failed", name, url)); - return false; - } - } - else { - if !os::change_dir(dir) { - error(fmt!("fetch for source %s (url %s) failed", name, url)); - return false; - } - - let p = run::program_output(~"git", ~[~"pull"]); - - if p.status != 0 { - error(fmt!("fetch for source %s (url %s) failed", name, url)); - return false; - } - } - - let has_src_file = os::path_exists(&srcfile); - - match copy src.key { - Some(u) => { - let p = run::program_output(~"curl", - ~[~"-f", ~"-s", - ~"-o", keyfile.to_str(), u]); - if p.status != 0 { - error(fmt!("fetch for source %s (key %s) failed", name, u)); - rollback(name, dir, false); - return false; - } - pgp::add(&c.root, &keyfile); - } - _ => () - } - match (src.key, src.keyfp) { - (Some(_), Some(f)) => { - let r = pgp::verify(&c.root, &pkgfile, &sigfile); - - if !r { - error(fmt!("signature verification failed for source %s with \ - key %s", name, f)); - rollback(name, dir, false); - return false; - } - - if has_src_file { - let e = pgp::verify(&c.root, &srcfile, &srcsigfile); - - if !e { - error(fmt!("signature verification failed for source %s \ - with key %s", name, f)); - rollback(name, dir, false); - return false; - } - } - } - _ => () - } - - os::remove_file(&keyfile); - - info(fmt!("synced source: %s", name)); - - return true; -} - -pub fn sync_one_curl(c: &Cargo, dir: &Path, src: @Source) -> bool { - let name = src.name; - let srcfile = dir.push("source.json.new"); - let destsrcfile = dir.push("source.json"); - let pkgfile = dir.push("packages.json.new"); - let destpkgfile = dir.push("packages.json"); - let keyfile = dir.push("key.gpg"); - let srcsigfile = dir.push("source.json.sig"); - let sigfile = dir.push("packages.json.sig"); - let mut url = src.url; - let smart = !str::ends_with(src.url, ~"packages.json"); - let mut has_src_file = false; - - if smart { - url += ~"/packages.json"; - } - - let p = run::program_output(~"curl", - ~[~"-f", ~"-s", - ~"-o", pkgfile.to_str(), url]); - - if p.status != 0 { - error(fmt!("fetch for source %s (url %s) failed", name, url)); - return false; - } - if smart { - url = src.url + ~"/source.json"; - let p = - run::program_output(~"curl", - ~[~"-f", ~"-s", - ~"-o", srcfile.to_str(), url]); - - if p.status == 0 { - has_src_file = true; - } - } - - match copy src.key { - Some(u) => { - let p = run::program_output(~"curl", - ~[~"-f", ~"-s", - ~"-o", keyfile.to_str(), u]); - if p.status != 0 { - error(fmt!("fetch for source %s (key %s) failed", name, u)); - return false; - } - pgp::add(&c.root, &keyfile); - } - _ => () - } - match (src.key, src.keyfp) { - (Some(_), Some(f)) => { - if smart { - url = src.url + ~"/packages.json.sig"; - } - else { - url = src.url + ~".sig"; - } - - let mut p = run::program_output(~"curl", - ~[~"-f", ~"-s", ~"-o", - sigfile.to_str(), url]); - if p.status != 0 { - error(fmt!("fetch for source %s (sig %s) failed", name, url)); - return false; - } - - let r = pgp::verify(&c.root, &pkgfile, &sigfile); - - if !r { - error(fmt!("signature verification failed for source %s with \ - key %s", name, f)); - return false; - } - - if smart && has_src_file { - url = src.url + ~"/source.json.sig"; - - p = run::program_output(~"curl", - ~[~"-f", ~"-s", ~"-o", - srcsigfile.to_str(), url]); - if p.status != 0 { - error(fmt!("fetch for source %s (sig %s) failed", - name, url)); - return false; - } - - let e = pgp::verify(&c.root, &srcfile, &srcsigfile); - - if !e { - error(~"signature verification failed for " + - ~"source " + name + ~" with key " + f); - return false; - } - } - } - _ => () - } - - copy_warn(&pkgfile, &destpkgfile); - - if smart && has_src_file { - copy_warn(&srcfile, &destsrcfile); - } - - os::remove_file(&keyfile); - os::remove_file(&srcfile); - os::remove_file(&srcsigfile); - os::remove_file(&pkgfile); - os::remove_file(&sigfile); - - info(fmt!("synced source: %s", name)); - - return true; -} - -pub fn sync_one(c: &Cargo, src: @Source) { - let name = src.name; - let dir = c.sourcedir.push(name); - - info(fmt!("syncing source: %s...", name)); - - need_dir(&dir); - - let result = match src.method { - ~"git" => sync_one_git(c, &dir, src), - ~"file" => sync_one_file(c, &dir, src), - _ => sync_one_curl(c, &dir, src) - }; - - if result { - load_source_info(c, src); - load_source_packages(c, src); - } -} - -pub fn cmd_init(c: &Cargo) { - let srcurl = ~"http://www.rust-lang.org/cargo/sources.json"; - let sigurl = ~"http://www.rust-lang.org/cargo/sources.json.sig"; - - let srcfile = c.root.push("sources.json.new"); - let sigfile = c.root.push("sources.json.sig"); - let destsrcfile = c.root.push("sources.json"); - - let p = - run::program_output(~"curl", ~[~"-f", ~"-s", - ~"-o", srcfile.to_str(), srcurl]); - if p.status != 0 { - error(fmt!("fetch of sources.json failed: %s", p.out)); - return; - } - - let p = - run::program_output(~"curl", ~[~"-f", ~"-s", - ~"-o", sigfile.to_str(), sigurl]); - if p.status != 0 { - error(fmt!("fetch of sources.json.sig failed: %s", p.out)); - return; - } - - let r = pgp::verify(&c.root, &srcfile, &sigfile); - if !r { - error(fmt!("signature verification failed for '%s'", - srcfile.to_str())); - return; - } - - copy_warn(&srcfile, &destsrcfile); - os::remove_file(&srcfile); - os::remove_file(&sigfile); - - info(fmt!("initialized .cargo in %s", c.root.to_str())); -} - -pub fn print_pkg(s: @Source, p: &Package) { - let mut m = s.name + ~"/" + p.name + ~" (" + p.uuid + ~")"; - if vec::len(p.tags) > 0u { - m = m + ~" [" + str::connect(p.tags, ~", ") + ~"]"; - } - info(m); - if p.description != ~"" { - print(~" >> " + p.description + ~"\n") - } -} - -pub fn print_source(s: @Source) { - info(s.name + ~" (" + s.url + ~")"); - - let pks = sort::merge_sort(s.packages.get(), sys::shape_lt); - let l = vec::len(pks); - - print(io::with_str_writer(|writer| { - let mut list = ~" >> "; - - for vec::eachi(pks) |i, pk| { - if str::len(list) > 78u { - writer.write_line(list); - list = ~" >> "; - } - list += pk.name + (if l - 1u == i { ~"" } else { ~", " }); - } - - writer.write_line(list); - })); -} - -pub fn cmd_list(c: &Cargo) { - sync(c); - - if vec::len(c.opts.free) >= 3u { - let v = vec::view(c.opts.free, 2u, vec::len(c.opts.free)); - for vec::each(v) |name| { - if !valid_pkg_name(*name) { - error(fmt!("'%s' is an invalid source name", *name)); - } else { - match c.sources.find(name) { - Some(source) => { - print_source(source); - } - None => { - error(fmt!("no such source: %s", *name)); - } - } - } - } - } else { - for c.sources.each_value |&v| { - print_source(v); - } - } -} - -pub fn cmd_search(c: &Cargo) { - if vec::len(c.opts.free) < 3u { - cmd_usage(); - return; - } - - sync(c); - - let mut n = 0; - let name = c.opts.free[2]; - let tags = vec::slice(c.opts.free, 3u, vec::len(c.opts.free)); - for_each_package(c, |s, p| { - if (str::contains(p.name, name) || name == ~"*") && - vec::all(tags, |t| vec::contains(p.tags, t) ) { - print_pkg(s, p); - n += 1; - } - }); - info(fmt!("found %d packages", n)); -} - -pub fn install_to_dir(srcfile: &Path, destdir: &Path) { - let newfile = destdir.push(srcfile.filename().get()); - - let status = run::run_program(~"cp", ~[~"-r", srcfile.to_str(), - newfile.to_str()]); - if status == 0 { - info(fmt!("installed: '%s'", newfile.to_str())); - } else { - error(fmt!("could not install: '%s'", newfile.to_str())); - } -} - -pub fn dump_cache(c: &Cargo) { - need_dir(&c.root); - - let out = c.root.push("cache.json"); - let _root = json::Object(~LinearMap::new()); - - if os::path_exists(&out) { - copy_warn(&out, &c.root.push("cache.json.old")); - } -} - -pub fn dump_sources(c: &Cargo) { - if c.sources.is_empty() { - return; - } - - need_dir(&c.root); - - let out = c.root.push("sources.json"); - - if os::path_exists(&out) { - copy_warn(&out, &c.root.push("sources.json.old")); - } - - match io::buffered_file_writer(&out) { - result::Ok(writer) => { - let mut hash = ~LinearMap::new(); - - for c.sources.each |&k, &v| { - let mut chash = ~LinearMap::new(); - - chash.insert(~"url", json::String(v.url)); - chash.insert(~"method", json::String(v.method)); - - match copy v.key { - Some(key) => { - chash.insert(~"key", json::String(copy key)); - } - _ => () - } - match copy v.keyfp { - Some(keyfp) => { - chash.insert(~"keyfp", json::String(copy keyfp)); - } - _ => () - } - - hash.insert(copy k, json::Object(move chash)); - } - - json::to_writer(writer, &json::Object(move hash)) - } - result::Err(e) => { - error(fmt!("could not dump sources: %s", e)); - } - } -} - -pub fn copy_warn(srcfile: &Path, destfile: &Path) { - if !os::copy_file(srcfile, destfile) { - warn(fmt!("copying %s to %s failed", - srcfile.to_str(), destfile.to_str())); - } -} - -pub fn cmd_sources(c: &Cargo) { - if vec::len(c.opts.free) < 3u { - for c.sources.each_value |&v| { - info(fmt!("%s (%s) via %s", - v.name, v.url, v.method)); - } - return; - } - - let action = c.opts.free[2u]; - - match action { - ~"clear" => { - for c.sources.each_key |&k| { - c.sources.remove(&k); - } - - info(~"cleared sources"); - } - ~"add" => { - if vec::len(c.opts.free) < 5u { - cmd_usage(); - return; - } - - let name = c.opts.free[3u]; - let url = c.opts.free[4u]; - - if !valid_pkg_name(name) { - error(fmt!("'%s' is an invalid source name", name)); - return; - } - - if c.sources.contains_key(&name) { - error(fmt!("source already exists: %s", name)); - } else { - c.sources.insert(name, @Source { - name: name, - mut url: url, - mut method: assume_source_method(url), - mut key: None, - mut keyfp: None, - packages: DVec() - }); - info(fmt!("added source: %s", name)); - } - } - ~"remove" => { - if vec::len(c.opts.free) < 4u { - cmd_usage(); - return; - } - - let name = c.opts.free[3u]; - - if !valid_pkg_name(name) { - error(fmt!("'%s' is an invalid source name", name)); - return; - } - - if c.sources.contains_key(&name) { - c.sources.remove(&name); - info(fmt!("removed source: %s", name)); - } else { - error(fmt!("no such source: %s", name)); - } - } - ~"set-url" => { - if vec::len(c.opts.free) < 5u { - cmd_usage(); - return; - } - - let name = c.opts.free[3u]; - let url = c.opts.free[4u]; - - if !valid_pkg_name(name) { - error(fmt!("'%s' is an invalid source name", name)); - return; - } - - match c.sources.find(&name) { - Some(source) => { - let old = copy source.url; - let method = assume_source_method(url); - - source.url = url; - source.method = method; - - c.sources.insert(name, source); - - info(fmt!("changed source url: '%s' to '%s'", old, url)); - } - None => { - error(fmt!("no such source: %s", name)); - } - } - } - ~"set-method" => { - if vec::len(c.opts.free) < 5u { - cmd_usage(); - return; - } - - let name = c.opts.free[3u]; - let method = c.opts.free[4u]; - - if !valid_pkg_name(name) { - error(fmt!("'%s' is an invalid source name", name)); - return; - } - - match c.sources.find(&name) { - Some(source) => { - let old = copy source.method; - - source.method = match method { - ~"git" => ~"git", - ~"file" => ~"file", - _ => ~"curl" - }; - - c.sources.insert(name, source); - - info(fmt!("changed source method: '%s' to '%s'", old, - method)); - } - None => { - error(fmt!("no such source: %s", name)); - } - } - } - ~"rename" => { - if vec::len(c.opts.free) < 5u { - cmd_usage(); - return; - } - - let name = c.opts.free[3u]; - let newn = c.opts.free[4u]; - - if !valid_pkg_name(name) { - error(fmt!("'%s' is an invalid source name", name)); - return; - } - if !valid_pkg_name(newn) { - error(fmt!("'%s' is an invalid source name", newn)); - return; - } - - match c.sources.find(&name) { - Some(source) => { - c.sources.remove(&name); - c.sources.insert(newn, source); - info(fmt!("renamed source: %s to %s", name, newn)); - } - None => { - error(fmt!("no such source: %s", name)); - } - } - } - _ => cmd_usage() - } -} - -pub fn cmd_usage() { - print(~"Usage: cargo [options] [args..] -e.g. cargo install - -Where is one of: - init, install, list, search, sources, - uninstall, usage - -Options: - - -h, --help Display this message - -h, --help Display help for -"); -} - -pub fn cmd_usage_init() { - print(~"cargo init - -Re-initialize cargo in ~/.cargo. Clears all sources and then adds the -default sources from ."); -} - -pub fn cmd_usage_install() { - print(~"cargo install -cargo install [source/][@version] -cargo install [source/][@version] -cargo install [ref] -cargo install -cargo install - -Options: - --test Run crate tests before installing - -g Install to the user level (~/.cargo/bin/ instead of - locally in ./.cargo/bin/ by default) - -G Install to the system level (/usr/local/lib/cargo/bin/) - -Install a crate. If no arguments are supplied, it installs from -the current working directory. If a source is provided, only install -from that source, otherwise it installs from any source."); -} - -pub fn cmd_usage_uninstall() { - print(~"cargo uninstall [source/][@version] -cargo uninstall [source/][@version] -cargo uninstall [@version] -cargo uninstall [@version] - -Options: - -g Remove from the user level (~/.cargo/bin/ instead of - locally in ./.cargo/bin/ by default) - -G Remove from the system level (/usr/local/lib/cargo/bin/) - -Remove a crate. If a source is provided, only remove -from that source, otherwise it removes from any source. -If a crate was installed directly (git, tarball, etc.), you can remove -it by metadata."); -} - -pub fn cmd_usage_list() { - print(~"cargo list [sources..] - -If no arguments are provided, list all sources and their packages. -If source names are provided, list those sources and their packages. -"); -} - -pub fn cmd_usage_search() { - print(~"cargo search [tags..] - -Search packages."); -} - -pub fn cmd_usage_sources() { - print(~"cargo sources -cargo sources add -cargo sources remove -cargo sources rename -cargo sources set-url -cargo sources set-method - -If no arguments are supplied, list all sources (but not their packages). - -Commands: - add Add a source. The source method will be guessed - from the URL. - remove Remove a source. - rename Rename a source. - set-url Change the URL for a source. - set-method Change the method for a source."); -} - -pub fn main() { - let argv = os::args(); - let o = build_cargo_options(argv); - - if vec::len(o.free) < 2u { - cmd_usage(); - return; - } - if o.help { - match o.free[1] { - ~"init" => cmd_usage_init(), - ~"install" => cmd_usage_install(), - ~"uninstall" => cmd_usage_uninstall(), - ~"list" => cmd_usage_list(), - ~"search" => cmd_usage_search(), - ~"sources" => cmd_usage_sources(), - _ => cmd_usage() - } - return; - } - if o.free[1] == ~"usage" { - cmd_usage(); - return; - } - - let mut c = configure(o); - let home = c.root; - let first_time = os::path_exists(&home.push("sources.json")); - - if !first_time && o.free[1] != ~"init" { - cmd_init(&c); - - // FIXME (#2662): shouldn't need to reconfigure - c = configure(o); - } - - match o.free[1] { - ~"init" => cmd_init(&c), - ~"install" => cmd_install(&mut c), - ~"uninstall" => cmd_uninstall(&c), - ~"list" => cmd_list(&c), - ~"search" => cmd_search(&c), - ~"sources" => cmd_sources(&c), - _ => cmd_usage() - } - - dump_cache(&c); - dump_sources(&c); -} - diff --git a/src/libcargo/pgp.rs b/src/libcargo/pgp.rs deleted file mode 100644 index 364effcd32f48..0000000000000 --- a/src/libcargo/pgp.rs +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use core::os; -use core::path::Path; -use core::run; - -pub fn gpgv(args: ~[~str]) -> run::ProgramOutput { - return run::program_output(~"gpgv", args); -} - -pub fn signing_key() -> ~str { - ~" ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: SKS 1.1.0 - -mQINBE7dQY0BEADYs5pHqXQugXjmgRTj0AzE3F4HAEJAiUBechVOmCgNcnW4dyb6bgj7Ctqs -Td/ZDSZkFwmsIqpwfGxMr+s9VA3PW+sEMDZPY+p8w3kvFPo/L2eRjSnQ+cPffdUPo+IXl96d -N/49iXs6/d7PHw+pYszdgCfpPAAo4TtLJLVCWRs1ETSbZBIUOFywgE5P71egYVMgYKndRM5K -cY0ZUsGUX9InpItuD3R7vFwDL9cUHBonOJoax+rYeM7eLQvNncl4YAwJsUKOVDBy28QK2wmz -R6MsBTX8+vRkj3ZTCnP1+RBNllViYnq6absnAgHFdQ6OL4T2wKhAaYhukE1foFTNNI1wAm4s -iYAI20Me+54xMQZa3QvrokL/Wf9+qeajEDOTZWs1T3Sn+H3Dg3T25b8WOH3ULZE7R4FPr0Id -5u95nxKG2D2fkMXDwc0BeG+VWh3lCdjOBn2kyT+6TwM9d+/VQmY4vZdZFhI6nCUlxeKEg4wk -HW6kad5QPcUlS/3flNHM0bVLPrmNDb61bm+2sYPpgw0iy7JA5m8MceG57jS7q6Mo001cIya8 -EqrfBLZ0/0eLyIH81/RjFYwEoI54+QWe0ovdsqNTVnQsCcZnIRFTbMQqdInuCqrROIn+00xe -L0KNMh0iQO4zRaG0XhQaUxt2mIbkA0PuntsM8+I9DUIAqXgttwARAQABtERSdXN0IExhbmd1 -YWdlIChUYWcgYW5kIFJlbGVhc2UgU2lnbmluZyBLZXkpIDxydXN0LWtleUBydXN0LWxhbmcu -b3JnPokCPgQTAQIAKAUCTt1BjQIbAwUJAeEzgAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AA -CgkQCy1qKDAzY3azFg//V+IoiCurdYyS4nckMbr9gTn5SKaAtQUqMWAoJty3/lZ2jLq/9zO0 -TO9Zw0rcoVUORpl4VsGsUu0QIA53KJJLOto4hHGvDBsASm4x1o06Ftsp37YrMozRN+4capIR -Kx5uM3whSUTGponOQplj9ED3zw/FkFWF4ni2KAZMfRJQy6berIBBHNWbMtY/vneTwv0YZOah -sS23AQ958mVhOfDYYnmpEzHza9kl6le9RjmxuFX0bOOB+bHE4T3X0OmB2q4RJetwd18qRGGY -dy/e5xON13Y708gV2v4t3ZC3X+XT/+dwHHjoa6nWIxI5OU59AfnjBJIs09pHq2VYUCfdZiHL -YRTrMQkUyapjOwWV5tbCtYnCufjILk2vk1YBqj1vjco0tMH7llsEoQ4seg8NrwkZYZ8jccN9 -Aymb0ObZZgSVJCFN3akUESfh9wPDAQjmLjqWAOMNDSpnElIVAxLX1O/HNgRv7tl0Te14Goul -lhrWzTg5vPpOhSe+1SVUAUVcBwHcZl1opXCHQHfW2vkfe9w1hRBqEMOmr54TBXufxneNc/te -NuV+ZA4l9QvirmGtmQee4LQwz7d//IFGVxidsbOTVOU9hbijm/USJCK1BPqF36I2rB/8ve7h -qTwTVbvMRb8qWS2YhwRHsYrngXbun1vwwFouiW2KV5NEFNMt3pj+Rcu5Ag0ETt1BjQEQAMOf -6oCHj5ASMHCdKzSGF+ofIG3OWH7SUVRDKtJck75LyjbW/14SxNQCF6UvyjwhVWnnGmXiCED6 -cCOo9UdMhF46ojWe//mszSJRZTc0OvUpq9AIe3UA7mLHve4A+8fXBd1mpgciG8qD4vifdO4T -yvkb4dwxW+hpsenKHaM4hvQJFB1c33loEeGdfE/9svZyCO9T4FA6tdj5niLdtGtcJ6eC/6rp -53kcg4RLz9hOH39ouitqIHVqO/j+TW2M8kYgh1niBCGQm2kV5jeh7QUMe7TA3KHksAVqAKcJ -4TO538KswbC8MLz4+cdHpXf+kSUNnRzyndazjIF31XSyT8cDZHdfFHFkCA/4Xr7ebp+gub6R -qbCeCbds/UQ8L7NOqze9/qGuRBLTarXmvZ0AgELu/z4bPF6GyKcJjFYkMZQoAzYZfFc2pNW+ -WhWCusAz0aw+6NoZVI6bYhfY2w+kf3vebpzuKdD0Qublk5cKFCU9bV6BYqI9PbgBkErUgrgp -Zrjkc2c2u6uje0sKRxihdczr75Kikhb3M4BKQx3V5GyKdvo+61MhYurwWtyTylgMvlyL+3Bn -r0bg/vFbdwO4wgdNjR9UkjjABjuTExdnAqvf2+eBnYkuzxG60TH5At3CRTBshNUO9N0q1SGH -tGJkDOOxEZwAnUmE9jAG9CdeWxJNaUa5ABEBAAGJAiUEGAECAA8FAk7dQY0CGwwFCQHhM4AA -CgkQCy1qKDAzY3a9NBAAqpQKlFBCJV2h8GJU68OzFdxYIelhzH0KcInm6QREiUtU2+WAAyli -IbvsEL3c0hH0xykhwZx0wPmj7QQW7h5geOTvfLhNe/XMLsnlIRXBCSZKmlsZ8HfOVAXZTY61 -LM0v11eI6w0lCUC6GqWfzpph+uxUQjJ6YrGomj7nDrvj8Dp4S4UYaJc+1pcVPjO/XmZrZkb1 -6KnTm4RJcIW0iO61g7SDn8JZCmrDf9Ur+9NmRdynEeiWn9DUkbAXTKj09NiRyV+8mVmSGw4F -Jylqtk+X4WTu7qCm9C0S3ROuSSJOkCQGcE552GaS5RN9wdL/cG1PfqQjSaY0HMQzpBzV+nXa -2eFk3Bg2/qi4OghjR00Y3SQftDWI4K3opwVdsF7u9YH6PQoX4jl5DJIvtdIwwQJVaHLjVF4r -koV3ryFlL4Oq70TLwBSUlUhYoii5pokr3GdzloUWuuBa8AK5sM0RG/pybUPWK1PQnDlJJg6H -JyEC4EFfBWv2+nwt1K+vIRuCX9ZSd5YP9F4RbQjsnz7dimo5ooy3Wj7Fv7lQnQGkaUev0+hs -t9H7RfQEyREukTMxzXjKEW9EO4lJ20cif3l7Be+bw6OzKaEkVE3reZRnKxO6SejUYA7reye1 -HI1jilzwKSXuV2EmyBk3tKh9NwscT/A78pr30FxxPUg3v72raNgusTo= -=2z6P ------END PGP PUBLIC KEY BLOCK----- -" -} - -pub fn signing_key_fp() -> ~str { - ~"FE79 EDB0 3DEF B0D8 27D2 6C41 0B2D 6A28 3033 6376" -} - -pub fn supported() -> bool { - let r = gpgv(~[~"--version"]); - r.status == 0 -} - -pub fn init(root: &Path) { - let p = root.push("gpg"); - if !os::path_is_dir(&p) { - os::make_dir(&p, 0x1c0i32); - let mut p = run::start_program(~"gpg", ~[~"--homedir", - p.to_str(), - ~"--import"]); - p.input().write_str(signing_key()); - let s = p.finish(); - if s != 0 { - fail!(~"pgp init failed"); - } - } -} - -pub fn add(root: &Path, key: &Path) { - let path = root.push("gpg"); - let p = - run::program_output(~"gpg", ~[~"--homedir", path.to_str(), - ~"--import", key.to_str()]); - if p.status != 0 { - fail!(~"pgp add failed: " + p.out); - } -} - -pub fn verify(root: &Path, data: &Path, sig: &Path) -> bool { - let path = root.push("gpg"); - let res = gpgv(~[~"--homedir", path.to_str(), - ~"--keyring", ~"pubring.gpg", - ~"--verbose", - sig.to_str(), data.to_str()]); - if res.status != 0 { - return false; - } - return true; -} diff --git a/src/libcargo/sources.json b/src/libcargo/sources.json deleted file mode 100644 index 66e14f9eff7d4..0000000000000 --- a/src/libcargo/sources.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "central": { - "url": "https://raw.github.com/mozilla/cargo-central/master/packages.json" - }, - "elly": { - "url": "https://raw.github.com/elly/rust-packages/master/packages.json", - "sig": "https://raw.github.com/elly/rust-packages/master/packages.json.sig", - "key": "https://raw.github.com/elly/rust-packages/master/signing-key.gpg", - "keyfp": "4107 21C0 FF32 858F 61FF 33F6 E595 8E36 FDC8 EA00" - }, - "erickt": { - "url": "https://raw.github.com/erickt/rust-packages/master/packages.json" - } -} diff --git a/src/libcore/at_vec.rs b/src/libcore/at_vec.rs index 75db5359e2e31..565fe11d3f4a8 100644 --- a/src/libcore/at_vec.rs +++ b/src/libcore/at_vec.rs @@ -173,7 +173,7 @@ pub mod traits { use kinds::Copy; use ops::Add; - pub impl @[T] : Add<&[const T],@[T]> { + pub impl Add<&[const T],@[T]> for @[T] { #[inline(always)] pure fn add(&self, rhs: & &self/[const T]) -> @[T] { append(*self, (*rhs)) @@ -229,12 +229,12 @@ pub mod raw { (**repr).unboxed.fill += sys::size_of::(); let p = addr_of(&((**repr).unboxed.data)); let p = ptr::offset(p, fill) as *mut T; - rusti::move_val_init(&mut(*p), move initval); + rusti::move_val_init(&mut(*p), initval); } pub unsafe fn push_slow(v: &mut @[const T], initval: T) { reserve_at_least(&mut *v, v.len() + 1u); - push_fast(v, move initval); + push_fast(v, initval); } /** diff --git a/src/libcore/cast.rs b/src/libcore/cast.rs index 14cc79ceaffed..22ed4f7694310 100644 --- a/src/libcore/cast.rs +++ b/src/libcore/cast.rs @@ -29,7 +29,7 @@ pub unsafe fn reinterpret_cast(src: &T) -> U { * reinterpret_cast on pointer types. */ #[inline(always)] -pub unsafe fn forget(thing: T) { rusti::forget(move thing); } +pub unsafe fn forget(thing: T) { rusti::forget(thing); } /** * Force-increment the reference count on a shared box. If used @@ -37,7 +37,7 @@ pub unsafe fn forget(thing: T) { rusti::forget(move thing); } * and/or reinterpret_cast when such calls would otherwise scramble a box's * reference count */ -pub unsafe fn bump_box_refcount(t: @T) { forget(move t); } +pub unsafe fn bump_box_refcount(t: @T) { forget(t); } /** * Transform a value of one type into a value of another type. @@ -50,23 +50,23 @@ pub unsafe fn bump_box_refcount(t: @T) { forget(move t); } #[inline(always)] pub unsafe fn transmute(thing: L) -> G { let newthing: G = reinterpret_cast(&thing); - forget(move thing); - move newthing + forget(thing); + newthing } /// Coerce an immutable reference to be mutable. #[inline(always)] -pub unsafe fn transmute_mut(ptr: &a/T) -> &a/mut T { transmute(move ptr) } +pub unsafe fn transmute_mut(ptr: &a/T) -> &a/mut T { transmute(ptr) } /// Coerce a mutable reference to be immutable. #[inline(always)] pub unsafe fn transmute_immut(ptr: &a/mut T) -> &a/T { - transmute(move ptr) + transmute(ptr) } /// Coerce a borrowed pointer to have an arbitrary associated region. #[inline(always)] -pub unsafe fn transmute_region(ptr: &a/T) -> &b/T { transmute(move ptr) } +pub unsafe fn transmute_region(ptr: &a/T) -> &b/T { transmute(ptr) } /// Coerce an immutable reference to be mutable. #[inline(always)] @@ -83,7 +83,7 @@ pub unsafe fn transmute_immut_unsafe(ptr: *const T) -> *T { /// Coerce a borrowed mutable pointer to have an arbitrary associated region. #[inline(always)] pub unsafe fn transmute_mut_region(ptr: &a/mut T) -> &b/mut T { - transmute(move ptr) + transmute(ptr) } /// Transforms lifetime of the second pointer to match the first. @@ -132,9 +132,9 @@ pub mod tests { use managed::raw::BoxRepr; unsafe { let x = @100u8; - let x: *BoxRepr = transmute(move x); + let x: *BoxRepr = transmute(x); assert (*x).data == 100; - let _x: @int = transmute(move x); + let _x: @int = transmute(x); } } diff --git a/src/libcore/core.rc b/src/libcore/core.rc index 5b6c40e09ef07..da13145b9f60f 100644 --- a/src/libcore/core.rc +++ b/src/libcore/core.rc @@ -170,7 +170,6 @@ pub mod condition; pub mod logging; pub mod util; - /* Reexported core operators */ pub use kinds::{Const, Copy, Owned, Durable}; diff --git a/src/libcore/dlist.rs b/src/libcore/dlist.rs index 0af0ecb16aa10..09de94f1aaf7d 100644 --- a/src/libcore/dlist.rs +++ b/src/libcore/dlist.rs @@ -493,7 +493,7 @@ impl DList { v[index] = *data; } } - move v + v } } diff --git a/src/libcore/dvec.rs b/src/libcore/dvec.rs index 0a96bd633d1ef..03a921d7ea504 100644 --- a/src/libcore/dvec.rs +++ b/src/libcore/dvec.rs @@ -67,18 +67,18 @@ pub pure fn DVec() -> DVec { /// Creates a new dvec with a single element pub pure fn from_elem(e: A) -> DVec { - DVec {mut data: ~[move e]} + DVec {mut data: ~[e]} } /// Creates a new dvec with the contents of a vector pub pure fn from_vec(v: ~[A]) -> DVec { - DVec {mut data: move v} + DVec {mut data: v} } /// Consumes the vector and returns its contents pub pure fn unwrap(d: DVec) -> ~[A] { - let DVec {data: v} = move d; - move v + let DVec {data: v} = d; + v } priv impl DVec { @@ -99,14 +99,14 @@ priv impl DVec { data <-> self.data; let data_ptr: *() = cast::reinterpret_cast(&data); if data_ptr.is_null() { fail!(~"Recursive use of dvec"); } - return f(move data); + return f(data); } } #[inline(always)] fn give_back(data: ~[A]) { unsafe { - self.data = move data; + self.data = data; } } @@ -130,7 +130,7 @@ impl DVec { */ #[inline(always)] fn swap(f: &fn(v: ~[A]) -> ~[A]) { - self.check_out(|v| self.give_back(f(move v))) + self.check_out(|v| self.give_back(f(v))) } /** @@ -141,7 +141,7 @@ impl DVec { #[inline(always)] fn swap_mut(f: &fn(v: ~[mut A]) -> ~[mut A]) { do self.swap |v| { - vec::cast_from_mut(f(vec::cast_to_mut(move v))) + vec::cast_from_mut(f(vec::cast_to_mut(v))) } } @@ -156,16 +156,16 @@ impl DVec { #[inline(always)] fn set(w: ~[A]) { self.check_not_borrowed(); - self.data = move w; + self.data = w; } /// Remove and return the last element fn pop() -> A { do self.check_out |v| { - let mut v = move v; + let mut v = v; let result = v.pop(); - self.give_back(move v); - move result + self.give_back(v); + result } } @@ -176,8 +176,8 @@ impl DVec { data <-> self.data; let data_ptr: *() = cast::reinterpret_cast(&data); if data_ptr.is_null() { fail!(~"Recursive use of dvec"); } - self.data = move ~[move t]; - self.data.push_all_move(move data); + self.data = ~[t]; + self.data.push_all_move(data); } } @@ -185,25 +185,25 @@ impl DVec { #[inline(always)] fn push(t: A) { self.check_not_borrowed(); - self.data.push(move t); + self.data.push(t); } /// Remove and return the first element fn shift() -> A { do self.check_out |v| { - let mut v = move v; + let mut v = v; let result = v.shift(); - self.give_back(move v); - move result + self.give_back(v); + result } } /// Reverse the elements in the list, in place fn reverse() { do self.check_out |v| { - let mut v = move v; + let mut v = v; vec::reverse(v); - self.give_back(move v); + self.give_back(v); } } @@ -211,18 +211,18 @@ impl DVec { fn borrow(op: fn(x: &[A]) -> R) -> R { do self.check_out |v| { let result = op(v); - self.give_back(move v); - move result + self.give_back(v); + result } } /// Gives access to the vector as a slice with mutable contents fn borrow_mut(op: fn(x: &[mut A]) -> R) -> R { do self.check_out |v| { - let mut v = move v; + let mut v = v; let result = op(v); - self.give_back(move v); - move result + self.give_back(v); + result } } } @@ -240,7 +240,7 @@ impl DVec { /// Appends elements from `from_idx` to `to_idx` (exclusive) fn push_slice(ts: &[const A], from_idx: uint, to_idx: uint) { do self.swap |v| { - let mut v = move v; + let mut v = v; let new_len = vec::len(v) + to_idx - from_idx; vec::reserve(&mut v, new_len); let mut i = from_idx; @@ -248,7 +248,7 @@ impl DVec { v.push(ts[i]); i += 1u; } - move v + v } } @@ -265,7 +265,7 @@ impl DVec { none { v } Some(h) { let len = v.len() + h; - let mut v = move v; + let mut v = v; vec::reserve(v, len); v } @@ -286,8 +286,8 @@ impl DVec { unsafe { do self.check_out |v| { let w = copy v; - self.give_back(move v); - move w + self.give_back(v); + w } } } @@ -312,9 +312,9 @@ impl DVec { */ fn grow_set_elt(idx: uint, initval: &A, val: A) { do self.swap |v| { - let mut v = move v; + let mut v = v; v.grow_set(idx, initval, val); - move v + v } } @@ -340,7 +340,7 @@ impl DVec { for vec::rev_each(v) |e| { if !f(e) { break; } } - move v + v } } @@ -353,7 +353,7 @@ impl DVec { for vec::rev_eachi(v) |i, e| { if !f(i, e) { break; } } - move v + v } } } diff --git a/src/libcore/either.rs b/src/libcore/either.rs index 54c9f7b98793b..72aecdd82954f 100644 --- a/src/libcore/either.rs +++ b/src/libcore/either.rs @@ -84,7 +84,7 @@ pub fn partition(eithers: ~[Either]) Right(r) => rights.push(r) } } - return (move lefts, move rights); + return (lefts, rights); } #[inline(always)] @@ -131,8 +131,8 @@ pub pure fn is_right(eith: &Either) -> bool { pub pure fn unwrap_left(eith: Either) -> T { //! Retrieves the value in the left branch. Fails if the either is Right. - match move eith { - Left(move x) => move x, + match eith { + Left(x) => x, Right(_) => fail!(~"either::unwrap_left Right") } } @@ -141,8 +141,8 @@ pub pure fn unwrap_left(eith: Either) -> T { pub pure fn unwrap_right(eith: Either) -> U { //! Retrieves the value in the right branch. Fails if the either is Left. - match move eith { - Right(move x) => move x, + match eith { + Right(x) => x, Left(_) => fail!(~"either::unwrap_right Left") } } diff --git a/src/libcore/extfmt.rs b/src/libcore/extfmt.rs index 3dbc3bef01733..36ea67ea6954e 100644 --- a/src/libcore/extfmt.rs +++ b/src/libcore/extfmt.rs @@ -510,7 +510,7 @@ pub mod rt { unsafe { str::unshift_char(&mut s, ' ') }; } } - return unsafe { pad(cv, move s, PadSigned) }; + return unsafe { pad(cv, s, PadSigned) }; } pub pure fn conv_uint(cv: Conv, u: uint) -> ~str { let prec = get_int_precision(cv); @@ -522,7 +522,7 @@ pub mod rt { TyBits => uint_to_str_prec(u, 2, prec), TyOctal => uint_to_str_prec(u, 8, prec) }; - return unsafe { pad(cv, move rs, PadUnsigned) }; + return unsafe { pad(cv, rs, PadUnsigned) }; } pub pure fn conv_bool(cv: Conv, b: bool) -> ~str { let s = if b { ~"true" } else { ~"false" }; @@ -532,7 +532,7 @@ pub mod rt { } pub pure fn conv_char(cv: Conv, c: char) -> ~str { let mut s = str::from_char(c); - return unsafe { pad(cv, move s, PadNozero) }; + return unsafe { pad(cv, s, PadNozero) }; } pub pure fn conv_str(cv: Conv, s: &str) -> ~str { // For strings, precision is the maximum characters @@ -545,7 +545,7 @@ pub mod rt { s.to_owned() } }; - return unsafe { pad(cv, move unpadded, PadNozero) }; + return unsafe { pad(cv, unpadded, PadNozero) }; } pub pure fn conv_float(cv: Conv, f: float) -> ~str { let (to_str, digits) = match cv.precision { @@ -560,7 +560,7 @@ pub mod rt { s = ~" " + s; } } - return unsafe { pad(cv, move s, PadFloat) }; + return unsafe { pad(cv, s, PadFloat) }; } pub pure fn conv_poly(cv: Conv, v: &T) -> ~str { let s = sys::log_str(v); @@ -589,7 +589,7 @@ pub mod rt { let diff = prec - len; let pad = str::from_chars(vec::from_elem(diff, '0')); pad + s - } else { move s } + } else { s } }; } pub pure fn get_int_precision(cv: Conv) -> uint { @@ -603,13 +603,13 @@ pub mod rt { pub enum PadMode { PadSigned, PadUnsigned, PadNozero, PadFloat } pub fn pad(cv: Conv, s: ~str, mode: PadMode) -> ~str { - let mut s = move s; // sadtimes + let mut s = s; // sadtimes let uwidth : uint = match cv.width { - CountImplied => return (move s), + CountImplied => return (s), CountIs(width) => { width as uint } }; let strlen = str::char_len(s); - if uwidth <= strlen { return (move s); } + if uwidth <= strlen { return (s); } let mut padchar = ' '; let diff = uwidth - strlen; if have_flag(cv.flags, flag_left_justify) { diff --git a/src/libcore/flate.rs b/src/libcore/flate.rs index 6b5c083662b84..c47e27e75d950 100644 --- a/src/libcore/flate.rs +++ b/src/libcore/flate.rs @@ -50,7 +50,7 @@ pub fn deflate_bytes(bytes: &[const u8]) -> ~[u8] { let out = vec::raw::from_buf_raw(res as *u8, outsz as uint); libc::free(res); - move out + out } } } @@ -68,7 +68,7 @@ pub fn inflate_bytes(bytes: &[const u8]) -> ~[u8] { let out = vec::raw::from_buf_raw(res as *u8, outsz as uint); libc::free(res); - move out + out } } } diff --git a/src/libcore/hash.rs b/src/libcore/hash.rs index b4f4e7d343b0a..40a9de0cea349 100644 --- a/src/libcore/hash.rs +++ b/src/libcore/hash.rs @@ -183,7 +183,7 @@ fn SipState(key0: u64, key1: u64) -> SipState { mut ntail : 0u, }; (&state).reset(); - move state + state } @@ -352,7 +352,7 @@ impl Streaming for &SipState { for vec::each(r) |b| { s += uint::to_str_radix(*b as uint, 16u); } - move s + s } #[inline(always)] @@ -447,7 +447,7 @@ pub fn test_siphash() { for vec::each(*r) |b| { s += uint::to_str_radix(*b as uint, 16u); } - move s + s } while t < 64 { diff --git a/src/libcore/hashmap.rs b/src/libcore/hashmap.rs index 1e9f05a35ebdc..9cc7c2b760c55 100644 --- a/src/libcore/hashmap.rs +++ b/src/libcore/hashmap.rs @@ -51,6 +51,7 @@ pub mod linear { FoundEntry(uint), FoundHole(uint), TableFull } + #[inline(always)] pure fn resize_at(capacity: uint) -> uint { ((capacity as float) * 3. / 4.) as uint } @@ -76,10 +77,8 @@ pub mod linear { priv impl LinearMap { #[inline(always)] pure fn to_bucket(&self, h: uint) -> uint { - // FIXME(#3041) borrow a more sophisticated technique here from - // Gecko, for example borrowing from Knuth, as Eich so - // colorfully argues for here: - // https://bugzilla.mozilla.org/show_bug.cgi?id=743107#c22 + // A good hash function with entropy spread over all of the + // bits is assumed. SipHash is more than good enough. h % self.buckets.len() } @@ -128,12 +127,19 @@ pub mod linear { TableFull } - /// Expands the capacity of the array and re-inserts each - /// of the existing buckets. + /// Expand the capacity of the array to the next power of two + /// and re-insert each of the existing buckets. + #[inline(always)] fn expand(&mut self) { + let new_capacity = self.buckets.len() * 2; + self.resize(new_capacity); + } + + /// Expands the capacity of the array and re-insert each of the + /// existing buckets. + fn resize(&mut self, new_capacity: uint) { let old_capacity = self.buckets.len(); - let new_capacity = old_capacity * 2; - self.resize_at = ((new_capacity as float) * 3.0 / 4.0) as uint; + self.resize_at = resize_at(new_capacity); let mut old_buckets = vec::from_fn(new_capacity, |_| None); self.buckets <-> old_buckets; @@ -159,7 +165,7 @@ pub mod linear { pure fn value_for_bucket(&self, idx: uint) -> &self/V { match self.buckets[idx] { Some(ref bkt) => &bkt.value, - None => die!(~"LinearMap::find: internal logic error"), + None => fail!(~"LinearMap::find: internal logic error"), } } @@ -333,6 +339,14 @@ pub mod linear { linear_map_with_capacity(INITIAL_CAPACITY) } + /// Reserve space for at least `n` elements in the hash table. + fn reserve_at_least(&mut self, n: uint) { + if n > self.buckets.len() { + let buckets = n * 4 / 3 + 1; + self.resize(uint::next_power_of_two(buckets)); + } + } + fn pop(&mut self, k: &K) -> Option { let hash = k.hash_keyed(self.k0, self.k1) as uint; self.pop_internal(hash, k) @@ -373,7 +387,7 @@ pub mod linear { let hash = k.hash_keyed(self.k0, self.k1) as uint; let idx = match self.bucket_for_key_with_hash(hash, &k) { - TableFull => die!(~"Internal logic error"), + TableFull => fail!(~"Internal logic error"), FoundEntry(idx) => idx, FoundHole(idx) => { self.buckets[idx] = Some(Bucket{hash: hash, key: k, @@ -403,7 +417,7 @@ pub mod linear { let hash = k.hash_keyed(self.k0, self.k1) as uint; let idx = match self.bucket_for_key_with_hash(hash, &k) { - TableFull => die!(~"Internal logic error"), + TableFull => fail!(~"Internal logic error"), FoundEntry(idx) => idx, FoundHole(idx) => { let v = f(&k); @@ -564,6 +578,11 @@ pub mod linear { pub impl LinearSet { /// Create an empty LinearSet static fn new() -> LinearSet { LinearSet{map: LinearMap::new()} } + + /// Reserve space for at least `n` elements in the hash table. + fn reserve_at_least(&mut self, n: uint) { + self.map.reserve_at_least(n) + } } } diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 2173efe5ac66f..6739c5b852e1d 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -178,7 +178,7 @@ impl ReaderUtil for T { let count = self.read(bytes, len); unsafe { vec::raw::set_len(&mut bytes, count); } - move bytes + bytes } fn read_line(&self) -> ~str { @@ -246,10 +246,10 @@ impl ReaderUtil for T { // over-read by reading 1-byte per char needed nbread = if ncreq > nbreq { ncreq } else { nbreq }; if nbread > 0 { - bytes = vec::slice(bytes, offset, bytes.len()); + bytes = vec::slice(bytes, offset, bytes.len()).to_vec(); } } - move chars + chars } fn read_char(&self) -> char { @@ -273,7 +273,7 @@ impl ReaderUtil for T { fn read_whole_stream(&self) -> ~[u8] { let mut bytes: ~[u8] = ~[]; while !self.eof() { bytes.push_all(self.read_bytes(2048u)); } - move bytes + bytes } fn each_byte(&self, it: fn(int) -> bool) { @@ -531,7 +531,7 @@ impl Reader for BytesReader { fn read(&self, bytes: &mut [u8], len: uint) -> uint { let count = uint::min(len, self.bytes.len() - self.pos); - let view = vec::view(self.bytes, self.pos, self.bytes.len()); + let view = vec::slice(self.bytes, self.pos, self.bytes.len()); vec::bytes::copy_memory(bytes, view, count); self.pos += count; @@ -999,7 +999,7 @@ pub struct BytesWriter { impl Writer for BytesWriter { fn write(&self, v: &[const u8]) { do self.bytes.swap |bytes| { - let mut bytes = move bytes; + let mut bytes = bytes; let v_len = v.len(); let bytes_len = bytes.len(); @@ -1008,13 +1008,13 @@ impl Writer for BytesWriter { unsafe { vec::raw::set_len(&mut bytes, count); } { - let view = vec::mut_view(bytes, self.pos, count); + let view = vec::mut_slice(bytes, self.pos, count); vec::bytes::copy_memory(view, v, v_len); } self.pos += v_len; - move bytes + bytes } } fn seek(&self, offset: int, whence: SeekStyle) { @@ -1035,7 +1035,7 @@ pub pure fn with_bytes_writer(f: fn(Writer)) -> ~[u8] { let wr = @BytesWriter(); f(wr as Writer); // FIXME (#3758): This should not be needed. - unsafe { wr.bytes.check_out(|bytes| move bytes) } + unsafe { wr.bytes.check_out(|bytes| bytes) } } pub pure fn with_str_writer(f: fn(Writer)) -> ~str { @@ -1048,7 +1048,7 @@ pub pure fn with_str_writer(f: fn(Writer)) -> ~str { } assert str::is_utf8(v); - unsafe { move ::cast::transmute(move v) } + unsafe { ::cast::transmute(v) } } // Utility functions @@ -1126,7 +1126,7 @@ pub mod fsync { pub fn Res(arg: Arg) -> Res{ Res { - arg: move arg + arg: arg } } diff --git a/src/libcore/iter-trait.rs b/src/libcore/iter-trait.rs index 7c2b5d7ffcd40..9a8f01baed1eb 100644 --- a/src/libcore/iter-trait.rs +++ b/src/libcore/iter-trait.rs @@ -42,7 +42,7 @@ impl iter::ExtendedIter for IMPL_T { } #[inline(always)] pure fn foldl(&self, b0: B, blk: fn(&B, &A) -> B) -> B { - iter::foldl(self, move b0, blk) + iter::foldl(self, b0, blk) } #[inline(always)] pure fn position(&self, f: fn(&A) -> bool) -> Option { diff --git a/src/libcore/iter-trait/dvec.rs b/src/libcore/iter-trait/dvec.rs index af788989e9c0f..986aa18ad4ab1 100644 --- a/src/libcore/iter-trait/dvec.rs +++ b/src/libcore/iter-trait/dvec.rs @@ -25,7 +25,7 @@ mod inst { unsafe { do self.swap |v| { v.each(f); - move v + v } } } diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index a36fa56fc79ba..25cdb11456a06 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -154,11 +154,11 @@ pub pure fn flat_map_to_vec,IB:BaseIter>( pub pure fn foldl>(self: &IA, b0: B, blk: fn(&B, &A) -> B) -> B { - let mut b = move b0; + let mut b = b0; for self.each |a| { b = blk(&b, a); } - move b + b } #[inline(always)] @@ -215,12 +215,12 @@ pub pure fn min>(self: &IA) -> A { match do foldl::,IA>(self, None) |a, b| { match a { &Some(ref a_) if *a_ < *b => { - *(move a) + *(a) } _ => Some(*b) } } { - Some(move val) => val, + Some(val) => val, None => fail!(~"min called on empty iterator") } } @@ -230,12 +230,12 @@ pub pure fn max>(self: &IA) -> A { match do foldl::,IA>(self, None) |a, b| { match a { &Some(ref a_) if *a_ > *b => { - *(move a) + *(a) } _ => Some(*b) } } { - Some(move val) => val, + Some(val) => val, None => fail!(~"max called on empty iterator") } } diff --git a/src/libcore/mutable.rs b/src/libcore/mutable.rs index 49e0d0bdd8a65..1fb855520ba49 100644 --- a/src/libcore/mutable.rs +++ b/src/libcore/mutable.rs @@ -32,15 +32,15 @@ struct Data { pub type Mut = Data; pub fn Mut(t: T) -> Mut { - Data {value: move t, mode: ReadOnly} + Data {value: t, mode: ReadOnly} } pub fn unwrap(m: Mut) -> T { // Borrowck should prevent us from calling unwrap while the value // is in use, as that would be a move from a borrowed value. assert (m.mode as uint) == (ReadOnly as uint); - let Data {value: move value, mode: _} = move m; - move value + let Data {value: value, mode: _} = m; + value } impl Data { diff --git a/src/libcore/num/f32.rs b/src/libcore/num/f32.rs index 8350ba42591d7..2189f109eff69 100644 --- a/src/libcore/num/f32.rs +++ b/src/libcore/num/f32.rs @@ -14,6 +14,7 @@ use cmath; use cmp; use libc::{c_float, c_int}; use num::NumCast; +use num::strconv; use num; use ops; use option::Option; @@ -282,7 +283,7 @@ impl num::One for f32 { static pure fn one() -> f32 { 1.0 } } -pub impl f32: NumCast { +pub impl NumCast for f32 { /** * Cast `n` to an `f32` */ @@ -376,8 +377,8 @@ impl num::Round for f32 { */ #[inline(always)] pub pure fn to_str(num: f32) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigAll); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigAll); r } @@ -390,8 +391,8 @@ pub pure fn to_str(num: f32) -> ~str { */ #[inline(always)] pub pure fn to_str_hex(num: f32) -> ~str { - let (r, _) = num::to_str_common( - &num, 16u, true, true, num::SignNeg, num::DigAll); + let (r, _) = strconv::to_str_common( + &num, 16u, true, strconv::SignNeg, strconv::DigAll); r } @@ -411,8 +412,8 @@ pub pure fn to_str_hex(num: f32) -> ~str { */ #[inline(always)] pub pure fn to_str_radix(num: f32, rdx: uint) -> ~str { - let (r, special) = num::to_str_common( - &num, rdx, true, true, num::SignNeg, num::DigAll); + let (r, special) = strconv::to_str_common( + &num, rdx, true, strconv::SignNeg, strconv::DigAll); if special { fail!(~"number has a special value, \ try to_str_radix_special() if those are expected") } r @@ -429,7 +430,8 @@ pub pure fn to_str_radix(num: f32, rdx: uint) -> ~str { */ #[inline(always)] pub pure fn to_str_radix_special(num: f32, rdx: uint) -> (~str, bool) { - num::to_str_common(&num, rdx, true, true, num::SignNeg, num::DigAll) + strconv::to_str_common(&num, rdx, true, + strconv::SignNeg, strconv::DigAll) } /** @@ -443,8 +445,8 @@ pub pure fn to_str_radix_special(num: f32, rdx: uint) -> (~str, bool) { */ #[inline(always)] pub pure fn to_str_exact(num: f32, dig: uint) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigExact(dig)); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigExact(dig)); r } @@ -459,8 +461,8 @@ pub pure fn to_str_exact(num: f32, dig: uint) -> ~str { */ #[inline(always)] pub pure fn to_str_digits(num: f32, dig: uint) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigMax(dig)); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigMax(dig)); r } @@ -505,7 +507,8 @@ impl num::ToStrRadix for f32 { */ #[inline(always)] pub pure fn from_str(num: &str) -> Option { - num::from_str_common(num, 10u, true, true, true, num::ExpDec, false) + strconv::from_str_common(num, 10u, true, true, true, + strconv::ExpDec, false) } /** @@ -537,7 +540,8 @@ pub pure fn from_str(num: &str) -> Option { */ #[inline(always)] pub pure fn from_str_hex(num: &str) -> Option { - num::from_str_common(num, 16u, true, true, true, num::ExpBin, false) + strconv::from_str_common(num, 16u, true, true, true, + strconv::ExpBin, false) } /** @@ -561,7 +565,8 @@ pub pure fn from_str_hex(num: &str) -> Option { */ #[inline(always)] pub pure fn from_str_radix(num: &str, rdx: uint) -> Option { - num::from_str_common(num, rdx, true, true, false, num::ExpNone, false) + strconv::from_str_common(num, rdx, true, true, false, + strconv::ExpNone, false) } impl from_str::FromStr for f32 { diff --git a/src/libcore/num/f64.rs b/src/libcore/num/f64.rs index 474067a1860c8..df68b6153cb42 100644 --- a/src/libcore/num/f64.rs +++ b/src/libcore/num/f64.rs @@ -15,6 +15,7 @@ use cmp; use libc::{c_double, c_int}; use libc; use num::NumCast; +use num::strconv; use num; use ops; use option::Option; @@ -297,7 +298,7 @@ impl cmp::Ord for f64 { pure fn gt(&self, other: &f64) -> bool { (*self) > (*other) } } -pub impl f64: NumCast { +pub impl NumCast for f64 { /** * Cast `n` to an `f64` */ @@ -401,8 +402,8 @@ impl num::Round for f64 { */ #[inline(always)] pub pure fn to_str(num: f64) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigAll); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigAll); r } @@ -415,8 +416,8 @@ pub pure fn to_str(num: f64) -> ~str { */ #[inline(always)] pub pure fn to_str_hex(num: f64) -> ~str { - let (r, _) = num::to_str_common( - &num, 16u, true, true, num::SignNeg, num::DigAll); + let (r, _) = strconv::to_str_common( + &num, 16u, true, strconv::SignNeg, strconv::DigAll); r } @@ -436,8 +437,8 @@ pub pure fn to_str_hex(num: f64) -> ~str { */ #[inline(always)] pub pure fn to_str_radix(num: f64, rdx: uint) -> ~str { - let (r, special) = num::to_str_common( - &num, rdx, true, true, num::SignNeg, num::DigAll); + let (r, special) = strconv::to_str_common( + &num, rdx, true, strconv::SignNeg, strconv::DigAll); if special { fail!(~"number has a special value, \ try to_str_radix_special() if those are expected") } r @@ -454,7 +455,8 @@ pub pure fn to_str_radix(num: f64, rdx: uint) -> ~str { */ #[inline(always)] pub pure fn to_str_radix_special(num: f64, rdx: uint) -> (~str, bool) { - num::to_str_common(&num, rdx, true, true, num::SignNeg, num::DigAll) + strconv::to_str_common(&num, rdx, true, + strconv::SignNeg, strconv::DigAll) } /** @@ -468,8 +470,8 @@ pub pure fn to_str_radix_special(num: f64, rdx: uint) -> (~str, bool) { */ #[inline(always)] pub pure fn to_str_exact(num: f64, dig: uint) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigExact(dig)); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigExact(dig)); r } @@ -484,8 +486,8 @@ pub pure fn to_str_exact(num: f64, dig: uint) -> ~str { */ #[inline(always)] pub pure fn to_str_digits(num: f64, dig: uint) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigMax(dig)); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigMax(dig)); r } @@ -530,7 +532,8 @@ impl num::ToStrRadix for f64 { */ #[inline(always)] pub pure fn from_str(num: &str) -> Option { - num::from_str_common(num, 10u, true, true, true, num::ExpDec, false) + strconv::from_str_common(num, 10u, true, true, true, + strconv::ExpDec, false) } /** @@ -562,7 +565,8 @@ pub pure fn from_str(num: &str) -> Option { */ #[inline(always)] pub pure fn from_str_hex(num: &str) -> Option { - num::from_str_common(num, 16u, true, true, true, num::ExpBin, false) + strconv::from_str_common(num, 16u, true, true, true, + strconv::ExpBin, false) } /** @@ -586,7 +590,8 @@ pub pure fn from_str_hex(num: &str) -> Option { */ #[inline(always)] pub pure fn from_str_radix(num: &str, rdx: uint) -> Option { - num::from_str_common(num, rdx, true, true, false, num::ExpNone, false) + strconv::from_str_common(num, rdx, true, true, false, + strconv::ExpNone, false) } impl from_str::FromStr for f64 { diff --git a/src/libcore/num/float.rs b/src/libcore/num/float.rs index 0f0b721e4626a..b857f76570ff5 100644 --- a/src/libcore/num/float.rs +++ b/src/libcore/num/float.rs @@ -26,6 +26,7 @@ use cmp::{Eq, Ord}; use cmp; use f64; use num::NumCast; +use num::strconv; use num; use ops; use option::{None, Option, Some}; @@ -107,8 +108,8 @@ pub mod consts { */ #[inline(always)] pub pure fn to_str(num: float) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigAll); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigAll); r } @@ -121,8 +122,8 @@ pub pure fn to_str(num: float) -> ~str { */ #[inline(always)] pub pure fn to_str_hex(num: float) -> ~str { - let (r, _) = num::to_str_common( - &num, 16u, true, true, num::SignNeg, num::DigAll); + let (r, _) = strconv::to_str_common( + &num, 16u, true, strconv::SignNeg, strconv::DigAll); r } @@ -142,8 +143,8 @@ pub pure fn to_str_hex(num: float) -> ~str { */ #[inline(always)] pub pure fn to_str_radix(num: float, radix: uint) -> ~str { - let (r, special) = num::to_str_common( - &num, radix, true, true, num::SignNeg, num::DigAll); + let (r, special) = strconv::to_str_common( + &num, radix, true, strconv::SignNeg, strconv::DigAll); if special { fail!(~"number has a special value, \ try to_str_radix_special() if those are expected") } r @@ -160,7 +161,8 @@ pub pure fn to_str_radix(num: float, radix: uint) -> ~str { */ #[inline(always)] pub pure fn to_str_radix_special(num: float, radix: uint) -> (~str, bool) { - num::to_str_common(&num, radix, true, true, num::SignNeg, num::DigAll) + strconv::to_str_common(&num, radix, true, + strconv::SignNeg, strconv::DigAll) } /** @@ -174,8 +176,8 @@ pub pure fn to_str_radix_special(num: float, radix: uint) -> (~str, bool) { */ #[inline(always)] pub pure fn to_str_exact(num: float, digits: uint) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigExact(digits)); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigExact(digits)); r } @@ -196,8 +198,8 @@ pub fn test_to_str_exact_do_decimal() { */ #[inline(always)] pub pure fn to_str_digits(num: float, digits: uint) -> ~str { - let (r, _) = num::to_str_common( - &num, 10u, true, true, num::SignNeg, num::DigMax(digits)); + let (r, _) = strconv::to_str_common( + &num, 10u, true, strconv::SignNeg, strconv::DigMax(digits)); r } @@ -242,7 +244,8 @@ impl num::ToStrRadix for float { */ #[inline(always)] pub pure fn from_str(num: &str) -> Option { - num::from_str_common(num, 10u, true, true, true, num::ExpDec, false) + strconv::from_str_common(num, 10u, true, true, true, + strconv::ExpDec, false) } /** @@ -274,7 +277,8 @@ pub pure fn from_str(num: &str) -> Option { */ #[inline(always)] pub pure fn from_str_hex(num: &str) -> Option { - num::from_str_common(num, 16u, true, true, true, num::ExpBin, false) + strconv::from_str_common(num, 16u, true, true, true, + strconv::ExpBin, false) } /** @@ -298,7 +302,8 @@ pub pure fn from_str_hex(num: &str) -> Option { */ #[inline(always)] pub pure fn from_str_radix(num: &str, radix: uint) -> Option { - num::from_str_common(num, radix, true, true, false, num::ExpNone, false) + strconv::from_str_common(num, radix, true, true, false, + strconv::ExpNone, false) } impl from_str::FromStr for float { @@ -415,7 +420,7 @@ impl num::One for float { static pure fn one() -> float { 1.0 } } -pub impl float: NumCast { +pub impl NumCast for float { /** * Cast `n` to a `float` */ diff --git a/src/libcore/num/int-template.rs b/src/libcore/num/int-template.rs index eaaa78b84f837..8d72878ef6acb 100644 --- a/src/libcore/num/int-template.rs +++ b/src/libcore/num/int-template.rs @@ -16,6 +16,7 @@ use cmp; use to_str::ToStr; use from_str::FromStr; use num::{ToStrRadix, FromStrRadix}; +use num::strconv; use num; use prelude::*; use str; @@ -176,18 +177,6 @@ impl num::One for T { static pure fn one() -> T { 1 } } -impl num::Round for T { - #[inline(always)] - pure fn round(&self, _: num::RoundMode) -> T { *self } - - #[inline(always)] - pure fn floor(&self) -> T { *self } - #[inline(always)] - pure fn ceil(&self) -> T { *self } - #[inline(always)] - pure fn fract(&self) -> T { 0 } -} - #[cfg(notest)] impl ops::Add for T { pure fn add(&self, other: &T) -> T { *self + *other } @@ -218,22 +207,22 @@ impl ops::Neg for T { /// Parse a string as a number in base 10. #[inline(always)] pub pure fn from_str(s: &str) -> Option { - num::from_str_common(s, 10u, true, false, false, - num::ExpNone, false) + strconv::from_str_common(s, 10u, true, false, false, + strconv::ExpNone, false) } /// Parse a string as a number in the given base. #[inline(always)] pub pure fn from_str_radix(s: &str, radix: uint) -> Option { - num::from_str_common(s, radix, true, false, false, - num::ExpNone, false) + strconv::from_str_common(s, radix, true, false, false, + strconv::ExpNone, false) } /// Parse a byte slice as a number in the given base. #[inline(always)] pub pure fn parse_bytes(buf: &[u8], radix: uint) -> Option { - num::from_str_bytes_common(buf, radix, true, false, false, - num::ExpNone, false) + strconv::from_str_bytes_common(buf, radix, true, false, false, + strconv::ExpNone, false) } impl FromStr for T { @@ -255,24 +244,24 @@ impl FromStrRadix for T { /// Convert to a string as a byte slice in a given base. #[inline(always)] pub pure fn to_str_bytes(n: T, radix: uint, f: fn(v: &[u8]) -> U) -> U { - let (buf, _) = num::to_str_bytes_common(&n, radix, false, false, - num::SignNeg, num::DigAll); + let (buf, _) = strconv::to_str_bytes_common(&n, radix, false, + strconv::SignNeg, strconv::DigAll); f(buf) } /// Convert to a string in base 10. #[inline(always)] pub pure fn to_str(num: T) -> ~str { - let (buf, _) = num::to_str_common(&num, 10u, false, false, - num::SignNeg, num::DigAll); + let (buf, _) = strconv::to_str_common(&num, 10u, false, + strconv::SignNeg, strconv::DigAll); buf } /// Convert to a string in a given base. #[inline(always)] pub pure fn to_str_radix(num: T, radix: uint) -> ~str { - let (buf, _) = num::to_str_common(&num, radix, false, false, - num::SignNeg, num::DigAll); + let (buf, _) = strconv::to_str_common(&num, radix, false, + strconv::SignNeg, strconv::DigAll); buf } diff --git a/src/libcore/num/int-template/i16.rs b/src/libcore/num/int-template/i16.rs index 76725e3895b55..1352959306a03 100644 --- a/src/libcore/num/int-template/i16.rs +++ b/src/libcore/num/int-template/i16.rs @@ -17,7 +17,7 @@ mod inst { pub const bits: uint = ::u16::bits; } -pub impl i16: NumCast { +pub impl NumCast for i16 { /** * Cast `n` to a `i16` */ diff --git a/src/libcore/num/int-template/i32.rs b/src/libcore/num/int-template/i32.rs index 1c2d60a80ee2b..e8dd603d50753 100644 --- a/src/libcore/num/int-template/i32.rs +++ b/src/libcore/num/int-template/i32.rs @@ -17,7 +17,7 @@ mod inst { pub const bits: uint = ::u32::bits; } -pub impl i32: NumCast { +pub impl NumCast for i32 { /** * Cast `n` to a `i32` */ diff --git a/src/libcore/num/int-template/i64.rs b/src/libcore/num/int-template/i64.rs index d7413920a64f1..6f1371f8ee221 100644 --- a/src/libcore/num/int-template/i64.rs +++ b/src/libcore/num/int-template/i64.rs @@ -17,7 +17,7 @@ mod inst { pub const bits: uint = ::u64::bits; } -pub impl i64: NumCast { +pub impl NumCast for i64 { /** * Cast `n` to a `i64` */ diff --git a/src/libcore/num/int-template/i8.rs b/src/libcore/num/int-template/i8.rs index f2577020128bd..46c734b95483e 100644 --- a/src/libcore/num/int-template/i8.rs +++ b/src/libcore/num/int-template/i8.rs @@ -17,7 +17,7 @@ mod inst { pub const bits: uint = ::u8::bits; } -pub impl i8: NumCast { +pub impl NumCast for i8 { /** * Cast `n` to a `i8` */ diff --git a/src/libcore/num/int-template/int.rs b/src/libcore/num/int-template/int.rs index 4ba1570e1359a..83ef421b70578 100644 --- a/src/libcore/num/int-template/int.rs +++ b/src/libcore/num/int-template/int.rs @@ -58,7 +58,7 @@ mod inst { } } -pub impl int: NumCast { +pub impl NumCast for int { /** * Cast `n` to a `int` */ diff --git a/src/libcore/num/num.rs b/src/libcore/num/num.rs index 44cd66363fb28..e720c2fa108ae 100644 --- a/src/libcore/num/num.rs +++ b/src/libcore/num/num.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -17,6 +17,8 @@ use str; use kinds::Copy; use vec; +pub mod strconv; + pub trait IntConvertible { pure fn to_int(&self) -> int; static pure fn from_int(n: int) -> Self; @@ -42,6 +44,13 @@ pub trait Round { pure fn fract(&self) -> Self; } +pub enum RoundMode { + RoundDown, + RoundUp, + RoundToZero, + RoundFromZero +} + /** * Cast a number the the enclosing type * @@ -80,13 +89,6 @@ pub trait NumCast { pure fn to_float(&self) -> float; } -pub enum RoundMode { - RoundDown, - RoundUp, - RoundToZero, - RoundFromZero -} - pub trait ToStrRadix { pub pure fn to_str_radix(&self, radix: uint) -> ~str; } @@ -97,62 +99,6 @@ pub trait FromStrRadix { // Generic math functions: -/// Dynamically calculates the value `inf` (`1/0`). -/// Can fail on integer types. -#[inline(always)] -pub pure fn infinity>() -> T { - let _0: T = Zero::zero(); - let _1: T = One::one(); - _1 / _0 -} - -/// Dynamically calculates the value `-inf` (`-1/0`). -/// Can fail on integer types. -#[inline(always)] -pub pure fn neg_infinity+Neg>() -> T { - let _0: T = Zero::zero(); - let _1: T = One::one(); - - _1 / _0 -} - -/// Dynamically calculates the value `NaN` (`0/0`). -/// Can fail on integer types. -#[inline(always)] -pub pure fn NaN>() -> T { - let _0: T = Zero::zero(); - _0 / _0 -} - -/// Returns `true` if `num` has the value `inf` (`1/0`). -/// Can fail on integer types. -#[inline(always)] -pub pure fn is_infinity>(num: &T) -> bool { - (*num) == (infinity::()) -} - -/// Returns `true` if `num` has the value `-inf` (`-1/0`). -/// Can fail on integer types. -#[inline(always)] -pub pure fn is_neg_infinity+Neg>(num: &T) - -> bool { - (*num) == (neg_infinity::()) -} - -/// Returns `true` if `num` has the value `NaN` (is not equal to itself). -#[inline(always)] -pub pure fn is_NaN(num: &T) -> bool { - (*num) != (*num) -} - -/// Returns `true` if `num` has the value `-0` (`1/num == -1/0`). -/// Can fail on integer types. -#[inline(always)] -pub pure fn is_neg_zero+Neg>(num: &T) -> bool { - let _1: T = One::one(); - let _0: T = Zero::zero(); - *num == _0 && is_neg_infinity(&(_1 / *num)) -} - /** * Calculates a power to a given radix, optimized for uint `pow` and `radix`. * @@ -186,540 +132,3 @@ pub pure fn pow_with_uint+Mul>( total } -pub enum ExponentFormat { - ExpNone, - ExpDec, - ExpBin -} - -pub enum SignificantDigits { - DigAll, - DigMax(uint), - DigExact(uint) -} - -pub enum SignFormat { - SignNone, - SignNeg, - SignAll -} - -/** - * Converts a number to its string representation as a byte vector. - * This is meant to be a common base implementation for all numeric string - * conversion functions like `to_str()` or `to_str_radix()`. - * - * # Arguments - * - `num` - The number to convert. Accepts any number that - * implements the numeric traits. - * - `radix` - Base to use. Accepts only the values 2-36. - * - `special` - Whether to attempt to compare to special values like - * `inf` or `NaN`. Also needed to detect negative 0. - * Can fail if it doesn't match `num`s type - * (see safety note). - * - `negative_zero` - Whether to treat the special value `-0` as - * `-0` or as `+0`. - * - `sign` - How to emit the sign. Options are: - * - `SignNone`: No sign at all. Basically emits `abs(num)`. - * - `SignNeg`: Only `-` on negative values. - * - `SignAll`: Both `+` on positive, and `-` on negative numbers. - * - `digits` - The amount of digits to use for emitting the - * fractional part, if any. Options are: - * - `DigAll`: All calculatable digits. Beware of bignums or - * fractions! - * - `DigMax(uint)`: Maximum N digits, truncating any trailing zeros. - * - `DigExact(uint)`: Exactly N digits. - * - * # Return value - * A tuple containing the byte vector, and a boolean flag indicating - * whether it represents a special value like `inf`, `-inf`, `NaN` or not. - * It returns a tuple because there can be ambiguity between a special value - * and a number representation at higher bases. - * - * # Failure - * - Fails if `radix` < 2 or `radix` > 36. - * - Fails on wrong value for `special` (see safety note). - * - * # Safety note - * The function detects the special values `inf`, `-inf` and `NaN` by - * dynamically comparing `num` to `1 / 0`, `-1 / 0` and `0 / 0` - * (each of type T) if `special` is `true`. This will fail on integer types - * with a 'divide by zero'. Likewise, it will fail if `num` **is** one of - * those special values, and `special` is `false`, because then the - * algorithm just does normal calculations on them. - */ -pub pure fn to_str_bytes_common+ - Neg+Modulo+Mul>( - num: &T, radix: uint, special: bool, negative_zero: bool, - sign: SignFormat, digits: SignificantDigits) -> (~[u8], bool) { - if radix as int < 2 { - fail!(fmt!("to_str_bytes_common: radix %? to low, \ - must lie in the range [2, 36]", radix)); - } else if radix as int > 36 { - fail!(fmt!("to_str_bytes_common: radix %? to high, \ - must lie in the range [2, 36]", radix)); - } - - let _0: T = Zero::zero(); - let _1: T = One::one(); - - if special { - if is_NaN(num) { - return (str::to_bytes("NaN"), true); - } else if is_infinity(num){ - return match sign { - SignAll => (str::to_bytes("+inf"), true), - _ => (str::to_bytes("inf"), true) - } - } else if is_neg_infinity(num) { - return match sign { - SignNone => (str::to_bytes("inf"), true), - _ => (str::to_bytes("-inf"), true), - } - } - } - - let neg = *num < _0 || (negative_zero && *num == _0 - && special && is_neg_zero(num)); - let mut buf: ~[u8] = ~[]; - let radix_gen: T = cast(radix as int); - - let mut deccum; - - // First emit the non-fractional part, looping at least once to make - // sure at least a `0` gets emitted. - deccum = num.round(RoundToZero); - loop { - // Calculate the absolute value of each digit instead of only - // doing it once for the whole number because a - // representable negative number doesn't necessary have an - // representable additive inverse of the same type - // (See twos complement). But we assume that for the - // numbers [-35 .. 0] we always have [0 .. 35]. - let current_digit_signed = deccum % radix_gen; - let current_digit = if current_digit_signed < _0 { - -current_digit_signed - } else { - current_digit_signed - }; - - // Decrease the deccumulator one digit at a time - deccum /= radix_gen; - deccum = deccum.round(RoundToZero); - - unsafe { // FIXME: Pureness workaround (#4568) - buf.push(char::from_digit(current_digit.to_int() as uint, radix) - .unwrap() as u8); - } - - // No more digits to calculate for the non-fractional part -> break - if deccum == _0 { break; } - } - - // If limited digits, calculate one digit more for rounding. - let (limit_digits, digit_count, exact) = match digits { - DigAll => (false, 0u, false), - DigMax(count) => (true, count+1, false), - DigExact(count) => (true, count+1, true) - }; - - // Decide what sign to put in front - match sign { - SignNeg | SignAll if neg => { - unsafe { // FIXME: Pureness workaround (#4568) - buf.push('-' as u8); - } - } - SignAll => { - unsafe { // FIXME: Pureness workaround (#4568) - buf.push('+' as u8); - } - } - _ => () - } - - unsafe { // FIXME: Pureness workaround (#4568) - vec::reverse(buf); - } - - // Remember start of the fractional digits. - // Points one beyond end of buf if none get generated, - // or at the '.' otherwise. - let start_fractional_digits = buf.len(); - - // Now emit the fractional part, if any - deccum = num.fract(); - if deccum != _0 || (limit_digits && exact && digit_count > 0) { - unsafe { // FIXME: Pureness workaround (#4568) - buf.push('.' as u8); - } - let mut dig = 0u; - - // calculate new digits while - // - there is no limit and there are digits left - // - or there is a limit, it's not reached yet and - // - it's exact - // - or it's a maximum, and there are still digits left - while (!limit_digits && deccum != _0) - || (limit_digits && dig < digit_count && ( - exact - || (!exact && deccum != _0) - ) - ) { - // Shift first fractional digit into the integer part - deccum *= radix_gen; - - // Calculate the absolute value of each digit. - // See note in first loop. - let current_digit_signed = deccum.round(RoundToZero); - let current_digit = if current_digit_signed < _0 { - -current_digit_signed - } else { - current_digit_signed - }; - - unsafe { // FIXME: Pureness workaround (#4568) - buf.push(char::from_digit( - current_digit.to_int() as uint, radix).unwrap() as u8); - } - - // Decrease the deccumulator one fractional digit at a time - deccum = deccum.fract(); - dig += 1u; - } - - // If digits are limited, and that limit has been reached, - // cut off the one extra digit, and depending on its value - // round the remaining ones. - if limit_digits && dig == digit_count { - let ascii2value = |chr: u8| { - char::to_digit(chr as char, radix).unwrap() as uint - }; - let value2ascii = |val: uint| { - char::from_digit(val, radix).unwrap() as u8 - }; - - unsafe { // FIXME: Pureness workaround (#4568) - let extra_digit = ascii2value(buf.pop()); - if extra_digit >= radix / 2 { // -> need to round - let mut i: int = buf.len() as int - 1; - loop { - // If reached left end of number, have to - // insert additional digit: - if i < 0 - || buf[i] == '-' as u8 - || buf[i] == '+' as u8 { - buf.insert((i + 1) as uint, value2ascii(1)); - break; - } - - // Skip the '.' - if buf[i] == '.' as u8 { i -= 1; loop; } - - // Either increment the digit, - // or set to 0 if max and carry the 1. - let current_digit = ascii2value(buf[i]); - if current_digit < (radix - 1) { - buf[i] = value2ascii(current_digit+1); - break; - } else { - buf[i] = value2ascii(0); - i -= 1; - } - } - } - } - } - } - - // if number of digits is not exact, remove all trailing '0's up to - // and including the '.' - if !exact { - let buf_max_i = buf.len() - 1; - - // index to truncate from - let mut i = buf_max_i; - - // discover trailing zeros of fractional part - while i > start_fractional_digits && buf[i] == '0' as u8 { - i -= 1; - } - - // Only attempt to truncate digits if buf has fractional digits - if i >= start_fractional_digits { - // If buf ends with '.', cut that too. - if buf[i] == '.' as u8 { i -= 1 } - - // only resize buf if we actually remove digits - if i < buf_max_i { - buf = buf.slice(0, i + 1); - } - } - } // If exact and trailing '.', just cut that - else { - let max_i = buf.len() - 1; - if buf[max_i] == '.' as u8 { - buf = buf.slice(0, max_i); - } - } - - (buf, false) -} - -/** - * Converts a number to its string representation. This is a wrapper for - * `to_str_bytes_common()`, for details see there. - */ -#[inline(always)] -pub pure fn to_str_common+Neg - +Modulo+Mul>( - num: &T, radix: uint, special: bool, negative_zero: bool, - sign: SignFormat, digits: SignificantDigits) -> (~str, bool) { - let (bytes, special) = to_str_bytes_common(num, radix, special, - negative_zero, sign, digits); - (str::from_bytes(bytes), special) -} - -// Some constants for from_str_bytes_common's input validation, -// they define minimum radix values for which the character is a valid digit. -priv const DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u; -priv const DIGIT_I_RADIX: uint = ('i' as uint) - ('a' as uint) + 11u; -priv const DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u; - -/** - * Parses a byte slice as a number. This is meant to - * be a common base implementation for all numeric string conversion - * functions like `from_str()` or `from_str_radix()`. - * - * # Arguments - * - `buf` - The byte slice to parse. - * - `radix` - Which base to parse the number as. Accepts 2-36. - * - `negative` - Whether to accept negative numbers. - * - `fractional` - Whether to accept numbers with fractional parts. - * - `special` - Whether to accept special values like `inf` - * and `NaN`. Can conflict with `radix`, see Failure. - * - `exponent` - Which exponent format to accept. Options are: - * - `ExpNone`: No Exponent, accepts just plain numbers like `42` or - * `-8.2`. - * - `ExpDec`: Accepts numbers with a decimal exponent like `42e5` or - * `8.2E-2`. The exponent string itself is always base 10. - * Can conflict with `radix`, see Failure. - * - `ExpBin`: Accepts numbers with a binary exponent like `42P-8` or - * `FFp128`. The exponent string itself is always base 10. - * Can conflict with `radix`, see Failure. - * - `empty_zero` - Whether to accept a empty `buf` as a 0 or not. - * - * # Return value - * Returns `Some(n)` if `buf` parses to a number n without overflowing, and - * `None` otherwise, depending on the constraints set by the remaining - * arguments. - * - * # Failure - * - Fails if `radix` < 2 or `radix` > 36. - * - Fails if `radix` > 14 and `exponent` is `ExpDec` due to conflict - * between digit and exponent sign `'e'`. - * - Fails if `radix` > 25 and `exponent` is `ExpBin` due to conflict - * between digit and exponent sign `'p'`. - * - Fails if `radix` > 18 and `special == true` due to conflict - * between digit and lowest first character in `inf` and `NaN`, the `'i'`. - * - * # Possible improvements - * - Could accept option to allow ignoring underscores, allowing for numbers - * formated like `FF_AE_FF_FF`. - */ -pub pure fn from_str_bytes_common+ - Mul+Sub+Neg+Add>( - buf: &[u8], radix: uint, negative: bool, fractional: bool, - special: bool, exponent: ExponentFormat, empty_zero: bool - ) -> Option { - match exponent { - ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' - => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \ - use of 'e' as decimal exponent", radix)), - ExpBin if radix >= DIGIT_P_RADIX // binary exponent 'p' - => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \ - use of 'p' as binary exponent", radix)), - _ if special && radix >= DIGIT_I_RADIX // first digit of 'inf' - => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \ - special values 'inf' and 'NaN'", radix)), - _ if radix as int < 2 - => fail!(fmt!("from_str_bytes_common: radix %? to low, \ - must lie in the range [2, 36]", radix)), - _ if radix as int > 36 - => fail!(fmt!("from_str_bytes_common: radix %? to high, \ - must lie in the range [2, 36]", radix)), - _ => () - } - - let _0: T = Zero::zero(); - let _1: T = One::one(); - let radix_gen: T = cast(radix as int); - - let len = buf.len(); - - if len == 0 { - if empty_zero { - return Some(_0); - } else { - return None; - } - } - - if special { - if buf == str::to_bytes("inf") || buf == str::to_bytes("+inf") { - return Some(infinity()); - } else if buf == str::to_bytes("-inf") { - if negative { - return Some(neg_infinity()); - } else { - return None; - } - } else if buf == str::to_bytes("NaN") { - return Some(NaN()); - } - } - - let (start, accum_positive) = match buf[0] { - '-' as u8 if !negative => return None, - '-' as u8 => (1u, false), - '+' as u8 => (1u, true), - _ => (0u, true) - }; - - // Initialize accumulator with signed zero for floating point parsing to - // work - let mut accum = if accum_positive { _0 } else { -_1 * _0}; - let mut last_accum = accum; // Necessary to detect overflow - let mut i = start; - let mut exp_found = false; - - // Parse integer part of number - while i < len { - let c = buf[i] as char; - - match char::to_digit(c, radix) { - Some(digit) => { - // shift accum one digit left - accum *= radix_gen; - - // add/subtract current digit depending on sign - if accum_positive { - accum += cast(digit as int); - } else { - accum -= cast(digit as int); - } - - // Detect overflow by comparing to last value - if accum_positive && accum < last_accum { return None; } - if !accum_positive && accum > last_accum { return None; } - last_accum = accum; - } - None => match c { - 'e' | 'E' | 'p' | 'P' => { - exp_found = true; - break; // start of exponent - } - '.' if fractional => { - i += 1u; // skip the '.' - break; // start of fractional part - } - _ => return None // invalid number - } - } - - i += 1u; - } - - // Parse fractional part of number - // Skip if already reached start of exponent - if !exp_found { - let mut power = _1; - - while i < len { - let c = buf[i] as char; - - match char::to_digit(c, radix) { - Some(digit) => { - // Decrease power one order of magnitude - power /= radix_gen; - - let digit_t: T = cast(digit); - - // add/subtract current digit depending on sign - if accum_positive { - accum += digit_t * power; - } else { - accum -= digit_t * power; - } - - // Detect overflow by comparing to last value - if accum_positive && accum < last_accum { return None; } - if !accum_positive && accum > last_accum { return None; } - last_accum = accum; - } - None => match c { - 'e' | 'E' | 'p' | 'P' => { - exp_found = true; - break; // start of exponent - } - _ => return None // invalid number - } - } - - i += 1u; - } - } - - // Special case: buf not empty, but does not contain any digit in front - // of the exponent sign -> number is empty string - if i == start { - if empty_zero { - return Some(_0); - } else { - return None; - } - } - - let mut multiplier = _1; - - if exp_found { - let c = buf[i] as char; - let base = match (c, exponent) { - ('e', ExpDec) | ('E', ExpDec) => 10u, - ('p', ExpBin) | ('P', ExpBin) => 2u, - _ => return None // char doesn't fit given exponent format - }; - - // parse remaining bytes as decimal integer, - // skipping the exponent char - let exp: Option = from_str_bytes_common( - buf.view(i+1, len), 10, true, false, false, ExpNone, false); - - match exp { - Some(exp_pow) => { - multiplier = if exp_pow < 0 { - _1 / pow_with_uint::(base, (-exp_pow.to_int()) as uint) - } else { - pow_with_uint::(base, exp_pow.to_int() as uint) - } - } - None => return None // invalid exponent -> invalid number - } - } - - Some(accum * multiplier) -} - -/** - * Parses a string as a number. This is a wrapper for - * `from_str_bytes_common()`, for details see there. - */ -#[inline(always)] -pub pure fn from_str_common+Mul+ - Sub+Neg+Add>( - buf: &str, radix: uint, negative: bool, fractional: bool, - special: bool, exponent: ExponentFormat, empty_zero: bool - ) -> Option { - from_str_bytes_common(str::to_bytes(buf), radix, negative, - fractional, special, exponent, empty_zero) -} diff --git a/src/libcore/num/strconv.rs b/src/libcore/num/strconv.rs new file mode 100644 index 0000000000000..4322ea40428fb --- /dev/null +++ b/src/libcore/num/strconv.rs @@ -0,0 +1,639 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::cmp::{Ord, Eq}; +use ops::{Add, Div, Modulo, Mul, Neg, Sub}; +use option::{None, Option, Some}; +use char; +use str; +use kinds::Copy; +use vec; +use num::{NumCast, Zero, One, cast, pow_with_uint}; +use f64; + +pub enum ExponentFormat { + ExpNone, + ExpDec, + ExpBin +} + +pub enum SignificantDigits { + DigAll, + DigMax(uint), + DigExact(uint) +} + +pub enum SignFormat { + SignNone, + SignNeg, + SignAll +} + +#[inline(always)] +pure fn is_NaN(num: &T) -> bool { + *num != *num +} + +#[inline(always)] +pure fn is_inf(num: &T) -> bool { + match NumStrConv::inf() { + None => false, + Some(n) => *num == n + } +} + +#[inline(always)] +pure fn is_neg_inf(num: &T) -> bool { + match NumStrConv::neg_inf() { + None => false, + Some(n) => *num == n + } +} + +#[inline(always)] +pure fn is_neg_zero>(num: &T) -> bool { + let _0: T = Zero::zero(); + let _1: T = One::one(); + + *num == _0 && is_neg_inf(&(_1 / *num)) +} + +pub trait NumStrConv { + static pure fn NaN() -> Option; + static pure fn inf() -> Option; + static pure fn neg_inf() -> Option; + static pure fn neg_zero() -> Option; + + pure fn round_to_zero(&self) -> Self; + pure fn fractional_part(&self) -> Self; +} + +macro_rules! impl_NumStrConv_Floating (($t:ty) => ( + impl NumStrConv for $t { + #[inline(always)] + static pure fn NaN() -> Option<$t> { Some( 0.0 / 0.0) } + #[inline(always)] + static pure fn inf() -> Option<$t> { Some( 1.0 / 0.0) } + #[inline(always)] + static pure fn neg_inf() -> Option<$t> { Some(-1.0 / 0.0) } + #[inline(always)] + static pure fn neg_zero() -> Option<$t> { Some(-0.0 ) } + + #[inline(always)] + pure fn round_to_zero(&self) -> $t { + ( if *self < 0.0 { f64::ceil(*self as f64) } + else { f64::floor(*self as f64) } + ) as $t + } + + #[inline(always)] + pure fn fractional_part(&self) -> $t { + *self - self.round_to_zero() + } + } +)) + +macro_rules! impl_NumStrConv_Integer (($t:ty) => ( + impl NumStrConv for $t { + #[inline(always)] static pure fn NaN() -> Option<$t> { None } + #[inline(always)] static pure fn inf() -> Option<$t> { None } + #[inline(always)] static pure fn neg_inf() -> Option<$t> { None } + #[inline(always)] static pure fn neg_zero() -> Option<$t> { None } + + #[inline(always)] pure fn round_to_zero(&self) -> $t { *self } + #[inline(always)] pure fn fractional_part(&self) -> $t { 0 } + } +)) + +// FIXME: #4955 +// Replace by two generic impls for traits 'Integral' and 'Floating' +impl_NumStrConv_Floating!(float) +impl_NumStrConv_Floating!(f32) +impl_NumStrConv_Floating!(f64) + +impl_NumStrConv_Integer!(int) +impl_NumStrConv_Integer!(i8) +impl_NumStrConv_Integer!(i16) +impl_NumStrConv_Integer!(i32) +impl_NumStrConv_Integer!(i64) + +impl_NumStrConv_Integer!(uint) +impl_NumStrConv_Integer!(u8) +impl_NumStrConv_Integer!(u16) +impl_NumStrConv_Integer!(u32) +impl_NumStrConv_Integer!(u64) + +/** + * Converts a number to its string representation as a byte vector. + * This is meant to be a common base implementation for all numeric string + * conversion functions like `to_str()` or `to_str_radix()`. + * + * # Arguments + * - `num` - The number to convert. Accepts any number that + * implements the numeric traits. + * - `radix` - Base to use. Accepts only the values 2-36. + * - `negative_zero` - Whether to treat the special value `-0` as + * `-0` or as `+0`. + * - `sign` - How to emit the sign. Options are: + * - `SignNone`: No sign at all. Basically emits `abs(num)`. + * - `SignNeg`: Only `-` on negative values. + * - `SignAll`: Both `+` on positive, and `-` on negative numbers. + * - `digits` - The amount of digits to use for emitting the + * fractional part, if any. Options are: + * - `DigAll`: All calculatable digits. Beware of bignums or + * fractions! + * - `DigMax(uint)`: Maximum N digits, truncating any trailing zeros. + * - `DigExact(uint)`: Exactly N digits. + * + * # Return value + * A tuple containing the byte vector, and a boolean flag indicating + * whether it represents a special value like `inf`, `-inf`, `NaN` or not. + * It returns a tuple because there can be ambiguity between a special value + * and a number representation at higher bases. + * + * # Failure + * - Fails if `radix` < 2 or `radix` > 36. + */ +pub pure fn to_str_bytes_common+Neg+Modulo+Mul>( + num: &T, radix: uint, negative_zero: bool, + sign: SignFormat, digits: SignificantDigits) -> (~[u8], bool) { + if radix as int < 2 { + fail!(fmt!("to_str_bytes_common: radix %? to low, \ + must lie in the range [2, 36]", radix)); + } else if radix as int > 36 { + fail!(fmt!("to_str_bytes_common: radix %? to high, \ + must lie in the range [2, 36]", radix)); + } + + let _0: T = Zero::zero(); + let _1: T = One::one(); + + if is_NaN(num) { + return (str::to_bytes("NaN"), true); + } + else if is_inf(num){ + return match sign { + SignAll => (str::to_bytes("+inf"), true), + _ => (str::to_bytes("inf"), true) + } + } + else if is_neg_inf(num) { + return match sign { + SignNone => (str::to_bytes("inf"), true), + _ => (str::to_bytes("-inf"), true), + } + } + + let neg = *num < _0 || (negative_zero && is_neg_zero(num)); + let mut buf: ~[u8] = ~[]; + let radix_gen: T = cast(radix as int); + + let mut deccum; + + // First emit the non-fractional part, looping at least once to make + // sure at least a `0` gets emitted. + deccum = num.round_to_zero(); + loop { + // Calculate the absolute value of each digit instead of only + // doing it once for the whole number because a + // representable negative number doesn't necessary have an + // representable additive inverse of the same type + // (See twos complement). But we assume that for the + // numbers [-35 .. 0] we always have [0 .. 35]. + let current_digit_signed = deccum % radix_gen; + let current_digit = if current_digit_signed < _0 { + -current_digit_signed + } else { + current_digit_signed + }; + + // Decrease the deccumulator one digit at a time + deccum /= radix_gen; + deccum = deccum.round_to_zero(); + + unsafe { // FIXME: Pureness workaround (#4568) + buf.push(char::from_digit(current_digit.to_int() as uint, radix) + .unwrap() as u8); + } + + // No more digits to calculate for the non-fractional part -> break + if deccum == _0 { break; } + } + + // If limited digits, calculate one digit more for rounding. + let (limit_digits, digit_count, exact) = match digits { + DigAll => (false, 0u, false), + DigMax(count) => (true, count+1, false), + DigExact(count) => (true, count+1, true) + }; + + // Decide what sign to put in front + match sign { + SignNeg | SignAll if neg => { + unsafe { // FIXME: Pureness workaround (#4568) + buf.push('-' as u8); + } + } + SignAll => { + unsafe { // FIXME: Pureness workaround (#4568) + buf.push('+' as u8); + } + } + _ => () + } + + unsafe { // FIXME: Pureness workaround (#4568) + vec::reverse(buf); + } + + // Remember start of the fractional digits. + // Points one beyond end of buf if none get generated, + // or at the '.' otherwise. + let start_fractional_digits = buf.len(); + + // Now emit the fractional part, if any + deccum = num.fractional_part(); + if deccum != _0 || (limit_digits && exact && digit_count > 0) { + unsafe { // FIXME: Pureness workaround (#4568) + buf.push('.' as u8); + } + let mut dig = 0u; + + // calculate new digits while + // - there is no limit and there are digits left + // - or there is a limit, it's not reached yet and + // - it's exact + // - or it's a maximum, and there are still digits left + while (!limit_digits && deccum != _0) + || (limit_digits && dig < digit_count && ( + exact + || (!exact && deccum != _0) + ) + ) { + // Shift first fractional digit into the integer part + deccum *= radix_gen; + + // Calculate the absolute value of each digit. + // See note in first loop. + let current_digit_signed = deccum.round_to_zero(); + let current_digit = if current_digit_signed < _0 { + -current_digit_signed + } else { + current_digit_signed + }; + + unsafe { // FIXME: Pureness workaround (#4568) + buf.push(char::from_digit( + current_digit.to_int() as uint, radix).unwrap() as u8); + } + + // Decrease the deccumulator one fractional digit at a time + deccum = deccum.fractional_part(); + dig += 1u; + } + + // If digits are limited, and that limit has been reached, + // cut off the one extra digit, and depending on its value + // round the remaining ones. + if limit_digits && dig == digit_count { + let ascii2value = |chr: u8| { + char::to_digit(chr as char, radix).unwrap() as uint + }; + let value2ascii = |val: uint| { + char::from_digit(val, radix).unwrap() as u8 + }; + + unsafe { // FIXME: Pureness workaround (#4568) + let extra_digit = ascii2value(buf.pop()); + if extra_digit >= radix / 2 { // -> need to round + let mut i: int = buf.len() as int - 1; + loop { + // If reached left end of number, have to + // insert additional digit: + if i < 0 + || buf[i] == '-' as u8 + || buf[i] == '+' as u8 { + buf.insert((i + 1) as uint, value2ascii(1)); + break; + } + + // Skip the '.' + if buf[i] == '.' as u8 { i -= 1; loop; } + + // Either increment the digit, + // or set to 0 if max and carry the 1. + let current_digit = ascii2value(buf[i]); + if current_digit < (radix - 1) { + buf[i] = value2ascii(current_digit+1); + break; + } else { + buf[i] = value2ascii(0); + i -= 1; + } + } + } + } + } + } + + // if number of digits is not exact, remove all trailing '0's up to + // and including the '.' + if !exact { + let buf_max_i = buf.len() - 1; + + // index to truncate from + let mut i = buf_max_i; + + // discover trailing zeros of fractional part + while i > start_fractional_digits && buf[i] == '0' as u8 { + i -= 1; + } + + // Only attempt to truncate digits if buf has fractional digits + if i >= start_fractional_digits { + // If buf ends with '.', cut that too. + if buf[i] == '.' as u8 { i -= 1 } + + // only resize buf if we actually remove digits + if i < buf_max_i { + buf = buf.slice(0, i + 1); + } + } + } // If exact and trailing '.', just cut that + else { + let max_i = buf.len() - 1; + if buf[max_i] == '.' as u8 { + buf = buf.slice(0, max_i); + } + } + + (buf, false) +} + +/** + * Converts a number to its string representation. This is a wrapper for + * `to_str_bytes_common()`, for details see there. + */ +#[inline(always)] +pub pure fn to_str_common+Neg+Modulo+Mul>( + num: &T, radix: uint, negative_zero: bool, + sign: SignFormat, digits: SignificantDigits) -> (~str, bool) { + let (bytes, special) = to_str_bytes_common(num, radix, + negative_zero, sign, digits); + (str::from_bytes(bytes), special) +} + +// Some constants for from_str_bytes_common's input validation, +// they define minimum radix values for which the character is a valid digit. +priv const DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u; +priv const DIGIT_I_RADIX: uint = ('i' as uint) - ('a' as uint) + 11u; +priv const DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u; + +/** + * Parses a byte slice as a number. This is meant to + * be a common base implementation for all numeric string conversion + * functions like `from_str()` or `from_str_radix()`. + * + * # Arguments + * - `buf` - The byte slice to parse. + * - `radix` - Which base to parse the number as. Accepts 2-36. + * - `negative` - Whether to accept negative numbers. + * - `fractional` - Whether to accept numbers with fractional parts. + * - `special` - Whether to accept special values like `inf` + * and `NaN`. Can conflict with `radix`, see Failure. + * - `exponent` - Which exponent format to accept. Options are: + * - `ExpNone`: No Exponent, accepts just plain numbers like `42` or + * `-8.2`. + * - `ExpDec`: Accepts numbers with a decimal exponent like `42e5` or + * `8.2E-2`. The exponent string itself is always base 10. + * Can conflict with `radix`, see Failure. + * - `ExpBin`: Accepts numbers with a binary exponent like `42P-8` or + * `FFp128`. The exponent string itself is always base 10. + * Can conflict with `radix`, see Failure. + * - `empty_zero` - Whether to accept a empty `buf` as a 0 or not. + * + * # Return value + * Returns `Some(n)` if `buf` parses to a number n without overflowing, and + * `None` otherwise, depending on the constraints set by the remaining + * arguments. + * + * # Failure + * - Fails if `radix` < 2 or `radix` > 36. + * - Fails if `radix` > 14 and `exponent` is `ExpDec` due to conflict + * between digit and exponent sign `'e'`. + * - Fails if `radix` > 25 and `exponent` is `ExpBin` due to conflict + * between digit and exponent sign `'p'`. + * - Fails if `radix` > 18 and `special == true` due to conflict + * between digit and lowest first character in `inf` and `NaN`, the `'i'`. + * + * # Possible improvements + * - Could accept option to allow ignoring underscores, allowing for numbers + * formated like `FF_AE_FF_FF`. + */ +pub pure fn from_str_bytes_common+ + Mul+Sub+Neg+Add+ + NumStrConv>( + buf: &[u8], radix: uint, negative: bool, fractional: bool, + special: bool, exponent: ExponentFormat, empty_zero: bool + ) -> Option { + match exponent { + ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' + => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \ + use of 'e' as decimal exponent", radix)), + ExpBin if radix >= DIGIT_P_RADIX // binary exponent 'p' + => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \ + use of 'p' as binary exponent", radix)), + _ if special && radix >= DIGIT_I_RADIX // first digit of 'inf' + => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \ + special values 'inf' and 'NaN'", radix)), + _ if radix as int < 2 + => fail!(fmt!("from_str_bytes_common: radix %? to low, \ + must lie in the range [2, 36]", radix)), + _ if radix as int > 36 + => fail!(fmt!("from_str_bytes_common: radix %? to high, \ + must lie in the range [2, 36]", radix)), + _ => () + } + + let _0: T = Zero::zero(); + let _1: T = One::one(); + let radix_gen: T = cast(radix as int); + + let len = buf.len(); + + if len == 0 { + if empty_zero { + return Some(_0); + } else { + return None; + } + } + + // XXX: Bytevector constant from str + if special { + if buf == str::to_bytes("inf") || buf == str::to_bytes("+inf") { + return NumStrConv::inf(); + } else if buf == str::to_bytes("-inf") { + if negative { + return NumStrConv::neg_inf(); + } else { + return None; + } + } else if buf == str::to_bytes("NaN") { + return NumStrConv::NaN(); + } + } + + let (start, accum_positive) = match buf[0] { + '-' as u8 if !negative => return None, + '-' as u8 => (1u, false), + '+' as u8 => (1u, true), + _ => (0u, true) + }; + + // Initialize accumulator with signed zero for floating point parsing to + // work + let mut accum = if accum_positive { _0 } else { -_1 * _0}; + let mut last_accum = accum; // Necessary to detect overflow + let mut i = start; + let mut exp_found = false; + + // Parse integer part of number + while i < len { + let c = buf[i] as char; + + match char::to_digit(c, radix) { + Some(digit) => { + // shift accum one digit left + accum *= radix_gen; + + // add/subtract current digit depending on sign + if accum_positive { + accum += cast(digit as int); + } else { + accum -= cast(digit as int); + } + + // Detect overflow by comparing to last value + if accum_positive && accum < last_accum { return None; } + if !accum_positive && accum > last_accum { return None; } + last_accum = accum; + } + None => match c { + 'e' | 'E' | 'p' | 'P' => { + exp_found = true; + break; // start of exponent + } + '.' if fractional => { + i += 1u; // skip the '.' + break; // start of fractional part + } + _ => return None // invalid number + } + } + + i += 1u; + } + + // Parse fractional part of number + // Skip if already reached start of exponent + if !exp_found { + let mut power = _1; + + while i < len { + let c = buf[i] as char; + + match char::to_digit(c, radix) { + Some(digit) => { + // Decrease power one order of magnitude + power /= radix_gen; + + let digit_t: T = cast(digit); + + // add/subtract current digit depending on sign + if accum_positive { + accum += digit_t * power; + } else { + accum -= digit_t * power; + } + + // Detect overflow by comparing to last value + if accum_positive && accum < last_accum { return None; } + if !accum_positive && accum > last_accum { return None; } + last_accum = accum; + } + None => match c { + 'e' | 'E' | 'p' | 'P' => { + exp_found = true; + break; // start of exponent + } + _ => return None // invalid number + } + } + + i += 1u; + } + } + + // Special case: buf not empty, but does not contain any digit in front + // of the exponent sign -> number is empty string + if i == start { + if empty_zero { + return Some(_0); + } else { + return None; + } + } + + let mut multiplier = _1; + + if exp_found { + let c = buf[i] as char; + let base = match (c, exponent) { + ('e', ExpDec) | ('E', ExpDec) => 10u, + ('p', ExpBin) | ('P', ExpBin) => 2u, + _ => return None // char doesn't fit given exponent format + }; + + // parse remaining bytes as decimal integer, + // skipping the exponent char + let exp: Option = from_str_bytes_common( + buf.view(i+1, len), 10, true, false, false, ExpNone, false); + + match exp { + Some(exp_pow) => { + multiplier = if exp_pow < 0 { + _1 / pow_with_uint::(base, (-exp_pow.to_int()) as uint) + } else { + pow_with_uint::(base, exp_pow.to_int() as uint) + } + } + None => return None // invalid exponent -> invalid number + } + } + + Some(accum * multiplier) +} + +/** + * Parses a string as a number. This is a wrapper for + * `from_str_bytes_common()`, for details see there. + */ +#[inline(always)] +pub pure fn from_str_common+Mul+ + Sub+Neg+Add+NumStrConv>( + buf: &str, radix: uint, negative: bool, fractional: bool, + special: bool, exponent: ExponentFormat, empty_zero: bool + ) -> Option { + from_str_bytes_common(str::to_bytes(buf), radix, negative, + fractional, special, exponent, empty_zero) +} diff --git a/src/libcore/num/uint-template.rs b/src/libcore/num/uint-template.rs index b1ef3f11fa4e1..005f0f2b5a4df 100644 --- a/src/libcore/num/uint-template.rs +++ b/src/libcore/num/uint-template.rs @@ -17,6 +17,7 @@ use cmp; use to_str::ToStr; use from_str::FromStr; use num::{ToStrRadix, FromStrRadix}; +use num::strconv; use num; use option::{None, Option, Some}; use prelude::*; @@ -140,18 +141,6 @@ impl num::One for T { static pure fn one() -> T { 1 } } -impl num::Round for T { - #[inline(always)] - pure fn round(&self, _: num::RoundMode) -> T { *self } - - #[inline(always)] - pure fn floor(&self) -> T { *self } - #[inline(always)] - pure fn ceil(&self) -> T { *self } - #[inline(always)] - pure fn fract(&self) -> T { 0 } -} - #[cfg(notest)] impl ops::Add for T { pure fn add(&self, other: &T) -> T { *self + *other } @@ -182,22 +171,22 @@ impl ops::Neg for T { /// Parse a string as a number in base 10. #[inline(always)] pub pure fn from_str(s: &str) -> Option { - num::from_str_common(s, 10u, false, false, false, - num::ExpNone, false) + strconv::from_str_common(s, 10u, false, false, false, + strconv::ExpNone, false) } /// Parse a string as a number in the given base. #[inline(always)] pub pure fn from_str_radix(s: &str, radix: uint) -> Option { - num::from_str_common(s, radix, false, false, false, - num::ExpNone, false) + strconv::from_str_common(s, radix, false, false, false, + strconv::ExpNone, false) } /// Parse a byte slice as a number in the given base. #[inline(always)] pub pure fn parse_bytes(buf: &[u8], radix: uint) -> Option { - num::from_str_bytes_common(buf, radix, false, false, false, - num::ExpNone, false) + strconv::from_str_bytes_common(buf, radix, false, false, false, + strconv::ExpNone, false) } impl FromStr for T { @@ -219,24 +208,24 @@ impl FromStrRadix for T { /// Convert to a string as a byte slice in a given base. #[inline(always)] pub pure fn to_str_bytes(n: T, radix: uint, f: fn(v: &[u8]) -> U) -> U { - let (buf, _) = num::to_str_bytes_common(&n, radix, false, false, - num::SignNeg, num::DigAll); + let (buf, _) = strconv::to_str_bytes_common(&n, radix, false, + strconv::SignNeg, strconv::DigAll); f(buf) } /// Convert to a string in base 10. #[inline(always)] pub pure fn to_str(num: T) -> ~str { - let (buf, _) = num::to_str_common(&num, 10u, false, false, - num::SignNeg, num::DigAll); + let (buf, _) = strconv::to_str_common(&num, 10u, false, + strconv::SignNeg, strconv::DigAll); buf } /// Convert to a string in a given base. #[inline(always)] pub pure fn to_str_radix(num: T, radix: uint) -> ~str { - let (buf, _) = num::to_str_common(&num, radix, false, false, - num::SignNeg, num::DigAll); + let (buf, _) = strconv::to_str_common(&num, radix, false, + strconv::SignNeg, strconv::DigAll); buf } diff --git a/src/libcore/num/uint-template/u16.rs b/src/libcore/num/uint-template/u16.rs index 57e1f5283f664..315ff84cc234c 100644 --- a/src/libcore/num/uint-template/u16.rs +++ b/src/libcore/num/uint-template/u16.rs @@ -19,7 +19,7 @@ mod inst { pub const bits: uint = 16; } -pub impl u16: NumCast { +pub impl NumCast for u16 { /** * Cast `n` to a `u16` */ diff --git a/src/libcore/num/uint-template/u32.rs b/src/libcore/num/uint-template/u32.rs index 7099d15c40b49..834feff292c59 100644 --- a/src/libcore/num/uint-template/u32.rs +++ b/src/libcore/num/uint-template/u32.rs @@ -19,7 +19,7 @@ mod inst { pub const bits: uint = 32; } -pub impl u32: NumCast { +pub impl NumCast for u32 { /** * Cast `n` to a `u32` */ diff --git a/src/libcore/num/uint-template/u64.rs b/src/libcore/num/uint-template/u64.rs index f4d1482de905f..b661b3b20b1cd 100644 --- a/src/libcore/num/uint-template/u64.rs +++ b/src/libcore/num/uint-template/u64.rs @@ -19,7 +19,7 @@ mod inst { pub const bits: uint = 64; } -pub impl u64: num::NumCast { +pub impl NumCast for u64 { /** * Cast `n` to a `u64` */ diff --git a/src/libcore/num/uint-template/u8.rs b/src/libcore/num/uint-template/u8.rs index e2f8e00db8197..c2be9e252d9a1 100644 --- a/src/libcore/num/uint-template/u8.rs +++ b/src/libcore/num/uint-template/u8.rs @@ -26,7 +26,7 @@ mod inst { pub pure fn is_ascii(x: T) -> bool { return 0 as T == x & 128 as T; } } -pub impl u8: NumCast { +pub impl NumCast for u8 { /** * Cast `n` to a `u8` */ diff --git a/src/libcore/num/uint-template/uint.rs b/src/libcore/num/uint-template/uint.rs index cfb445cbdc878..475ae243915d9 100644 --- a/src/libcore/num/uint-template/uint.rs +++ b/src/libcore/num/uint-template/uint.rs @@ -110,7 +110,7 @@ pub mod inst { return true; } - pub impl uint: iter::Times { + pub impl iter::Times for uint { #[inline(always)] /** * A convenience form for basic iteration. Given a uint `x`, @@ -209,7 +209,7 @@ pub mod inst { } } -pub impl uint: NumCast { +pub impl NumCast for uint { /** * Cast `n` to a `uint` */ diff --git a/src/libcore/option.rs b/src/libcore/option.rs index e57d664c2aaee..13d4ec6e10df6 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -33,15 +33,15 @@ match msg { } // Remove the contained string, destroying the Option -let unwrapped_msg = match move msg { - Some(move m) => m, +let unwrapped_msg = match msg { + Some(m) => m, None => ~"default message" }; ~~~ */ -use cmp::Eq; +use cmp::{Eq,Ord}; use kinds::Copy; use option; use ptr; @@ -56,6 +56,34 @@ pub enum Option { Some(T), } +pub impl Ord for Option { + pure fn lt(&self, other: &Option) -> bool { + match (self, other) { + (&None, &None) => false, + (&None, &Some(_)) => true, + (&Some(_), &None) => false, + (&Some(ref a), &Some(ref b)) => *a < *b + } + } + + pure fn le(&self, other: &Option) -> bool { + match (self, other) { + (&None, &None) => true, + (&None, &Some(_)) => true, + (&Some(_), &None) => false, + (&Some(ref a), &Some(ref b)) => *a <= *b + } + } + + pure fn ge(&self, other: &Option) -> bool { + ! (self < other) + } + + pure fn gt(&self, other: &Option) -> bool { + ! (self <= other) + } +} + #[inline(always)] pub pure fn get(opt: Option) -> T { /*! @@ -126,8 +154,8 @@ pub pure fn chain(opt: Option, * function that returns an option. */ - match move opt { - Some(move t) => f(move t), + match opt { + Some(t) => f(t), None => None } } @@ -148,9 +176,9 @@ pub pure fn or(opta: Option, optb: Option) -> Option { /*! * Returns the leftmost Some() value, or None if both are None. */ - match move opta { - Some(move opta) => Some(move opta), - _ => move optb + match opta { + Some(opta) => Some(opta), + _ => optb } } @@ -158,9 +186,9 @@ pub pure fn or(opta: Option, optb: Option) -> Option { pub pure fn while_some(x: Option, blk: fn(v: T) -> Option) { //! Applies a function zero or more times until the result is none. - let mut opt = move x; + let mut opt = x; while opt.is_some() { - opt = blk(unwrap(move opt)); + opt = blk(unwrap(opt)); } } @@ -197,7 +225,7 @@ pub pure fn map_default(opt: &r/Option, def: U, f: fn(&r/T) -> U) -> U { //! Applies a function to the contained value or returns a default - match *opt { None => move def, Some(ref t) => f(t) } + match *opt { None => def, Some(ref t) => f(t) } } #[inline(always)] @@ -224,8 +252,8 @@ pub pure fn unwrap(opt: Option) -> T { Instead, prefer to use pattern matching and handle the `None` case explicitly. */ - match move opt { - Some(move x) => move x, + match opt { + Some(x) => x, None => fail!(~"option::unwrap none") } } @@ -247,8 +275,8 @@ pub fn swap_unwrap(opt: &mut Option) -> T { #[inline(always)] pub pure fn expect(opt: Option, reason: &str) -> T { //! As unwrap, but with a specified failure message. - match move opt { - Some(move val) => val, + match opt { + Some(val) => val, None => fail!(reason.to_owned()), } } @@ -285,7 +313,7 @@ impl Option { /// Applies a function to the contained value or returns a default #[inline(always)] pure fn map_default(&self, def: U, f: fn(&self/T) -> U) -> U { - map_default(self, move def, f) + map_default(self, def, f) } /// As `map_default`, but consumes the option and gives `f` @@ -402,8 +430,8 @@ impl Option { fn test_unwrap_ptr() { let x = ~0; let addr_x = ptr::addr_of(&(*x)); - let opt = Some(move x); - let y = unwrap(move opt); + let opt = Some(x); + let y = unwrap(opt); let addr_y = ptr::addr_of(&(*y)); assert addr_x == addr_y; } @@ -412,8 +440,8 @@ fn test_unwrap_ptr() { fn test_unwrap_str() { let x = ~"test"; let addr_x = str::as_buf(x, |buf, _len| buf); - let opt = Some(move x); - let y = unwrap(move opt); + let opt = Some(x); + let y = unwrap(opt); let addr_y = str::as_buf(y, |buf, _len| buf); assert addr_x == addr_y; } @@ -434,8 +462,8 @@ fn test_unwrap_resource() { let i = @mut 0; { let x = R(i); - let opt = Some(move x); - let _y = unwrap(move opt); + let opt = Some(x); + let _y = unwrap(opt); } assert *i == 1; } diff --git a/src/libcore/os.rs b/src/libcore/os.rs index 6ed8d70642cce..98bac3a49d8a2 100644 --- a/src/libcore/os.rs +++ b/src/libcore/os.rs @@ -108,9 +108,10 @@ pub mod win32 { let mut res = None; let mut done = false; while !done { - let mut buf = vec::from_elem(n as uint, 0u16); + let mut k: DWORD = 0; + let buf = vec::cast_to_mut(vec::from_elem(n as uint, 0u16)); do vec::as_mut_buf(buf) |b, _sz| { - let k : DWORD = f(b, TMPBUF_SZ as DWORD); + k = f(b, TMPBUF_SZ as DWORD); if k == (0 as DWORD) { done = true; } else if (k == n && @@ -118,11 +119,13 @@ pub mod win32 { libc::ERROR_INSUFFICIENT_BUFFER as DWORD) { n *= (2 as DWORD); } else { - let sub = vec::slice(buf, 0u, k as uint); - res = option::Some(str::from_utf16(sub)); done = true; } } + if k != 0 && done { + let sub = vec::slice(buf, 0u, k as uint); + res = option::Some(str::from_utf16(sub)); + } } return res; } @@ -171,7 +174,7 @@ pub fn env() -> ~[(~str,~str)] { assert vec::len(vs) == 2u; pairs.push((copy vs[0], copy vs[1])); } - move pairs + pairs } } } @@ -306,10 +309,9 @@ pub fn waitpid(pid: pid_t) -> c_int { pub fn waitpid(pid: pid_t) -> c_int { unsafe { use libc::funcs::posix01::wait::*; - let status = 0 as c_int; + let mut status = 0 as c_int; - assert (waitpid(pid, ptr::mut_addr_of(&status), - 0 as c_int) != (-1 as c_int)); + assert (waitpid(pid, &mut status, 0 as c_int) != (-1 as c_int)); return status; } } @@ -322,7 +324,7 @@ pub fn pipe() -> Pipe { unsafe { let mut fds = Pipe {mut in: 0 as c_int, mut out: 0 as c_int }; - assert (libc::pipe(ptr::mut_addr_of(&(fds.in))) == (0 as c_int)); + assert (libc::pipe(&mut fds.in) == (0 as c_int)); return Pipe {in: fds.in, out: fds.out}; } } @@ -339,8 +341,7 @@ pub fn pipe() -> Pipe { // first, as in rust_run_program. let mut fds = Pipe { mut in: 0 as c_int, mut out: 0 as c_int }; - let res = libc::pipe(ptr::mut_addr_of(&(fds.in)), - 1024 as c_uint, + let res = libc::pipe(&mut fds.in, 1024 as c_uint, (libc::O_BINARY | libc::O_NOINHERIT) as c_int); assert (res == 0 as c_int); assert (fds.in != -1 as c_int && fds.in != 0 as c_int); @@ -374,8 +375,8 @@ pub fn self_exe_path() -> Option { KERN_PROC as c_int, KERN_PROC_PATHNAME as c_int, -1 as c_int]; sysctl(vec::raw::to_ptr(mib), vec::len(mib) as c_uint, - buf as *mut c_void, ptr::mut_addr_of(&sz), - ptr::null(), 0u as size_t) == (0 as c_int) + buf as *mut c_void, &mut sz, ptr::null(), + 0u as size_t) == (0 as c_int) } } } @@ -406,8 +407,9 @@ pub fn self_exe_path() -> Option { fn load_self() -> Option<~str> { unsafe { do fill_charp_buf() |buf, sz| { + let mut sz = sz as u32; libc::funcs::extra::_NSGetExecutablePath( - buf, ptr::mut_addr_of(&(sz as u32))) == (0 as c_int) + buf, &mut sz) == (0 as c_int) } } } @@ -483,7 +485,7 @@ pub fn tmpdir() -> Path { fn getenv_nonempty(v: &str) -> Option { match getenv(v) { - Some(move x) => + Some(x) => if str::is_empty(x) { None } else { @@ -849,7 +851,7 @@ pub fn last_os_error() -> ~str { let err = strerror_r(errno() as c_int, &buf[0], TMPBUF_SZ as size_t); if err < 0 { - die!(~"strerror_r failure"); + fail!(~"strerror_r failure"); } str::raw::from_c_str(&buf[0]) @@ -887,7 +889,7 @@ pub fn last_os_error() -> ~str { &mut buf[0], TMPBUF_SZ as DWORD, ptr::null()); if res == 0 { - die!(fmt!("[%?] FormatMessage failure", errno())); + fail!(fmt!("[%?] FormatMessage failure", errno())); } str::raw::from_c_str(&buf[0]) @@ -916,7 +918,7 @@ unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] { for uint::range(0, argc as uint) |i| { vec::push(&mut args, str::raw::from_c_str(*argv.offset(i))); } - move args + args } /** @@ -1138,7 +1140,7 @@ mod tests { let rng: rand::Rng = rand::Rng(); let n = ~"TEST" + rng.gen_str(10u); assert getenv(n).is_none(); - move n + n } #[test] @@ -1172,7 +1174,7 @@ mod tests { let n = make_rand_name(); setenv(n, s); log(debug, copy s); - assert getenv(n) == option::Some(move s); + assert getenv(n) == option::Some(s); } #[test] @@ -1198,7 +1200,7 @@ mod tests { // MingW seems to set some funky environment variables like // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned // from env() but not visible from getenv(). - assert v2.is_none() || v2 == option::Some(move v); + assert v2.is_none() || v2 == option::Some(v); } } @@ -1211,7 +1213,7 @@ mod tests { assert !vec::contains(e, &(copy n, ~"VALUE")); e = env(); - assert vec::contains(e, &(move n, ~"VALUE")); + assert vec::contains(e, &(n, ~"VALUE")); } #[test] diff --git a/src/libcore/path.rs b/src/libcore/path.rs index 91690b6b5b0b2..531ce95d067be 100644 --- a/src/libcore/path.rs +++ b/src/libcore/path.rs @@ -243,9 +243,9 @@ impl Path { unsafe { do str::as_c_str(self.to_str()) |buf| { let mut st = stat::arch::default_stat(); - let r = libc::stat(buf, ptr::mut_addr_of(&st)); + let r = libc::stat(buf, &mut st); - if r == 0 { Some(move st) } else { None } + if r == 0 { Some(st) } else { None } } } } @@ -255,9 +255,9 @@ impl Path { unsafe { do str::as_c_str(self.to_str()) |buf| { let mut st = stat::arch::default_stat(); - let r = libc::lstat(buf, ptr::mut_addr_of(&st)); + let r = libc::lstat(buf, &mut st); - if r == 0 { Some(move st) } else { None } + if r == 0 { Some(st) } else { None } } } } @@ -381,7 +381,7 @@ impl GenericPath for PosixPath { let mut components = str::split_nonempty(s, |c| c == '/'); let is_absolute = (s.len() != 0 && s[0] == '/' as u8); return PosixPath { is_absolute: is_absolute, - components: move components } + components: components } } pure fn dirname() -> ~str { @@ -390,7 +390,7 @@ impl GenericPath for PosixPath { if s.len() == 0 { ~"." } else { - move s + s } } } @@ -430,7 +430,7 @@ impl GenericPath for PosixPath { let dpath = PosixPath(d); match self.filename() { Some(ref f) => dpath.push(*f), - None => move dpath + None => dpath } } @@ -477,7 +477,7 @@ impl GenericPath for PosixPath { Some(ref f) => ~[copy *f] }; return PosixPath { is_absolute: false, - components: move cs } + components: cs } } pure fn push_rel(other: &PosixPath) -> PosixPath { @@ -491,17 +491,17 @@ impl GenericPath for PosixPath { let mut ss = str::split_nonempty( *e, |c| windows::is_sep(c as u8)); - unsafe { v.push_all_move(move ss); } + unsafe { v.push_all_move(ss); } } PosixPath { is_absolute: self.is_absolute, - components: move v } + components: v } } pure fn push(s: &str) -> PosixPath { let mut v = copy self.components; let mut ss = str::split_nonempty(s, |c| windows::is_sep(c as u8)); - unsafe { v.push_all_move(move ss); } - PosixPath { components: move v, ..copy self } + unsafe { v.push_all_move(ss); } + PosixPath { components: v, ..copy self } } pure fn pop() -> PosixPath { @@ -511,7 +511,7 @@ impl GenericPath for PosixPath { } return PosixPath { is_absolute: self.is_absolute, - components: move cs + components: cs } //..self } } @@ -577,10 +577,10 @@ impl GenericPath for WindowsPath { let mut components = str::split_nonempty(rest, |c| windows::is_sep(c as u8)); let is_absolute = (rest.len() != 0 && windows::is_sep(rest[0])); - return WindowsPath { host: move host, - device: move device, + return WindowsPath { host: host, + device: device, is_absolute: is_absolute, - components: move components } + components: components } } pure fn dirname() -> ~str { @@ -589,7 +589,7 @@ impl GenericPath for WindowsPath { if s.len() == 0 { ~"." } else { - move s + s } } } @@ -629,7 +629,7 @@ impl GenericPath for WindowsPath { let dpath = WindowsPath(d); match self.filename() { Some(ref f) => dpath.push(*f), - None => move dpath + None => dpath } } @@ -677,7 +677,7 @@ impl GenericPath for WindowsPath { return WindowsPath { host: None, device: None, is_absolute: false, - components: move cs } + components: cs } } pure fn push_rel(other: &WindowsPath) -> WindowsPath { @@ -691,22 +691,22 @@ impl GenericPath for WindowsPath { let mut ss = str::split_nonempty( *e, |c| windows::is_sep(c as u8)); - unsafe { v.push_all_move(move ss); } + unsafe { v.push_all_move(ss); } } // tedious, but as-is, we can't use ..self return WindowsPath { host: copy self.host, device: copy self.device, is_absolute: self.is_absolute, - components: move v + components: v } } pure fn push(s: &str) -> WindowsPath { let mut v = copy self.components; let mut ss = str::split_nonempty(s, |c| windows::is_sep(c as u8)); - unsafe { v.push_all_move(move ss); } - return WindowsPath { components: move v, ..copy self } + unsafe { v.push_all_move(ss); } + return WindowsPath { components: v, ..copy self } } pure fn pop() -> WindowsPath { @@ -718,7 +718,7 @@ impl GenericPath for WindowsPath { host: copy self.host, device: copy self.device, is_absolute: self.is_absolute, - components: move cs + components: cs } } @@ -748,7 +748,7 @@ pub pure fn normalize(components: &[~str]) -> ~[~str] { } } } - move cs + cs } // Various windows helpers, and tests for the impl. @@ -771,7 +771,7 @@ pub mod windows { if s[i] == '\\' as u8 { let pre = s.slice(2, i); let rest = s.slice(i, s.len()); - return Some((move pre, move rest)); + return Some((pre, rest)); } i += 1; } @@ -789,7 +789,7 @@ pub mod windows { } else { s.slice(2, s.len()) }; - return Some((s.slice(0,1), move rest)); + return Some((s.slice(0,1), rest)); } None } diff --git a/src/libcore/pipes.rs b/src/libcore/pipes.rs index a26a6b5f8ec3d..f0108fe85b757 100644 --- a/src/libcore/pipes.rs +++ b/src/libcore/pipes.rs @@ -101,7 +101,7 @@ use vec; const SPIN_COUNT: uint = 0; macro_rules! move_it ( - { $x:expr } => ( unsafe { let y = move *ptr::addr_of(&($x)); move y } ) + { $x:expr } => ( unsafe { let y = *ptr::addr_of(&($x)); y } ) ) #[doc(hidden)] @@ -233,7 +233,7 @@ fn unibuffer() -> ~Buffer> { unsafe { b.data.header.buffer = reinterpret_cast(&b); } - move b + b } #[doc(hidden)] @@ -241,7 +241,7 @@ pub fn packet() -> *Packet { let b = unibuffer(); let p = ptr::addr_of(&(b.data)); // We'll take over memory management from here. - unsafe { forget(move b) } + unsafe { forget(b) } p } @@ -252,7 +252,7 @@ pub fn entangle_buffer( -> (SendPacketBuffered, RecvPacketBuffered) { let p = init(unsafe { reinterpret_cast(&buffer) }, &buffer.data); - unsafe { forget(move buffer) } + unsafe { forget(buffer) } (SendPacketBuffered(p), RecvPacketBuffered(p)) } @@ -295,7 +295,7 @@ pub fn swap_task(dst: &mut *rust_task, src: *rust_task) -> *rust_task { // It might be worth making both acquire and release versions of // this. unsafe { - transmute(rusti::atomic_xchg(transmute(move dst), src as int)) + transmute(rusti::atomic_xchg(transmute(dst), src as int)) } } @@ -335,14 +335,14 @@ fn wait_event(this: *rust_task) -> *libc::c_void { #[doc(hidden)] fn swap_state_acq(dst: &mut State, src: State) -> State { unsafe { - transmute(rusti::atomic_xchg_acq(transmute(move dst), src as int)) + transmute(rusti::atomic_xchg_acq(transmute(dst), src as int)) } } #[doc(hidden)] fn swap_state_rel(dst: &mut State, src: State) -> State { unsafe { - transmute(rusti::atomic_xchg_rel(transmute(move dst), src as int)) + transmute(rusti::atomic_xchg_rel(transmute(dst), src as int)) } } @@ -368,7 +368,7 @@ struct BufferResource { // go go gadget drop glue } else { - forget(move b) + forget(b) } } } @@ -381,7 +381,7 @@ fn BufferResource(b: ~Buffer) -> BufferResource { BufferResource { // tjc: ???? - buffer: move b + buffer: b } } @@ -392,7 +392,7 @@ pub fn send(p: SendPacketBuffered, payload: T) -> bool { let p = unsafe { &*p_ }; assert ptr::addr_of(&(p.header)) == header; assert p.payload.is_none(); - p.payload = move Some(move payload); + p.payload = Some(payload); let old_state = swap_state_rel(&mut p.header.state, Full); match old_state { Empty => { @@ -434,7 +434,7 @@ Fails if the sender closes the connection. */ pub fn recv( p: RecvPacketBuffered) -> T { - try_recv(move p).expect("connection closed") + try_recv(p).expect("connection closed") } /** Attempts to receive a message from a pipe. @@ -474,7 +474,7 @@ pub fn try_recv(p: RecvPacketBuffered) let mut payload = None; payload <-> p.payload; p.header.state = Empty; - return Some(option::unwrap(move payload)) + return Some(option::unwrap(payload)) }, Terminated => return None, _ => {} @@ -532,7 +532,7 @@ pub fn try_recv(p: RecvPacketBuffered) } } p.header.state = Empty; - return Some(option::unwrap(move payload)) + return Some(option::unwrap(payload)) } Terminated => { // This assert detects when we've accidentally unsafely @@ -723,8 +723,8 @@ pub fn select2( let i = wait_many([a.header(), b.header()]); match i { - 0 => Left((try_recv(move a), move b)), - 1 => Right((move a, try_recv(move b))), + 0 => Left((try_recv(a), b)), + 1 => Right((a, try_recv(b))), _ => fail!(~"select2 return an invalid packet") } } @@ -761,10 +761,10 @@ pub fn select(endpoints: ~[RecvPacketBuffered]) -> (uint, Option, ~[RecvPacketBuffered]) { let ready = wait_many(endpoints.map(|p| p.header())); - let mut remaining = move endpoints; + let mut remaining = endpoints; let port = remaining.swap_remove(ready); - let result = try_recv(move port); - (ready, move result, move remaining) + let result = try_recv(port); + (ready, result, remaining) } /** The sending end of a pipe. It can be used to send exactly one @@ -791,7 +791,7 @@ impl ::ops::Drop for SendPacketBuffered { if self.p != None { let mut p = None; p <-> self.p; - sender_terminate(option::unwrap(move p)) + sender_terminate(option::unwrap(p)) } //unsafe { error!("send_drop: %?", // if self.buffer == none { @@ -816,7 +816,7 @@ impl SendPacketBuffered { fn unwrap() -> *Packet { let mut p = None; p <-> self.p; - option::unwrap(move p) + option::unwrap(p) } pure fn header() -> *PacketHeader { @@ -835,7 +835,7 @@ impl SendPacketBuffered { //error!("send reuse_buffer"); let mut tmp = None; tmp <-> self.buffer; - option::unwrap(move tmp) + option::unwrap(tmp) } } @@ -860,7 +860,7 @@ impl ::ops::Drop for RecvPacketBuffered { if self.p != None { let mut p = None; p <-> self.p; - receiver_terminate(option::unwrap(move p)) + receiver_terminate(option::unwrap(p)) } //unsafe { error!("recv_drop: %?", // if self.buffer == none { @@ -873,14 +873,14 @@ impl RecvPacketBuffered { fn unwrap() -> *Packet { let mut p = None; p <-> self.p; - option::unwrap(move p) + option::unwrap(p) } fn reuse_buffer() -> BufferResource { //error!("recv reuse_buffer"); let mut tmp = None; tmp <-> self.buffer; - option::unwrap(move tmp) + option::unwrap(tmp) } } @@ -933,14 +933,14 @@ pub fn spawn_service( // This is some nasty gymnastics required to safely move the pipe // into a new task. - let server = ~mut Some(move server); - do task::spawn |move service, move server| { + let server = ~mut Some(server); + do task::spawn || { let mut server_ = None; server_ <-> *server; - service(option::unwrap(move server_)) + service(option::unwrap(server_)) } - move client + client } /** Like `spawn_service_recv`, but for protocols that start in the @@ -957,14 +957,14 @@ pub fn spawn_service_recv( // This is some nasty gymnastics required to safely move the pipe // into a new task. - let server = ~mut Some(move server); - do task::spawn |move service, move server| { + let server = ~mut Some(server); + do task::spawn || { let mut server_ = None; server_ <-> *server; - service(option::unwrap(move server_)) + service(option::unwrap(server_)) } - move client + client } // Streams - Make pipes a little easier in general. @@ -1041,7 +1041,7 @@ impl GenericChan for Chan { let mut endp = None; endp <-> self.endp; self.endp = Some( - streamp::client::data(unwrap(move endp), move x)) + streamp::client::data(unwrap(endp), x)) } } @@ -1050,9 +1050,9 @@ impl GenericSmartChan for Chan { fn try_send(x: T) -> bool { let mut endp = None; endp <-> self.endp; - match move streamp::client::try_data(unwrap(move endp), move x) { - Some(move next) => { - self.endp = Some(move next); + match streamp::client::try_data(unwrap(endp), x) { + Some(next) => { + self.endp = Some(next); true } None => false @@ -1064,18 +1064,18 @@ impl GenericPort for Port { fn recv() -> T { let mut endp = None; endp <-> self.endp; - let streamp::data(x, endp) = pipes::recv(unwrap(move endp)); - self.endp = Some(move endp); - move x + let streamp::data(x, endp) = pipes::recv(unwrap(endp)); + self.endp = Some(endp); + x } fn try_recv() -> Option { let mut endp = None; endp <-> self.endp; - match move pipes::try_recv(unwrap(move endp)) { - Some(streamp::data(move x, move endp)) => { - self.endp = Some(move endp); - Some(move x) + match pipes::try_recv(unwrap(endp)) { + Some(streamp::data(x, endp)) => { + self.endp = Some(endp); + Some(x) } None => None } @@ -1122,13 +1122,13 @@ pub fn PortSet() -> PortSet{ impl PortSet { fn add(port: pipes::Port) { - self.ports.push(move port) + self.ports.push(port) } fn chan() -> Chan { let (po, ch) = stream(); - self.add(move po); - move ch + self.add(po); + ch } } @@ -1142,9 +1142,9 @@ impl GenericPort for PortSet { ports <-> self.ports; while result.is_none() && ports.len() > 0 { let i = wait_many(ports); - match move ports[i].try_recv() { - Some(move m) => { - result = Some(move m); + match ports[i].try_recv() { + Some(m) => { + result = Some(m); } None => { // Remove this port. @@ -1153,7 +1153,7 @@ impl GenericPort for PortSet { } } ports <-> self.ports; - move result + result } fn recv() -> T { @@ -1178,29 +1178,29 @@ pub type SharedChan = private::Exclusive>; impl GenericChan for SharedChan { fn send(x: T) { - let mut xx = Some(move x); + let mut xx = Some(x); do self.with_imm |chan| { let mut x = None; x <-> xx; - chan.send(option::unwrap(move x)) + chan.send(option::unwrap(x)) } } } impl GenericSmartChan for SharedChan { fn try_send(x: T) -> bool { - let mut xx = Some(move x); + let mut xx = Some(x); do self.with_imm |chan| { let mut x = None; x <-> xx; - chan.try_send(option::unwrap(move x)) + chan.try_send(option::unwrap(x)) } } } /// Converts a `chan` into a `shared_chan`. pub fn SharedChan(c: Chan) -> SharedChan { - private::exclusive(move c) + private::exclusive(c) } /// Receive a message from one of two endpoints. @@ -1211,11 +1211,11 @@ pub trait Select2 { fn select() -> Either; } -impl, Right: Selectable GenericPort> - (Left, Right): Select2 { - + Select2 for (Left, Right) { fn select() -> Either { match self { (ref lp, ref rp) => match select2i(lp, rp) { @@ -1267,24 +1267,24 @@ impl ChanOne { * closed. */ pub fn recv_one(port: PortOne) -> T { - let oneshot::send(message) = recv(move port); - move message + let oneshot::send(message) = recv(port); + message } /// Receive a message from a oneshot pipe unless the connection was closed. pub fn try_recv_one (port: PortOne) -> Option { - let message = try_recv(move port); + let message = try_recv(port); if message.is_none() { None } else { - let oneshot::send(message) = option::unwrap(move message); - Some(move message) + let oneshot::send(message) = option::unwrap(message); + Some(message) } } /// Send a message on a oneshot pipe, failing if the connection was closed. pub fn send_one(chan: ChanOne, data: T) { - oneshot::client::send(move chan, move data); + oneshot::client::send(chan, data); } /** @@ -1293,7 +1293,7 @@ pub fn send_one(chan: ChanOne, data: T) { */ pub fn try_send_one(chan: ChanOne, data: T) -> bool { - oneshot::client::try_send(move chan, move data).is_some() + oneshot::client::try_send(chan, data).is_some() } pub mod rt { @@ -1301,7 +1301,7 @@ pub mod rt { // These are used to hide the option constructors from the // compiler because their names are changing - pub fn make_some(val: T) -> Option { Some(move val) } + pub fn make_some(val: T) -> Option { Some(val) } pub fn make_none() -> Option { None } } @@ -1318,7 +1318,7 @@ pub mod test { c1.send(~"abc"); - match (move p1, move p2).select() { + match (p1, p2).select() { Right(_) => fail!(), _ => () } @@ -1330,9 +1330,9 @@ pub mod test { pub fn test_oneshot() { let (c, p) = oneshot::init(); - oneshot::client::send(move c, ()); + oneshot::client::send(c, ()); - recv_one(move p) + recv_one(p) } #[test] @@ -1341,7 +1341,7 @@ pub mod test { { // Destroy the channel - let _chan = move chan; + let _chan = chan; } assert !port.peek(); diff --git a/src/libcore/private.rs b/src/libcore/private.rs index 9df31bbd81f2c..5b69c348c1591 100644 --- a/src/libcore/private.rs +++ b/src/libcore/private.rs @@ -145,11 +145,11 @@ struct ArcDestruct { cast::reinterpret_cast(&data.unwrapper); let (message, response) = option::swap_unwrap(p); // Send 'ready' and wait for a response. - pipes::send_one(move message, ()); + pipes::send_one(message, ()); // Unkillable wait. Message guaranteed to come. - if pipes::recv_one(move response) { + if pipes::recv_one(response) { // Other task got the data. - cast::forget(move data); + cast::forget(data); } else { // Other task was killed. drop glue takes over. } @@ -157,7 +157,7 @@ struct ArcDestruct { // drop glue takes over. } } else { - cast::forget(move data); + cast::forget(data); } } } @@ -182,13 +182,13 @@ pub unsafe fn unwrap_shared_mutable_state(rc: SharedMutableState) // tried to wake us whether they should hand-off the data to // us. if task::failing() { - pipes::send_one(move response, false); + pipes::send_one(response, false); // Either this swap_unwrap or the one below (at "Got // here") ought to run. cast::forget(option::swap_unwrap(&mut self.ptr)); } else { assert self.ptr.is_none(); - pipes::send_one(move response, true); + pipes::send_one(response, true); } } } @@ -198,8 +198,8 @@ pub unsafe fn unwrap_shared_mutable_state(rc: SharedMutableState) let ptr: ~ArcData = cast::reinterpret_cast(&rc.data); let (p1,c1) = pipes::oneshot(); // () let (p2,c2) = pipes::oneshot(); // bool - let server: UnwrapProto = ~mut Some((move c1,move p2)); - let serverp: int = cast::transmute(move server); + let server: UnwrapProto = ~mut Some((c1,p2)); + let serverp: int = cast::transmute(server); // Try to put our server end in the unwrapper slot. if compare_and_swap(&mut ptr.unwrapper, 0, serverp) { // Got in. Step 0: Tell destructor not to run. We are now it. @@ -210,15 +210,15 @@ pub unsafe fn unwrap_shared_mutable_state(rc: SharedMutableState) if new_count == 0 { // We were the last owner. Can unwrap immediately. // Also we have to free the server endpoints. - let _server: UnwrapProto = cast::transmute(move serverp); + let _server: UnwrapProto = cast::transmute(serverp); option::swap_unwrap(&mut ptr.data) // drop glue takes over. } else { // The *next* person who sees the refcount hit 0 will wake us. let end_result = - DeathThroes { ptr: Some(move ptr), - response: Some(move c2) }; - let mut p1 = Some(move p1); // argh + DeathThroes { ptr: Some(ptr), + response: Some(c2) }; + let mut p1 = Some(p1); // argh do task::rekillable { pipes::recv_one(option::swap_unwrap(&mut p1)); } @@ -230,9 +230,9 @@ pub unsafe fn unwrap_shared_mutable_state(rc: SharedMutableState) } } else { // Somebody else was trying to unwrap. Avoid guaranteed deadlock. - cast::forget(move ptr); + cast::forget(ptr); // Also we have to free the (rejected) server endpoints. - let _server: UnwrapProto = cast::transmute(move serverp); + let _server: UnwrapProto = cast::transmute(serverp); fail!(~"Another task is already unwrapping this ARC!"); } } @@ -248,9 +248,9 @@ pub type SharedMutableState = ArcDestruct; pub unsafe fn shared_mutable_state(data: T) -> SharedMutableState { - let data = ~ArcData { count: 1, unwrapper: 0, data: Some(move data) }; + let data = ~ArcData { count: 1, unwrapper: 0, data: Some(data) }; unsafe { - let ptr = cast::transmute(move data); + let ptr = cast::transmute(data); ArcDestruct(ptr) } } @@ -263,7 +263,7 @@ pub unsafe fn get_shared_mutable_state( let ptr: ~ArcData = cast::reinterpret_cast(&(*rc).data); assert ptr.count > 0; let r = cast::transmute(option::get_ref(&ptr.data)); - cast::forget(move ptr); + cast::forget(ptr); return r; } } @@ -275,7 +275,7 @@ pub unsafe fn get_shared_immutable_state( assert ptr.count > 0; // Cast us back into the correct region let r = cast::transmute_region(option::get_ref(&ptr.data)); - cast::forget(move ptr); + cast::forget(ptr); return r; } } @@ -286,7 +286,7 @@ pub unsafe fn clone_shared_mutable_state(rc: &SharedMutableState) let ptr: ~ArcData = cast::reinterpret_cast(&(*rc).data); let new_count = rusti::atomic_xadd(&mut ptr.count, 1) + 1; assert new_count >= 2; - cast::forget(move ptr); + cast::forget(ptr); } ArcDestruct((*rc).data) } @@ -355,9 +355,9 @@ pub struct Exclusive { x: SharedMutableState> } pub fn exclusive(user_data: T) -> Exclusive { let data = ExData { - lock: LittleLock(), mut failed: false, mut data: move user_data + lock: LittleLock(), mut failed: false, mut data: user_data }; - Exclusive { x: unsafe { shared_mutable_state(move data) } } + Exclusive { x: unsafe { shared_mutable_state(data) } } } impl Clone for Exclusive { @@ -386,7 +386,7 @@ impl Exclusive { (*rec).failed = true; let result = f(&mut (*rec).data); (*rec).failed = false; - move result + result } } } @@ -401,10 +401,10 @@ impl Exclusive { // FIXME(#3724) make this a by-move method on the exclusive pub fn unwrap_exclusive(arc: Exclusive) -> T { - let Exclusive { x: x } = move arc; - let inner = unsafe { unwrap_shared_mutable_state(move x) }; - let ExData { data: data, _ } = move inner; - move data + let Exclusive { x: x } = arc; + let inner = unsafe { unwrap_shared_mutable_state(x) }; + let ExData { data: data, _ } = inner; + data } #[cfg(test)] @@ -430,9 +430,9 @@ pub mod tests { for uint::range(0, num_tasks) |_i| { let total = total.clone(); let (port, chan) = pipes::stream(); - futures.push(move port); + futures.push(port); - do task::spawn |move total, move chan| { + do task::spawn || { for uint::range(0, count) |_i| { do total.with |count| { **count += 1; @@ -455,7 +455,7 @@ pub mod tests { // accesses will also fail. let x = exclusive(1); let x2 = x.clone(); - do task::try |move x2| { + do task::try || { do x2.with |one| { assert *one == 2; } @@ -468,31 +468,31 @@ pub mod tests { #[test] pub fn exclusive_unwrap_basic() { let x = exclusive(~~"hello"); - assert unwrap_exclusive(move x) == ~~"hello"; + assert unwrap_exclusive(x) == ~~"hello"; } #[test] pub fn exclusive_unwrap_contended() { let x = exclusive(~~"hello"); let x2 = ~mut Some(x.clone()); - do task::spawn |move x2| { + do task::spawn || { let x2 = option::swap_unwrap(x2); do x2.with |_hello| { } task::yield(); } - assert unwrap_exclusive(move x) == ~~"hello"; + assert unwrap_exclusive(x) == ~~"hello"; // Now try the same thing, but with the child task blocking. let x = exclusive(~~"hello"); let x2 = ~mut Some(x.clone()); let mut res = None; - do task::task().future_result(|+r| res = Some(move r)).spawn - |move x2| { + do task::task().future_result(|+r| res = Some(r)).spawn + || { let x2 = option::swap_unwrap(x2); - assert unwrap_exclusive(move x2) == ~~"hello"; + assert unwrap_exclusive(x2) == ~~"hello"; } // Have to get rid of our reference before blocking. - { let _x = move x; } // FIXME(#3161) util::ignore doesn't work here + { let _x = x; } // FIXME(#3161) util::ignore doesn't work here let res = option::swap_unwrap(&mut res); res.recv(); } @@ -502,12 +502,12 @@ pub mod tests { let x = exclusive(~~"hello"); let x2 = ~mut Some(x.clone()); let mut res = None; - do task::task().future_result(|+r| res = Some(move r)).spawn - |move x2| { + do task::task().future_result(|+r| res = Some(r)).spawn + || { let x2 = option::swap_unwrap(x2); - assert unwrap_exclusive(move x2) == ~~"hello"; + assert unwrap_exclusive(x2) == ~~"hello"; } - assert unwrap_exclusive(move x) == ~~"hello"; + assert unwrap_exclusive(x) == ~~"hello"; let res = option::swap_unwrap(&mut res); res.recv(); } @@ -526,7 +526,7 @@ pub mod tests { for 10.times { task::yield(); } // try to let the unwrapper go fail!(); // punt it awake from its deadlock } - let _z = unwrap_exclusive(move x); + let _z = unwrap_exclusive(x); do x2.with |_hello| { } }; assert result.is_err(); diff --git a/src/libcore/private/exchange_alloc.rs b/src/libcore/private/exchange_alloc.rs index 4a3c8d59af59b..f7fcf3bdd5ebc 100644 --- a/src/libcore/private/exchange_alloc.rs +++ b/src/libcore/private/exchange_alloc.rs @@ -14,7 +14,7 @@ use c_malloc = libc::malloc; use c_free = libc::free; use managed::raw::{BoxHeaderRepr, BoxRepr}; use cast::transmute; -use ptr::{set_memory, null}; +use ptr::null; use intrinsic::TyDesc; pub unsafe fn malloc(td: *TypeDesc, size: uint) -> *c_void { @@ -25,10 +25,6 @@ pub unsafe fn malloc(td: *TypeDesc, size: uint) -> *c_void { let p = c_malloc(total_size as size_t); assert p.is_not_null(); - // FIXME #4761: Would be very nice to not memset all allocations - let p: *mut u8 = transmute(p); - set_memory(p, 0, total_size); - // FIXME #3475: Converting between our two different tydesc types let td: *TyDesc = transmute(td); diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index acadf079b3b67..c6617bdd516e5 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -44,14 +44,6 @@ extern mod rusti { #[inline(always)] pub pure fn addr_of(val: &T) -> *T { unsafe { rusti::addr_of(*val) } } -/// Get an unsafe mut pointer to a value -#[inline(always)] -pub pure fn mut_addr_of(val: &T) -> *mut T { - unsafe { - cast::reinterpret_cast(&rusti::addr_of(*val)) - } -} - /// Calculate the offset from a pointer #[inline(always)] pub pure fn offset(ptr: *T, count: uint) -> *T { @@ -313,8 +305,8 @@ impl Ord for &const T { pub fn test() { unsafe { struct Pair {mut fst: int, mut snd: int}; - let p = Pair {mut fst: 10, mut snd: 20}; - let pptr: *mut Pair = mut_addr_of(&p); + let mut p = Pair {mut fst: 10, mut snd: 20}; + let pptr: *mut Pair = &mut p; let iptr: *mut int = cast::reinterpret_cast(&pptr); assert (*iptr == 10);; *iptr = 30; diff --git a/src/libcore/rand.rs b/src/libcore/rand.rs index 47a0e11941cb0..97812602ce762 100644 --- a/src/libcore/rand.rs +++ b/src/libcore/rand.rs @@ -116,15 +116,15 @@ impl Rand for Option { } #[allow(non_camel_case_types)] // runtime type -enum rctx {} +enum rust_rng {} #[abi = "cdecl"] extern mod rustrt { unsafe fn rand_seed() -> ~[u8]; - unsafe fn rand_new() -> *rctx; - unsafe fn rand_new_seeded2(&&seed: ~[u8]) -> *rctx; - unsafe fn rand_next(c: *rctx) -> u32; - unsafe fn rand_free(c: *rctx); + unsafe fn rand_new() -> *rust_rng; + unsafe fn rand_new_seeded2(&&seed: ~[u8]) -> *rust_rng; + unsafe fn rand_next(rng: *rust_rng) -> u32; + unsafe fn rand_free(rng: *rust_rng); } /// A random number generator @@ -273,7 +273,7 @@ impl Rng { s = s + str::from_char(self.gen_char_from(charset)); i += 1u; } - move s + s } /// Return a random byte string of the specified length @@ -339,14 +339,14 @@ impl Rng { r.push(item.item); } } - move r + r } /// Shuffle a vec fn shuffle(values: &[T]) -> ~[T] { let mut m = vec::from_slice(values); self.shuffle_mut(m); - move m + m } /// Shuffle a mutable vec in place @@ -363,24 +363,24 @@ impl Rng { } struct RandRes { - c: *rctx, + rng: *rust_rng, drop { unsafe { - rustrt::rand_free(self.c); + rustrt::rand_free(self.rng); } } } -fn RandRes(c: *rctx) -> RandRes { +fn RandRes(rng: *rust_rng) -> RandRes { RandRes { - c: c + rng: rng } } impl Rng for @RandRes { fn next() -> u32 { unsafe { - return rustrt::rand_next((*self).c); + return rustrt::rand_next((*self).rng); } } } diff --git a/src/libcore/reflect.rs b/src/libcore/reflect.rs index eb407cf1128e9..8983c63f42a1f 100644 --- a/src/libcore/reflect.rs +++ b/src/libcore/reflect.rs @@ -42,7 +42,7 @@ pub struct MovePtrAdaptor { inner: V } pub fn MovePtrAdaptor(v: V) -> MovePtrAdaptor { - MovePtrAdaptor { inner: move v } + MovePtrAdaptor { inner: v } } impl MovePtrAdaptor { diff --git a/src/libcore/repr.rs b/src/libcore/repr.rs index c2266f4fdb042..7f1687b08608a 100644 --- a/src/libcore/repr.rs +++ b/src/libcore/repr.rs @@ -200,8 +200,8 @@ impl ReprVisitor { fn visit_ptr_inner(ptr: *c_void, inner: *TyDesc) -> bool { unsafe { let mut u = ReprVisitor(ptr, self.writer); - let v = reflect::MovePtrAdaptor(move u); - visit_tydesc(inner, (move v) as @TyVisitor); + let v = reflect::MovePtrAdaptor(u); + visit_tydesc(inner, (v) as @TyVisitor); true } } @@ -569,8 +569,8 @@ pub fn write_repr(writer: @Writer, object: &T) { let ptr = ptr::to_unsafe_ptr(object) as *c_void; let tydesc = intrinsic::get_tydesc::(); let mut u = ReprVisitor(ptr, writer); - let v = reflect::MovePtrAdaptor(move u); - visit_tydesc(tydesc, (move v) as @TyVisitor) + let v = reflect::MovePtrAdaptor(u); + visit_tydesc(tydesc, (v) as @TyVisitor) } } diff --git a/src/libcore/result.rs b/src/libcore/result.rs index fb824087f2199..64c62c925849f 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -125,9 +125,9 @@ pub pure fn to_either(res: &Result) #[inline(always)] pub pure fn chain(res: Result, op: fn(T) -> Result) -> Result { - match move res { - Ok(move t) => op(move t), - Err(move e) => Err(move e) + match res { + Ok(t) => op(t), + Err(e) => Err(e) } } @@ -144,9 +144,9 @@ pub pure fn chain_err( res: Result, op: fn(t: V) -> Result) -> Result { - match move res { - Ok(move t) => Ok(move t), - Err(move v) => op(move v) + match res { + Ok(t) => Ok(t), + Err(v) => op(v) } } @@ -309,7 +309,7 @@ pub fn map_vec( Err(copy u) => return Err(u) } } - return Ok(move vs); + return Ok(vs); } #[inline(always)] @@ -349,7 +349,7 @@ pub fn map_vec2(ss: &[S], ts: &[T], } i += 1u; } - return Ok(move vs); + return Ok(vs); } /** @@ -377,8 +377,8 @@ pub fn iter_vec2(ss: &[S], ts: &[T], /// Unwraps a result, assuming it is an `ok(T)` #[inline(always)] pub pure fn unwrap(res: Result) -> T { - match move res { - Ok(move t) => move t, + match res { + Ok(t) => t, Err(_) => fail!(~"unwrap called on an err result") } } @@ -386,8 +386,8 @@ pub pure fn unwrap(res: Result) -> T { /// Unwraps a result, assuming it is an `err(U)` #[inline(always)] pub pure fn unwrap_err(res: Result) -> U { - match move res { - Err(move u) => move u, + match res { + Err(u) => u, Ok(_) => fail!(~"unwrap called on an ok result") } } diff --git a/src/libcore/rt.rs b/src/libcore/rt.rs index 769c0b3c70703..60e6118057d6a 100644 --- a/src/libcore/rt.rs +++ b/src/libcore/rt.rs @@ -62,7 +62,7 @@ pub unsafe fn rt_fail_borrowed() { } } -// XXX: Make these signatures agree with exchange_alloc's signatures +// FIXME #4942: Make these signatures agree with exchange_alloc's signatures #[rt(exchange_malloc)] #[lang="exchange_malloc"] pub unsafe fn rt_exchange_malloc(td: *c_char, size: uintptr_t) -> *c_char { diff --git a/src/libcore/run.rs b/src/libcore/run.rs index 1761d7658386f..5103025d12051 100644 --- a/src/libcore/run.rs +++ b/src/libcore/run.rs @@ -250,7 +250,7 @@ pub fn start_program(prog: &str, args: &[~str]) -> Program { r: ProgRepr, drop { unsafe { - // XXX: This is bad. + // FIXME #4943: This is bad. destroy_repr(cast::transmute(&self.r)); } } @@ -258,7 +258,7 @@ pub fn start_program(prog: &str, args: &[~str]) -> Program { fn ProgRes(r: ProgRepr) -> ProgRes { ProgRes { - r: move r + r: r } } @@ -344,11 +344,11 @@ pub fn program_output(prog: &str, args: &[~str]) -> ProgramOutput { let ch_clone = ch.clone(); do task::spawn_sched(task::SingleThreaded) { let errput = readclose(pipe_err.in); - ch.send((2, move errput)); + ch.send((2, errput)); }; do task::spawn_sched(task::SingleThreaded) { let output = readclose(pipe_out.in); - ch_clone.send((1, move output)); + ch_clone.send((1, output)); }; let status = run::waitpid(pid); let mut errs = ~""; @@ -358,10 +358,10 @@ pub fn program_output(prog: &str, args: &[~str]) -> ProgramOutput { let stream = p.recv(); match stream { (1, copy s) => { - outs = move s; + outs = s; } (2, copy s) => { - errs = move s; + errs = s; } (n, _) => { fail!(fmt!("program_output received an unexpected file \ @@ -371,8 +371,8 @@ pub fn program_output(prog: &str, args: &[~str]) -> ProgramOutput { count -= 1; }; return ProgramOutput {status: status, - out: move outs, - err: move errs}; + out: outs, + err: errs}; } } diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 7e7a34f1bab0c..3c15a89081d7f 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -2110,7 +2110,7 @@ pub mod raw { let v: **vec::raw::VecRepr = cast::transmute(v); let repr: *vec::raw::VecRepr = *v; (*repr).unboxed.fill = new_len + 1u; - let null = ptr::mut_offset(ptr::mut_addr_of(&((*repr).unboxed.data)), + let null = ptr::mut_offset(cast::transmute(&((*repr).unboxed.data)), new_len); *null = 0u8; } @@ -2328,7 +2328,7 @@ pub trait OwnedStr { fn push_char(&mut self, c: char); } -pub impl ~str : OwnedStr { +pub impl OwnedStr for ~str { fn push_str(&mut self, v: &str) { push_str(self, v); } diff --git a/src/libcore/sys.rs b/src/libcore/sys.rs index 1571e64511784..afc9d7f1417e4 100644 --- a/src/libcore/sys.rs +++ b/src/libcore/sys.rs @@ -216,7 +216,7 @@ pub mod tests { assert f(20) == 30; - let original_closure: Closure = cast::transmute(move f); + let original_closure: Closure = cast::transmute(f); let actual_function_pointer = original_closure.code; let environment = original_closure.env; @@ -226,7 +226,7 @@ pub mod tests { env: environment }; - let new_f: fn(int) -> int = cast::transmute(move new_closure); + let new_f: fn(int) -> int = cast::transmute(new_closure); assert new_f(20) == 30; } } diff --git a/src/libcore/task/local_data_priv.rs b/src/libcore/task/local_data_priv.rs index 35bbc0347ee11..949c36545dd03 100644 --- a/src/libcore/task/local_data_priv.rs +++ b/src/libcore/task/local_data_priv.rs @@ -73,7 +73,7 @@ unsafe fn get_task_local_map(task: *rust_task) -> TaskLocalMap { cast::bump_box_refcount(map); map } else { - let map = cast::transmute(move map_ptr); + let map = cast::transmute(map_ptr); cast::bump_box_refcount(map); map } @@ -119,7 +119,7 @@ unsafe fn local_get_helper( // overwriting the local_data_box we need to give an extra reference. // We must also give an extra reference when not removing. let (index, data_ptr) = *result; - let data: @T = cast::transmute(move data_ptr); + let data: @T = cast::transmute(data_ptr); cast::bump_box_refcount(data); if do_pop { (*map).set_elt(index, None); @@ -182,6 +182,6 @@ pub unsafe fn local_modify( // Could be more efficient by doing the lookup work, but this is easy. let newdata = modify_fn(local_pop(task, key)); if newdata.is_some() { - local_set(task, key, option::unwrap(move newdata)); + local_set(task, key, option::unwrap(newdata)); } } diff --git a/src/libcore/task/mod.rs b/src/libcore/task/mod.rs index 09c558e3be599..4b15d1f76c98a 100644 --- a/src/libcore/task/mod.rs +++ b/src/libcore/task/mod.rs @@ -203,7 +203,7 @@ pub struct TaskBuilder { pub fn task() -> TaskBuilder { TaskBuilder { opts: default_task_opts(), - gen_body: |body| move body, // Identity function + gen_body: |body| body, // Identity function can_not_copy: None, mut consumed: false, } @@ -315,7 +315,7 @@ impl TaskBuilder { // Construct the future and give it to the caller. let (notify_pipe_po, notify_pipe_ch) = stream::(); - blk(move notify_pipe_po); + blk(notify_pipe_po); // Reconfigure self to use a notify channel. TaskBuilder { @@ -336,7 +336,7 @@ impl TaskBuilder { opts: TaskOpts { linked: self.opts.linked, supervised: self.opts.supervised, - notify_chan: move notify_chan, + notify_chan: notify_chan, sched: SchedOpts { mode: mode, foreign_stack_size: None} }, can_not_copy: None, @@ -366,11 +366,7 @@ impl TaskBuilder { notify_chan: notify_chan, sched: self.opts.sched }, - // tjc: I think this is the line that gets miscompiled - // w/ last-use off, if we leave out the move prev_gen_body? - // that makes no sense, though... - gen_body: |move prev_gen_body, - body| { wrapper(prev_gen_body(move body)) }, + gen_body: |body| { wrapper(prev_gen_body(body)) }, can_not_copy: None, .. self.consume() } @@ -397,12 +393,12 @@ impl TaskBuilder { notify_chan: notify_chan, sched: x.opts.sched }; - spawn::spawn_raw(move opts, (x.gen_body)(move f)); + spawn::spawn_raw(opts, (x.gen_body)(f)); } /// Runs a task, while transfering ownership of one argument to the child. fn spawn_with(arg: A, f: fn~(v: A)) { - let arg = ~mut Some(move arg); - do self.spawn |move arg, move f| { + let arg = ~mut Some(arg); + do self.spawn || { f(option::swap_unwrap(arg)) } } @@ -425,12 +421,12 @@ impl TaskBuilder { let mut result = None; let fr_task_builder = self.future_result(|+r| { - result = Some(move r); + result = Some(r); }); - do fr_task_builder.spawn |move f, move ch| { + do fr_task_builder.spawn || { ch.send(f()); } - match option::unwrap(move result).recv() { + match option::unwrap(result).recv() { Success => result::Ok(po.recv()), Failure => result::Err(()) } @@ -471,7 +467,7 @@ pub fn spawn(f: fn~()) { * This function is equivalent to `task().spawn(f)`. */ - task().spawn(move f) + task().spawn(f) } pub fn spawn_unlinked(f: fn~()) { @@ -480,7 +476,7 @@ pub fn spawn_unlinked(f: fn~()) { * task or the child task fails, the other will not be killed. */ - task().unlinked().spawn(move f) + task().unlinked().spawn(f) } pub fn spawn_supervised(f: fn~()) { @@ -489,7 +485,7 @@ pub fn spawn_supervised(f: fn~()) { * task or the child task fails, the other will not be killed. */ - task().supervised().spawn(move f) + task().supervised().spawn(f) } pub fn spawn_with(arg: A, f: fn~(v: A)) { @@ -503,7 +499,7 @@ pub fn spawn_with(arg: A, f: fn~(v: A)) { * This function is equivalent to `task().spawn_with(arg, f)`. */ - task().spawn_with(move arg, move f) + task().spawn_with(arg, f) } pub fn spawn_sched(mode: SchedMode, f: fn~()) { @@ -519,7 +515,7 @@ pub fn spawn_sched(mode: SchedMode, f: fn~()) { * greater than zero. */ - task().sched_mode(mode).spawn(move f) + task().sched_mode(mode).spawn(f) } pub fn try(f: fn~() -> T) -> Result { @@ -530,7 +526,7 @@ pub fn try(f: fn~() -> T) -> Result { * This is equivalent to task().supervised().try. */ - task().supervised().try(move f) + task().supervised().try(f) } @@ -719,12 +715,12 @@ fn test_spawn_linked_sup_fail_up() { // child fails; parent fails let mut opts = default_task_opts(); opts.linked = true; opts.supervised = true; - move opts + opts }; let b0 = task(); let b1 = TaskBuilder { - opts: move opts, + opts: opts, can_not_copy: None, .. b0 }; @@ -739,12 +735,12 @@ fn test_spawn_linked_sup_fail_down() { // parent fails; child fails let mut opts = default_task_opts(); opts.linked = true; opts.supervised = true; - move opts + opts }; let b0 = task(); let b1 = TaskBuilder { - opts: move opts, + opts: opts, can_not_copy: None, .. b0 }; @@ -843,7 +839,7 @@ fn test_add_wrapper() { let ch = Wrapper { f: Some(ch) }; let b1 = do b0.add_wrapper |body| { let ch = Wrapper { f: Some(ch.f.swap_unwrap()) }; - fn~(move body) { + fn~() { let ch = ch.f.swap_unwrap(); body(); ch.send(()); @@ -857,15 +853,15 @@ fn test_add_wrapper() { #[ignore(cfg(windows))] fn test_future_result() { let mut result = None; - do task().future_result(|+r| { result = Some(move r); }).spawn { } - assert option::unwrap(move result).recv() == Success; + do task().future_result(|+r| { result = Some(r); }).spawn { } + assert option::unwrap(result).recv() == Success; result = None; do task().future_result(|+r| - { result = Some(move r); }).unlinked().spawn { + { result = Some(r); }).unlinked().spawn { fail!(); } - assert option::unwrap(move result).recv() == Failure; + assert option::unwrap(result).recv() == Failure; } #[test] #[should_fail] #[ignore(cfg(windows))] @@ -1024,7 +1020,7 @@ fn avoid_copying_the_body(spawnfn: fn(v: fn~())) { let x = ~1; let x_in_parent = ptr::addr_of(&(*x)) as uint; - do spawnfn |move x| { + do spawnfn || { let x_in_child = ptr::addr_of(&(*x)) as uint; ch.send(x_in_child); } @@ -1041,7 +1037,7 @@ fn test_avoid_copying_the_body_spawn() { #[test] fn test_avoid_copying_the_body_task_spawn() { do avoid_copying_the_body |f| { - do task().spawn |move f| { + do task().spawn || { f(); } } @@ -1050,7 +1046,7 @@ fn test_avoid_copying_the_body_task_spawn() { #[test] fn test_avoid_copying_the_body_try() { do avoid_copying_the_body |f| { - do try |move f| { + do try || { f() }; } @@ -1059,7 +1055,7 @@ fn test_avoid_copying_the_body_try() { #[test] fn test_avoid_copying_the_body_unlinked() { do avoid_copying_the_body |f| { - do spawn_unlinked |move f| { + do spawn_unlinked || { f(); } } @@ -1096,12 +1092,12 @@ fn test_unkillable() { unsafe { do unkillable { let p = ~0; - let pp: *uint = cast::transmute(move p); + let pp: *uint = cast::transmute(p); // If we are killed here then the box will leak po.recv(); - let _p: ~int = cast::transmute(move pp); + let _p: ~int = cast::transmute(pp); } } @@ -1116,7 +1112,7 @@ fn test_unkillable_nested() { let (po, ch) = pipes::stream(); // We want to do this after failing - do spawn_unlinked |move ch| { + do spawn_unlinked || { for iter::repeat(10) { yield() } ch.send(()); } @@ -1132,12 +1128,12 @@ fn test_unkillable_nested() { do unkillable { do unkillable {} // Here's the difference from the previous test. let p = ~0; - let pp: *uint = cast::transmute(move p); + let pp: *uint = cast::transmute(p); // If we are killed here then the box will leak po.recv(); - let _p: ~int = cast::transmute(move pp); + let _p: ~int = cast::transmute(pp); } } @@ -1181,7 +1177,7 @@ fn test_child_doesnt_ref_parent() { fn test_sched_thread_per_core() { let (port, chan) = pipes::stream(); - do spawn_sched(ThreadPerCore) |move chan| { + do spawn_sched(ThreadPerCore) || { unsafe { let cores = rt::rust_num_threads(); let reported_threads = rt::rust_sched_threads(); @@ -1197,7 +1193,7 @@ fn test_sched_thread_per_core() { fn test_spawn_thread_on_demand() { let (port, chan) = pipes::stream(); - do spawn_sched(ManualThreads(2)) |move chan| { + do spawn_sched(ManualThreads(2)) || { unsafe { let max_threads = rt::rust_sched_threads(); assert(max_threads as int == 2); @@ -1206,7 +1202,7 @@ fn test_spawn_thread_on_demand() { let (port2, chan2) = pipes::stream(); - do spawn_sched(CurrentScheduler) |move chan2| { + do spawn_sched(CurrentScheduler) || { chan2.send(()); } diff --git a/src/libcore/task/spawn.rs b/src/libcore/task/spawn.rs index a57e8a8ee44b7..d72cacc2c4be7 100644 --- a/src/libcore/task/spawn.rs +++ b/src/libcore/task/spawn.rs @@ -93,7 +93,7 @@ use uint; use util; macro_rules! move_it ( - { $x:expr } => ( unsafe { let y = move *ptr::addr_of(&($x)); move y } ) + { $x:expr } => ( unsafe { let y = *ptr::addr_of(&($x)); y } ) ) type TaskSet = LinearSet<*rust_task>; @@ -195,10 +195,10 @@ fn each_ancestor(list: &mut AncestorList, if coalesce_this.is_some() { // Needed coalesce. Our next ancestor becomes our old // ancestor's next ancestor. ("next = old_next->next;") - *list = move option::unwrap(move coalesce_this); + *list = option::unwrap(coalesce_this); } else { // No coalesce; restore from tmp. ("next = old_next;") - *list = move tmp_list; + *list = tmp_list; } return early_break; } @@ -279,7 +279,7 @@ fn each_ancestor(list: &mut AncestorList, // Swap the list out here; the caller replaces us with it. let rest = util::replace(&mut nobe.ancestors, AncestorList(None)); - (Some(move rest), need_unwind) + (Some(rest), need_unwind) } else { (None, need_unwind) } @@ -292,8 +292,8 @@ fn each_ancestor(list: &mut AncestorList, // If this trips, more likely the problem is 'blk' failed inside. let tmp_arc = option::swap_unwrap(&mut *parent_group); let result = do access_group(&tmp_arc) |tg_opt| { blk(tg_opt) }; - *parent_group = move Some(move tmp_arc); - move result + *parent_group = Some(tmp_arc); + result } } } @@ -337,15 +337,15 @@ struct TCB { fn TCB(me: *rust_task, tasks: TaskGroupArc, ancestors: AncestorList, is_main: bool, notifier: Option) -> TCB { - let notifier = move notifier; + let notifier = notifier; notifier.iter(|x| { x.failed = false; }); TCB { me: me, - tasks: move tasks, - ancestors: move ancestors, + tasks: tasks, + ancestors: ancestors, is_main: is_main, - notifier: move notifier + notifier: notifier } } @@ -360,7 +360,7 @@ struct AutoNotify { fn AutoNotify(chan: Chan) -> AutoNotify { AutoNotify { - notify_chan: move chan, + notify_chan: chan, failed: true // Un-set above when taskgroup successfully made. } } @@ -370,10 +370,10 @@ fn enlist_in_taskgroup(state: TaskGroupInner, me: *rust_task, let newstate = util::replace(&mut *state, None); // If 'None', the group was failing. Can't enlist. if newstate.is_some() { - let group = option::unwrap(move newstate); + let group = option::unwrap(newstate); taskset_insert(if is_member { &mut group.members } else { &mut group.descendants }, me); - *state = Some(move group); + *state = Some(group); true } else { false @@ -386,10 +386,10 @@ fn leave_taskgroup(state: TaskGroupInner, me: *rust_task, let newstate = util::replace(&mut *state, None); // If 'None', already failing and we've already gotten a kill signal. if newstate.is_some() { - let group = option::unwrap(move newstate); + let group = option::unwrap(newstate); taskset_remove(if is_member { &mut group.members } else { &mut group.descendants }, me); - *state = Some(move group); + *state = Some(group); } } @@ -410,7 +410,7 @@ fn kill_taskgroup(state: TaskGroupInner, me: *rust_task, is_main: bool) { // That's ok; only one task needs to do the dirty work. (Might also // see 'None' if Somebody already failed and we got a kill signal.) if newstate.is_some() { - let group = option::unwrap(move newstate); + let group = option::unwrap(newstate); for taskset_each(&group.members) |sibling| { // Skip self - killing ourself won't do much good. if sibling != me { @@ -457,7 +457,7 @@ fn gen_child_taskgroup(linked: bool, supervised: bool) })); // Main task/group has no ancestors, no notifier, etc. let group = - @TCB(spawner, move tasks, AncestorList(None), true, None); + @TCB(spawner, tasks, AncestorList(None), true, None); local_set(spawner, taskgroup_key!(), group); group } @@ -472,7 +472,7 @@ fn gen_child_taskgroup(linked: bool, supervised: bool) // Child's ancestors are spawner's ancestors. let a = share_ancestors(&mut spawner_group.ancestors); // Propagate main-ness. - (move g, move a, spawner_group.is_main) + (g, a, spawner_group.is_main) } else { // Child is in a separate group from spawner. let g = private::exclusive(Some(TaskGroupData { @@ -504,7 +504,7 @@ fn gen_child_taskgroup(linked: bool, supervised: bool) // Child has no ancestors. AncestorList(None) }; - (move g, move a, false) + (g, a, false) }; } @@ -515,10 +515,10 @@ fn gen_child_taskgroup(linked: bool, supervised: bool) // None { ancestor_list(None) } let tmp = util::replace(&mut **ancestors, None); if tmp.is_some() { - let ancestor_arc = option::unwrap(move tmp); + let ancestor_arc = option::unwrap(tmp); let result = ancestor_arc.clone(); - **ancestors = move Some(move ancestor_arc); - AncestorList(Some(move result)) + **ancestors = Some(ancestor_arc); + AncestorList(Some(result)) } else { AncestorList(None) } @@ -530,7 +530,7 @@ pub fn spawn_raw(opts: TaskOpts, f: fn~()) { gen_child_taskgroup(opts.linked, opts.supervised); unsafe { - let child_data = ~mut Some((move child_tg, move ancestors, move f)); + let child_data = ~mut Some((child_tg, ancestors, f)); // Being killed with the unsafe task/closure pointers would leak them. do unkillable { // Agh. Get move-mode items into the closure. FIXME (#2829) @@ -548,8 +548,8 @@ pub fn spawn_raw(opts: TaskOpts, f: fn~()) { Some(option::swap_unwrap(&mut opts.notify_chan)) }; - let child_wrapper = make_child_wrapper(new_task, move child_tg, - move ancestors, is_main, move notify_chan, move f); + let child_wrapper = make_child_wrapper(new_task, child_tg, + ancestors, is_main, notify_chan, f); let closure = cast::transmute(&child_wrapper); @@ -557,7 +557,7 @@ pub fn spawn_raw(opts: TaskOpts, f: fn~()) { // closure. (Reordering them wouldn't help - then getting killed // between them would leak.) rt::start_task(new_task, closure); - cast::forget(move child_wrapper); + cast::forget(child_wrapper); } } @@ -571,8 +571,8 @@ pub fn spawn_raw(opts: TaskOpts, f: fn~()) { ancestors: AncestorList, is_main: bool, notify_chan: Option>, f: fn~()) -> fn~() { - let child_data = ~mut Some((move child_arc, move ancestors)); - return fn~(move notify_chan, move child_data, move f) { + let child_data = ~mut Some((child_arc, ancestors)); + return fn~() { // Agh. Get move-mode items into the closure. FIXME (#2829) let mut (child_arc, ancestors) = option::swap_unwrap(child_data); // Child task runs this code. @@ -584,14 +584,14 @@ pub fn spawn_raw(opts: TaskOpts, f: fn~()) { let notifier = match notify_chan { Some(ref notify_chan_value) => { let moved_ncv = move_it!(*notify_chan_value); - Some(AutoNotify(move moved_ncv)) + Some(AutoNotify(moved_ncv)) } _ => None }; if enlist_many(child, &child_arc, &mut ancestors) { - let group = @TCB(child, move child_arc, move ancestors, - is_main, move notifier); + let group = @TCB(child, child_arc, ancestors, + is_main, notifier); unsafe { local_set(child, taskgroup_key!(), group); } @@ -694,7 +694,7 @@ fn test_spawn_raw_unsupervise() { notify_chan: None, .. default_task_opts() }; - do spawn_raw(move opts) { + do spawn_raw(opts) { fail!(); } } @@ -708,7 +708,7 @@ fn test_spawn_raw_notify_success() { notify_chan: Some(notify_ch), .. default_task_opts() }; - do spawn_raw(move opts) { + do spawn_raw(opts) { } assert notify_po.recv() == Success; } @@ -724,7 +724,7 @@ fn test_spawn_raw_notify_failure() { notify_chan: Some(notify_ch), .. default_task_opts() }; - do spawn_raw(move opts) { + do spawn_raw(opts) { fail!(); } assert notify_po.recv() == Failure; diff --git a/src/libcore/to_bytes.rs b/src/libcore/to_bytes.rs index 58ecf2560ace0..10efa9196a7bb 100644 --- a/src/libcore/to_bytes.rs +++ b/src/libcore/to_bytes.rs @@ -170,7 +170,7 @@ impl IterBytes for char { pub mod x32 { use to_bytes::{Cb, IterBytes}; - pub impl uint: IterBytes { + pub impl IterBytes for uint { #[inline(always)] pure fn iter_bytes(&self, lsb0: bool, f: Cb) { (*self as u32).iter_bytes(lsb0, f) @@ -182,7 +182,7 @@ pub mod x32 { pub mod x64 { use to_bytes::{Cb, IterBytes}; - pub impl uint: IterBytes { + pub impl IterBytes for uint { #[inline(always)] pure fn iter_bytes(&self, lsb0: bool, f: Cb) { (*self as u64).iter_bytes(lsb0, f) diff --git a/src/libcore/to_str.rs b/src/libcore/to_str.rs index a1e77a494d5bd..e545f6567ec32 100644 --- a/src/libcore/to_str.rs +++ b/src/libcore/to_str.rs @@ -87,7 +87,7 @@ impl ToStr for ~[A] { } } str::push_char(&mut acc, ']'); - move acc + acc } } } diff --git a/src/libcore/util.rs b/src/libcore/util.rs index 87cbcdfe30b9a..eea172a43ced1 100644 --- a/src/libcore/util.rs +++ b/src/libcore/util.rs @@ -19,7 +19,7 @@ use prelude::*; /// The identity function. #[inline(always)] -pub pure fn id(x: T) -> T { move x } +pub pure fn id(x: T) -> T { x } /// Ignores a value. #[inline(always)] @@ -37,10 +37,10 @@ pub fn with( // we wouldn't need to copy... let old_value = *ptr; - *ptr = move new_value; + *ptr = new_value; let result = op(); - *ptr = move old_value; - return move result; + *ptr = old_value; + return result; } /** @@ -58,9 +58,9 @@ pub fn swap(x: &mut T, y: &mut T) { */ #[inline(always)] pub fn replace(dest: &mut T, src: T) -> T { - let mut tmp = move src; + let mut tmp = src; swap(dest, &mut tmp); - move tmp + tmp } /// A non-copyable dummy type. @@ -109,7 +109,7 @@ mod tests { let x = ~[(5, false)]; //FIXME #3387 assert x.eq(id(copy x)); let y = copy x; - assert x.eq(&id(move y)); + assert x.eq(&id(y)); } #[test] pub fn test_swap() { diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 3808e13be1cbc..43ab77287a639 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -220,7 +220,7 @@ pub pure fn head(v: &[const T]) -> T { v[0] } /// Returns a vector containing all but the first element of a slice pub pure fn tail(v: &[const T]) -> ~[T] { - return slice(v, 1u, len(v)); + slice(v, 1u, len(v)).to_vec() } /** @@ -228,13 +228,13 @@ pub pure fn tail(v: &[const T]) -> ~[T] { * elements of a slice */ pub pure fn tailn(v: &[const T], n: uint) -> ~[T] { - slice(v, n, len(v)) + slice(v, n, len(v)).to_vec() } /// Returns a vector containing all but the last element of a slice pub pure fn init(v: &[const T]) -> ~[T] { assert len(v) != 0u; - slice(v, 0u, len(v) - 1u) + slice(v, 0u, len(v) - 1u).to_vec() } /// Returns the last element of the slice `v`, failing if the slice is empty. @@ -252,20 +252,9 @@ pub pure fn last_opt(v: &[const T]) -> Option { Some(v[len(v) - 1u]) } -/// Returns a copy of the elements from [`start`..`end`) from `v`. -pub pure fn slice(v: &[const T], start: uint, end: uint) -> ~[T] { - assert (start <= end); - assert (end <= len(v)); - let mut result = ~[]; - unsafe { - for uint::range(start, end) |i| { result.push(v[i]) } - } - result -} - /// Return a slice that points into another slice. #[inline(always)] -pub pure fn view(v: &r/[T], start: uint, end: uint) -> &r/[T] { +pub pure fn slice(v: &r/[T], start: uint, end: uint) -> &r/[T] { assert (start <= end); assert (end <= len(v)); do as_imm_buf(v) |p, _len| { @@ -279,7 +268,9 @@ pub pure fn view(v: &r/[T], start: uint, end: uint) -> &r/[T] { /// Return a slice that points into another slice. #[inline(always)] -pub pure fn mut_view(v: &r/[mut T], start: uint, end: uint) -> &r/[mut T] { +pub pure fn mut_slice(v: &r/[mut T], start: uint, + end: uint) -> &r/[mut T] { + assert (start <= end); assert (end <= len(v)); do as_mut_buf(v) |p, _len| { @@ -293,7 +284,7 @@ pub pure fn mut_view(v: &r/[mut T], start: uint, end: uint) -> &r/[mut T] { /// Return a slice that points into another slice. #[inline(always)] -pub pure fn const_view(v: &r/[const T], start: uint, +pub pure fn const_slice(v: &r/[const T], start: uint, end: uint) -> &r/[const T] { assert (start <= end); assert (end <= len(v)); @@ -319,12 +310,12 @@ pub fn split(v: &[T], f: fn(t: &T) -> bool) -> ~[~[T]] { match position_between(v, start, ln, f) { None => break, Some(i) => { - result.push(slice(v, start, i)); + result.push(slice(v, start, i).to_vec()); start = i + 1u; } } } - result.push(slice(v, start, ln)); + result.push(slice(v, start, ln).to_vec()); result } @@ -343,14 +334,14 @@ pub fn splitn(v: &[T], n: uint, f: fn(t: &T) -> bool) -> ~[~[T]] { match position_between(v, start, ln, f) { None => break, Some(i) => { - result.push(slice(v, start, i)); + result.push(slice(v, start, i).to_vec()); // Make sure to skip the separator. start = i + 1u; count -= 1u; } } } - result.push(slice(v, start, ln)); + result.push(slice(v, start, ln).to_vec()); result } @@ -368,12 +359,12 @@ pub fn rsplit(v: &[T], f: fn(t: &T) -> bool) -> ~[~[T]] { match rposition_between(v, 0, end, f) { None => break, Some(i) => { - result.push(slice(v, i + 1, end)); + result.push(slice(v, i + 1, end).to_vec()); end = i; } } } - result.push(slice(v, 0u, end)); + result.push(slice(v, 0u, end).to_vec()); reverse(result); return result; } @@ -393,14 +384,14 @@ pub fn rsplitn(v: &[T], n: uint, f: fn(t: &T) -> bool) -> ~[~[T]] { match rposition_between(v, 0u, end, f) { None => break, Some(i) => { - result.push(slice(v, i + 1u, end)); + result.push(slice(v, i + 1u, end).to_vec()); // Make sure to skip the separator. end = i; count -= 1u; } } } - result.push(slice(v, 0u, end)); + result.push(slice(v, 0u, end).to_vec()); reverse(result); result } @@ -478,15 +469,15 @@ pub fn shift(v: &mut ~[T]) -> T { // popped. For the moment it unsafely exists at both the head and last // positions { - let first_slice = view(*v, 0, 1); - let last_slice = view(*v, next_ln, ln); + let first_slice = slice(*v, 0, 1); + let last_slice = slice(*v, next_ln, ln); raw::copy_memory(::cast::transmute(last_slice), first_slice, 1); } // Memcopy everything to the left one element { - let init_slice = view(*v, 0, next_ln); - let tail_slice = view(*v, 1, ln); + let init_slice = slice(*v, 0, next_ln); + let tail_slice = slice(*v, 1, ln); raw::copy_memory(::cast::transmute(init_slice), tail_slice, next_ln); @@ -614,7 +605,7 @@ unsafe fn push_fast(v: &mut ~[T], initval: T) { (**repr).unboxed.fill += sys::nonzero_size_of::(); let p = addr_of(&((**repr).unboxed.data)); let p = ptr::offset(p, fill) as *mut T; - rusti::move_val_init(&mut(*p), move initval); + rusti::move_val_init(&mut(*p), initval); } #[inline(never)] @@ -1464,9 +1455,9 @@ pure fn each_permutation(v: &[T], put: fn(ts: &[T]) -> bool) { let mut i = 0u; while i < ln { let elt = v[i]; - let mut rest = slice(v, 0u, i); + let mut rest = slice(v, 0u, i).to_vec(); unsafe { - rest.push_all(const_view(v, i+1u, ln)); + rest.push_all(const_slice(v, i+1u, ln)); for each_permutation(rest) |permutation| { if !put(append(~[elt], permutation)) { return; @@ -1485,7 +1476,7 @@ pub pure fn windowed(nn: uint, xx: &[TT]) -> ~[~[TT]] { let len = vec::len(xx); if ii+nn <= len { unsafe { - ww.push(vec::slice(xx, ii, ii+nn)); + ww.push(slice(xx, ii, ii+nn).to_vec()); } } } @@ -1689,7 +1680,7 @@ impl CopyableVector for &[const T] { /// Returns a copy of the elements from [`start`..`end`) from `v`. #[inline] pure fn slice(&self, start: uint, end: uint) -> ~[T] { - slice(*self, start, end) + slice(*self, start, end).to_vec() } /// Returns all but the first element of a vector @@ -1713,7 +1704,7 @@ impl ImmutableVector for &[T] { /// Return a slice that points into another slice. #[inline] pure fn view(&self, start: uint, end: uint) -> &self/[T] { - view(*self, start, end) + slice(*self, start, end) } /// Reduce a vector from right to left @@ -2566,42 +2557,45 @@ mod tests { #[test] fn test_slice() { - // Test on-stack -> on-stack slice. - let mut v = slice(~[1, 2, 3], 1u, 3u); - assert (len(v) == 2u); - assert (v[0] == 2); - assert (v[1] == 3); - - // Test on-heap -> on-stack slice. - v = slice(~[1, 2, 3, 4, 5], 0u, 3u); - assert (len(v) == 3u); - assert (v[0] == 1); - assert (v[1] == 2); - assert (v[2] == 3); - - // Test on-heap -> on-heap slice. - v = slice(~[1, 2, 3, 4, 5, 6], 1u, 6u); - assert (len(v) == 5u); - assert (v[0] == 2); - assert (v[1] == 3); - assert (v[2] == 4); - assert (v[3] == 5); - assert (v[4] == 6); + // Test fixed length vector. + let vec_fixed = [1, 2, 3, 4]; + let v_a = slice(vec_fixed, 1u, len(vec_fixed)).to_vec(); + assert (len(v_a) == 3u); + assert (v_a[0] == 2); + assert (v_a[1] == 3); + assert (v_a[2] == 4); + + // Test on stack. + let vec_stack = &[1, 2, 3]; + let v_b = slice(vec_stack, 1u, 3u).to_vec(); + assert (len(v_b) == 2u); + assert (v_b[0] == 2); + assert (v_b[1] == 3); + + // Test on managed heap. + let vec_managed = @[1, 2, 3, 4, 5]; + let v_c = slice(vec_managed, 0u, 3u).to_vec(); + assert (len(v_c) == 3u); + assert (v_c[0] == 1); + assert (v_c[1] == 2); + assert (v_c[2] == 3); + + // Test on exchange heap. + let vec_unique = ~[1, 2, 3, 4, 5, 6]; + let v_d = slice(vec_unique, 1u, 6u).to_vec(); + assert (len(v_d) == 5u); + assert (v_d[0] == 2); + assert (v_d[1] == 3); + assert (v_d[2] == 4); + assert (v_d[3] == 5); + assert (v_d[4] == 6); } #[test] fn test_pop() { - // Test on-stack pop. - let mut v = ~[1, 2, 3]; - let mut e = v.pop(); - assert (len(v) == 2u); - assert (v[0] == 1); - assert (v[1] == 2); - assert (e == 3); - // Test on-heap pop. - v = ~[1, 2, 3, 4, 5]; - e = v.pop(); + let mut v = ~[1, 2, 3, 4, 5]; + let e = v.pop(); assert (len(v) == 4u); assert (v[0] == 1); assert (v[1] == 2); diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index df362b7798408..bd9c7f1616dc7 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -156,7 +156,7 @@ pub mod jit { code: entry, env: ptr::null() }; - let func: fn(++argv: ~[~str]) = cast::transmute(move closure); + let func: fn(++argv: ~[~str]) = cast::transmute(closure); func(~[/*bad*/copy sess.opts.binary]); } @@ -497,8 +497,7 @@ pub fn build_link_meta(sess: Session, c: &ast::crate, output: &Path, let cmh_items = attr::sort_meta_items(cmh_items); - symbol_hasher.reset(); - for cmh_items.each |m| { + fn hash(symbol_hasher: &hash::State, m: &@ast::meta_item) { match m.node { ast::meta_name_value(ref key, value) => { symbol_hasher.write_str(len_and_str((*key))); @@ -507,13 +506,20 @@ pub fn build_link_meta(sess: Session, c: &ast::crate, output: &Path, ast::meta_word(ref name) => { symbol_hasher.write_str(len_and_str((*name))); } - ast::meta_list(_, _) => { - // FIXME (#607): Implement this - fail!(~"unimplemented meta_item variant"); + ast::meta_list(ref name, ref mis) => { + symbol_hasher.write_str(len_and_str((*name))); + for mis.each |m_| { + hash(symbol_hasher, m_); + } } } } + symbol_hasher.reset(); + for cmh_items.each |m| { + hash(symbol_hasher, m); + } + for dep_hashes.each |dh| { symbol_hasher.write_str(len_and_str(*dh)); } @@ -559,11 +565,11 @@ pub fn build_link_meta(sess: Session, c: &ast::crate, output: &Path, let {name: opt_name, vers: opt_vers, cmh_items: cmh_items} = provided_link_metas(sess, c); - let name = crate_meta_name(sess, output, move opt_name); - let vers = crate_meta_vers(sess, move opt_vers); + let name = crate_meta_name(sess, output, opt_name); + let vers = crate_meta_vers(sess, opt_vers); let dep_hashes = cstore::get_dep_hashes(sess.cstore); let extras_hash = - crate_meta_extras_hash(symbol_hasher, move cmh_items, + crate_meta_extras_hash(symbol_hasher, cmh_items, dep_hashes); return {name: name, vers: vers, extras_hash: extras_hash}; diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 18e89635ab298..1bcd67bd67b53 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -157,7 +157,7 @@ pub fn get_relative_to(abs1: &Path, abs2: &Path) -> Path { let mut path = ~[]; for uint::range(start_idx, len1 - 1) |_i| { path.push(~".."); }; - path.push_all(vec::view(split2, start_idx, len2 - 1)); + path.push_all(vec::slice(split2, start_idx, len2 - 1)); if !path.is_empty() { return Path("").push_many(path); diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index b0024bace37e0..e091e93f3726c 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -88,10 +88,12 @@ pub fn default_configuration(sess: Session, +argv0: ~str, input: input) -> let mk = attr::mk_name_value_item_str; - let (arch,wordsz) = match sess.targ_cfg.arch { - session::arch_x86 => (~"x86",~"32"), - session::arch_x86_64 => (~"x86_64",~"64"), - session::arch_arm => (~"arm",~"32") + // ARM is bi-endian, however using NDK seems to default + // to little-endian unless a flag is provided. + let (end,arch,wordsz) = match sess.targ_cfg.arch { + session::arch_x86 => (~"little",~"x86",~"32"), + session::arch_x86_64 => (~"little",~"x86_64",~"64"), + session::arch_arm => (~"little",~"arm",~"32") }; return ~[ // Target bindings. @@ -99,6 +101,7 @@ pub fn default_configuration(sess: Session, +argv0: ~str, input: input) -> mk(~"target_os", tos), mk(~"target_family", str::from_slice(os::FAMILY)), mk(~"target_arch", arch), + mk(~"target_endian", end), mk(~"target_word_size", wordsz), mk(~"target_libc", libc), // Build bindings. @@ -172,9 +175,10 @@ pub fn time(do_it: bool, what: ~str, thunk: fn() -> T) -> T { let end = std::time::precise_time_s(); io::stdout().write_str(fmt!("time: %3.3f s\t%s\n", end - start, what)); - move rv + rv } +#[deriving_eq] pub enum compile_upto { cu_parse, cu_expand, @@ -183,21 +187,14 @@ pub enum compile_upto { cu_everything, } -pub impl compile_upto : cmp::Eq { - pure fn eq(&self, other: &compile_upto) -> bool { - ((*self) as uint) == ((*other) as uint) - } - pure fn ne(&self, other: &compile_upto) -> bool { !(*self).eq(other) } -} - -pub fn compile_upto(sess: Session, cfg: ast::crate_cfg, - input: input, upto: compile_upto, - outputs: Option) - -> {crate: @ast::crate, tcx: Option} { +// For continuing compilation after a parsed crate has been +// modified +pub fn compile_rest(sess: Session, cfg: ast::crate_cfg, + upto: compile_upto, outputs: Option, + curr: Option<@ast::crate>) + -> {crate: @ast::crate, tcx: Option} { let time_passes = sess.time_passes(); - let mut crate = time(time_passes, ~"parsing", - || parse_input(sess, copy cfg, input) ); - if upto == cu_parse { return {crate: crate, tcx: None}; } + let mut crate = curr.get(); *sess.building_library = session::building_library( sess.opts.crate_type, crate, sess.opts.test); @@ -257,7 +254,7 @@ pub fn compile_upto(sess: Session, cfg: ast::crate_cfg, let (llmod, link_meta) = { let ty_cx = ty::mk_ctxt(sess, def_map, ast_map, freevars, - region_map, rp_set, move lang_items, crate); + region_map, rp_set, lang_items, crate); let (method_map, vtable_map) = time(time_passes, ~"typechecking", || @@ -328,7 +325,6 @@ pub fn compile_upto(sess: Session, cfg: ast::crate_cfg, }; - time(time_passes, ~"LLVM passes", || link::write::run_passes(sess, llmod, &outputs.obj_filename)); @@ -348,9 +344,20 @@ pub fn compile_upto(sess: Session, cfg: ast::crate_cfg, return {crate: crate, tcx: None}; } +pub fn compile_upto(sess: Session, +cfg: ast::crate_cfg, + input: input, upto: compile_upto, + outputs: Option) + -> {crate: @ast::crate, tcx: Option} { + let time_passes = sess.time_passes(); + let mut crate = time(time_passes, ~"parsing", + || parse_input(sess, copy cfg, input) ); + if upto == cu_parse { return {crate: crate, tcx: None}; } + + compile_rest(sess, cfg, upto, outputs, Some(crate)) +} + pub fn compile_input(sess: Session, +cfg: ast::crate_cfg, input: input, outdir: &Option, output: &Option) { - let upto = if sess.opts.parse_only { cu_parse } else if sess.opts.no_trans { cu_no_trans } else { cu_everything }; diff --git a/src/librustc/driver/session.rs b/src/librustc/driver/session.rs index cb55051c57f09..1a299f22ec057 100644 --- a/src/librustc/driver/session.rs +++ b/src/librustc/driver/session.rs @@ -29,24 +29,12 @@ use syntax::parse::parse_sess; use syntax::{ast, codemap}; use syntax; +#[deriving_eq] pub enum os { os_win32, os_macos, os_linux, os_android, os_freebsd, } -pub impl os : cmp::Eq { - pure fn eq(&self, other: &os) -> bool { - ((*self) as uint) == ((*other) as uint) - } - pure fn ne(&self, other: &os) -> bool { !(*self).eq(other) } -} - +#[deriving_eq] pub enum arch { arch_x86, arch_x86_64, arch_arm, } -pub impl arch : cmp::Eq { - pure fn eq(&self, other: &arch) -> bool { - ((*self) as uint) == ((*other) as uint) - } - pure fn ne(&self, other: &arch) -> bool { !(*self).eq(other) } -} - pub enum crate_type { bin_crate, lib_crate, unknown_crate, } pub type config = @@ -117,6 +105,7 @@ pub fn debugging_opts_map() -> ~[(~str, ~str, uint)] { ] } +#[deriving_eq] pub enum OptLevel { No, // -O0 Less, // -O1 @@ -124,13 +113,6 @@ pub enum OptLevel { Aggressive // -O3 } -pub impl OptLevel : cmp::Eq { - pure fn eq(&self, other: &OptLevel) -> bool { - ((*self) as uint) == ((*other) as uint) - } - pure fn ne(&self, other: &OptLevel) -> bool { !(*self).eq(other) } -} - pub type options = // The crate config requested for the session, which may be combined // with additional crate configurations during the compile process diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index 4b63bb3721538..c58ab494ed364 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -132,6 +132,7 @@ pub enum RealPredicate { // enum for the LLVM TypeKind type - must stay in sync with the def of // LLVMTypeKind in llvm/include/llvm-c/Core.h +#[deriving_eq] pub enum TypeKind { Void = 0, Half = 1, @@ -151,46 +152,6 @@ pub enum TypeKind { X86_MMX = 15 } -pub impl TypeKind : cmp::Eq { - pure fn eq(&self, other: &TypeKind) -> bool { - match ((*self), (*other)) { - (Void, Void) => true, - (Half, Half) => true, - (Float, Float) => true, - (Double, Double) => true, - (X86_FP80, X86_FP80) => true, - (FP128, FP128) => true, - (PPC_FP128, PPC_FP128) => true, - (Label, Label) => true, - (Integer, Integer) => true, - (Function, Function) => true, - (Struct, Struct) => true, - (Array, Array) => true, - (Pointer, Pointer) => true, - (Vector, Vector) => true, - (Metadata, Metadata) => true, - (X86_MMX, X86_MMX) => true, - (Void, _) => false, - (Half, _) => false, - (Float, _) => false, - (Double, _) => false, - (X86_FP80, _) => false, - (FP128, _) => false, - (PPC_FP128, _) => false, - (Label, _) => false, - (Integer, _) => false, - (Function, _) => false, - (Struct, _) => false, - (Array, _) => false, - (Pointer, _) => false, - (Vector, _) => false, - (Metadata, _) => false, - (X86_MMX, _) => false, - } - } - pure fn ne(&self, other: &TypeKind) -> bool { !(*self).eq(other) } -} - pub enum AtomicBinOp { Xchg = 0, Add = 1, @@ -1481,7 +1442,7 @@ pub fn struct_element_types(struct_ty: TypeRef) -> ~[TypeRef] { llvm::LLVMGetStructElementTypes( struct_ty, ptr::to_mut_unsafe_ptr(&mut buf[0])); } - return move buf; + return buf; } } diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index a2203f0a3998a..d069c95c5ec9d 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -55,6 +55,7 @@ pub fn read_crates(diag: span_handler, visit_view_item: |a| visit_view_item(e, a), visit_item: |a| visit_item(e, a), .. *visit::default_simple_visitor()}); + visit_crate(e, crate); visit::visit_crate(crate, (), v); dump_crates(e.crate_cache); warn_if_multiple_versions(e, diag, e.crate_cache); @@ -125,6 +126,20 @@ struct Env { intr: @ident_interner } +fn visit_crate(e: @mut Env, c: ast::crate) { + let cstore = e.cstore; + let link_args = attr::find_attrs_by_name(c.node.attrs, "link_args"); + + for link_args.each |a| { + match attr::get_meta_item_value_str(attr::attr_meta(*a)) { + Some(ref linkarg) => { + cstore::add_used_link_args(cstore, (/*bad*/copy *linkarg)); + } + None => {/* fallthrough */ } + } + } +} + fn visit_view_item(e: @mut Env, i: @ast::view_item) { match /*bad*/copy i.node { ast::view_item_use(ident, meta_items, id) => { @@ -181,7 +196,7 @@ fn visit_item(e: @mut Env, i: @ast::item) { for link_args.each |a| { match attr::get_meta_item_value_str(attr::attr_meta(*a)) { Some(ref linkarg) => { - cstore::add_used_link_args(cstore, (/*bad*/copy *linkarg)); + cstore::add_used_link_args(cstore, *linkarg); } None => {/* fallthrough */ } } diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 73ec872b6a6ec..84a588e48860c 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -119,7 +119,7 @@ pub fn get_used_libraries(cstore: @mut CStore) -> ~[~str] { return /*bad*/copy cstore.used_libraries; } -pub fn add_used_link_args(cstore: @mut CStore, args: ~str) { +pub fn add_used_link_args(cstore: @mut CStore, args: &str) { cstore.used_link_args.push_all(str::split_char(args, ' ')); } diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 3564e10790d3a..644cf3af0bd54 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -64,7 +64,7 @@ fn lookup_hash(d: ebml::Doc, eq_fn: fn(x:&[u8]) -> bool, hash: uint) -> let belt = tag_index_buckets_bucket_elt; for reader::tagged_docs(tagged_doc.doc, belt) |elt| { let pos = io::u64_from_be_bytes(*elt.data, elt.start, 4u) as uint; - if eq_fn(vec::view(*elt.data, elt.start + 4u, elt.end)) { + if eq_fn(vec::slice(*elt.data, elt.start + 4u, elt.end)) { return Some(reader::doc_at(d.data, pos).doc); } }; @@ -75,7 +75,8 @@ pub type GetCrateDataCb = &fn(ast::crate_num) -> cmd; pub fn maybe_find_item(item_id: int, items: ebml::Doc) -> Option { fn eq_item(bytes: &[u8], item_id: int) -> bool { - return io::u64_from_be_bytes(vec::view(bytes, 0u, 4u), 0u, 4u) as int + return io::u64_from_be_bytes( + vec::slice(bytes, 0u, 4u), 0u, 4u) as int == item_id; } lookup_hash(items, @@ -752,10 +753,10 @@ pub fn get_provided_trait_methods(intr: @ident_interner, cdata: cmd, def_id: did }; - vec::push(&mut result, move provided_trait_method_info); + vec::push(&mut result, provided_trait_method_info); } - return move result; + return result; } /// Returns the supertraits of the given trait. @@ -766,7 +767,7 @@ pub fn get_supertraits(cdata: cmd, id: ast::node_id, tcx: ty::ctxt) for reader::tagged_docs(item_doc, tag_impl_trait) |trait_doc| { results.push(doc_type(trait_doc, tcx, cdata)); } - return dvec::unwrap(move results); + return dvec::unwrap(results); } // If the item in question is a trait, returns its set of methods and @@ -847,7 +848,7 @@ pub fn get_static_methods_if_impl(intr: @ident_interner, } } - return Some(dvec::unwrap(move static_impl_methods)); + return Some(dvec::unwrap(static_impl_methods)); } pub fn get_item_attrs(cdata: cmd, diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 12c5e3388dbe7..e2a2573e04165 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -1147,7 +1147,7 @@ fn encode_crate_deps(ecx: @encode_ctxt, } // mut -> immutable hack for vec::map - return vec::slice(deps, 0u, vec::len(deps)); + return vec::slice(deps, 0u, vec::len(deps)).to_vec(); } // We're just going to write a list of crate 'name-hash-version's, with @@ -1229,7 +1229,7 @@ pub fn encode_metadata(parms: encode_parms, crate: &crate) -> ~[u8] { let ecx: @encode_ctxt = @encode_ctxt({ diag: parms.diag, tcx: parms.tcx, - stats: @mut move stats, + stats: @mut stats, reachable: parms.reachable, reexports2: parms.reexports2, item_symbols: parms.item_symbols, @@ -1307,7 +1307,7 @@ pub fn encode_metadata(parms: encode_parms, crate: &crate) -> ~[u8] { // vec::from_slice(metadata_encoding_version) + (do str::as_bytes(&~"rust\x00\x00\x00\x01") |bytes| { - vec::slice(*bytes, 0, 8) + vec::slice(*bytes, 0, 8).to_vec() }) + flate::deflate_bytes(wr.bytes.check_out(|buf| buf)) } diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index ed4ea665aafcd..f5cc44867a5d1 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -49,11 +49,11 @@ pub fn mk_filesearch(maybe_sysroot: Option, paths.push( make_target_lib_path(&self.sysroot, self.target_triple)); - match get_cargo_lib_path_nearest() { + match get_rustpkg_lib_path_nearest() { result::Ok(ref p) => paths.push((/*bad*/copy *p)), result::Err(_) => () } - match get_cargo_lib_path() { + match get_rustpkg_lib_path() { result::Ok(ref p) => paths.push((/*bad*/copy *p)), result::Err(_) => () } @@ -119,54 +119,54 @@ fn get_sysroot(maybe_sysroot: Option) -> Path { } } -pub fn get_cargo_sysroot() -> Result { - result::Ok(get_or_default_sysroot().push_many([libdir(), ~"cargo"])) +pub fn get_rustpkg_sysroot() -> Result { + result::Ok(get_or_default_sysroot().push_many([libdir(), ~"rustpkg"])) } -pub fn get_cargo_root() -> Result { - match os::getenv(~"CARGO_ROOT") { +pub fn get_rustpkg_root() -> Result { + match os::getenv(~"RUSTPKG_ROOT") { Some(ref _p) => result::Ok(Path((*_p))), None => match os::homedir() { - Some(ref _q) => result::Ok((*_q).push(".cargo")), - None => result::Err(~"no CARGO_ROOT or home directory") + Some(ref _q) => result::Ok((*_q).push(".rustpkg")), + None => result::Err(~"no RUSTPKG_ROOT or home directory") } } } -pub fn get_cargo_root_nearest() -> Result { - do result::chain(get_cargo_root()) |p| { +pub fn get_rustpkg_root_nearest() -> Result { + do result::chain(get_rustpkg_root()) |p| { let cwd = os::getcwd(); - let cwd_cargo = cwd.push(".cargo"); - let cargo_is_non_root_file = - !os::path_is_dir(&cwd_cargo) && cwd_cargo != p; - let mut par_cargo = cwd.pop().push(".cargo"); - let mut rslt = result::Ok(cwd_cargo); - - if cargo_is_non_root_file { - while par_cargo != p { - if os::path_is_dir(&par_cargo) { - rslt = result::Ok(par_cargo); + let cwd_rustpkg = cwd.push(".rustpkg"); + let rustpkg_is_non_root_file = + !os::path_is_dir(&cwd_rustpkg) && cwd_rustpkg != p; + let mut par_rustpkg = cwd.pop().push(".rustpkg"); + let mut rslt = result::Ok(cwd_rustpkg); + + if rustpkg_is_non_root_file { + while par_rustpkg != p { + if os::path_is_dir(&par_rustpkg) { + rslt = result::Ok(par_rustpkg); break; } - if par_cargo.components.len() == 1 { - // We just checked /.cargo, stop now. + if par_rustpkg.components.len() == 1 { + // We just checked /.rustpkg, stop now. break; } - par_cargo = par_cargo.pop().pop().push(".cargo"); + par_rustpkg = par_rustpkg.pop().pop().push(".rustpkg"); } } rslt } } -fn get_cargo_lib_path() -> Result { - do result::chain(get_cargo_root()) |p| { +fn get_rustpkg_lib_path() -> Result { + do result::chain(get_rustpkg_root()) |p| { result::Ok(p.push(libdir())) } } -fn get_cargo_lib_path_nearest() -> Result { - do result::chain(get_cargo_root_nearest()) |p| { +fn get_rustpkg_lib_path_nearest() -> Result { + do result::chain(get_rustpkg_root_nearest()) |p| { result::Ok(p.push(libdir())) } } diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 9e5b1db879f0c..ad19eed6992f3 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -228,7 +228,7 @@ fn get_metadata_section(os: os, csz - vlen); do vec::raw::buf_as_slice(cvbuf1, csz-vlen) |bytes| { let inflated = flate::inflate_bytes(bytes); - found = move Some(@(move inflated)); + found = Some(@(inflated)); } if found != None { return found; diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index 2599ceb2ef16e..8da6ddda4b319 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -493,8 +493,8 @@ pub fn parse_def_id(buf: &[u8]) -> ast::def_id { fail!(); } - let crate_part = vec::view(buf, 0u, colon_idx); - let def_part = vec::view(buf, colon_idx + 1u, len); + let crate_part = vec::slice(buf, 0u, colon_idx); + let def_part = vec::slice(buf, colon_idx + 1u, len); let crate_num = match uint::parse_bytes(crate_part, 10u) { Some(cn) => cn as int, diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 3b84216b2e6db..e992c2a3af747 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -821,7 +821,7 @@ fn encode_side_tables_for_ii(ecx: @e::encode_ctxt, let ebml_w = copy ebml_w; ast_util::visit_ids_for_inlined_item( ii, - fn@(id: ast::node_id, copy ebml_w) { + fn@(id: ast::node_id) { // Note: this will cause a copy of ebml_w, which is bad as // it has mut fields. But I believe it's harmless since // we generate balanced EBML. @@ -1140,7 +1140,7 @@ fn decode_side_tables(xcx: extended_decode_ctxt, let ids = val_dsr.read_to_vec(|| { xcx.tr_id(val_dsr.read_int()) }); - let dvec = @dvec::from_vec(move ids); + let dvec = @dvec::from_vec(ids); dcx.maps.last_use_map.insert(id, dvec); } else if tag == (c::tag_table_method_map as uint) { dcx.maps.method_map.insert( diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index b6b94faa3db7e..507f3059f32c8 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -632,7 +632,7 @@ fn check_loans_in_fn(fk: visit::fn_kind, _ => {} // Ignore this argument. } } - *self.fn_args = @move fn_args; + *self.fn_args = @fn_args; } } diff --git a/src/librustc/middle/borrowck/gather_loans.rs b/src/librustc/middle/borrowck/gather_loans.rs index 65518398eb752..126a7f3033308 100644 --- a/src/librustc/middle/borrowck/gather_loans.rs +++ b/src/librustc/middle/borrowck/gather_loans.rs @@ -376,8 +376,8 @@ impl GatherLoanCtxt { Some(_) => { match loan::loan(self.bccx, cmt, scope_r, loan_kind) { Err(ref e) => { self.bccx.report((*e)); } - Ok(move loans) => { - self.add_loans(cmt, loan_kind, scope_r, move loans); + Ok(loans) => { + self.add_loans(cmt, loan_kind, scope_r, loans); } } } @@ -540,7 +540,7 @@ impl GatherLoanCtxt { } }; - self.add_loans_to_scope_id(scope_id, move loans); + self.add_loans_to_scope_id(scope_id, loans); if loan_kind.is_freeze() && !cmt.mutbl.is_immutable() { self.bccx.stats.loaned_paths_imm += 1; @@ -566,7 +566,7 @@ impl GatherLoanCtxt { req_loans.push_all(loans); } None => { - let dvec = @dvec::from_vec(move loans); + let dvec = @dvec::from_vec(loans); let req_loan_map = self.req_maps.req_loan_map; req_loan_map.insert(scope_id, dvec); } diff --git a/src/librustc/middle/borrowck/loan.rs b/src/librustc/middle/borrowck/loan.rs index 3b6d735ae781f..c39f2455c2f8f 100644 --- a/src/librustc/middle/borrowck/loan.rs +++ b/src/librustc/middle/borrowck/loan.rs @@ -73,7 +73,7 @@ pub fn loan(bccx: @BorrowckCtxt, Err(ref e) => return Err((*e)), Ok(()) => {} } - // XXX: Workaround for borrow check bug. + // FIXME #4945: Workaround for borrow check bug. Ok(copy lc.loans) } diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index dd8f889a05732..a420faf1f1d96 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -420,7 +420,7 @@ pub fn save_and_restore(save_and_restore_t: &mut T, let old_save_and_restore_t = *save_and_restore_t; let u = f(); *save_and_restore_t = old_save_and_restore_t; - move u + u } pub fn save_and_restore_managed(save_and_restore_t: @mut T, @@ -428,7 +428,7 @@ pub fn save_and_restore_managed(save_and_restore_t: @mut T, let old_save_and_restore_t = *save_and_restore_t; let u = f(); *save_and_restore_t = old_save_and_restore_t; - move u + u } impl LoanKind { @@ -449,7 +449,7 @@ impl LoanKind { /// Creates and returns a new root_map -pub impl root_map_key : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for root_map_key { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { to_bytes::iter_bytes_2(&self.id, &self.derefs, lsb0, f); } diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index 6d4de6aeb9351..c86f7ea5a922f 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -16,7 +16,6 @@ use middle::ty; use middle::typeck; use util::ppaux; -use core::dvec::DVec; use core::option; use std::oldmap::HashMap; use syntax::ast::*; @@ -212,20 +211,20 @@ pub fn check_item_recursion(sess: Session, ast_map: ast_map::map, def_map: resolve::DefMap, it: @item) { - type env = { + struct env { root_it: @item, sess: Session, ast_map: ast_map::map, def_map: resolve::DefMap, - idstack: @DVec, - }; + idstack: @mut ~[node_id] + } - let env = { + let env = env { root_it: it, sess: sess, ast_map: ast_map, def_map: def_map, - idstack: @DVec() + idstack: @mut ~[] }; let visitor = visit::mk_vt(@visit::Visitor { @@ -236,12 +235,12 @@ pub fn check_item_recursion(sess: Session, (visitor.visit_item)(it, env, visitor); fn visit_item(it: @item, &&env: env, v: visit::vt) { - if (*env.idstack).contains(&(it.id)) { + if env.idstack.contains(&(it.id)) { env.sess.span_fatal(env.root_it.span, ~"recursive constant"); } - (*env.idstack).push(it.id); + env.idstack.push(it.id); visit::visit_item(it, env, v); - (*env.idstack).pop(); + env.idstack.pop(); } fn visit_expr(e: @expr, &&env: env, v: visit::vt) { diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index d65c4e0158055..70464d0084a35 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -1520,7 +1520,7 @@ impl Liveness { self.cont_ln.insert(loop_node_id, cont_ln); let r = f(); self.loop_scope.pop(); - move r + r } } diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index c4612e7602417..da2c8965ba1c8 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -281,12 +281,12 @@ pub trait ast_node { fn span() -> span; } -pub impl @ast::expr: ast_node { +pub impl ast_node for @ast::expr { fn id() -> ast::node_id { self.id } fn span() -> span { self.span } } -pub impl @ast::pat: ast_node { +pub impl ast_node for @ast::pat { fn id() -> ast::node_id { self.id } fn span() -> span { self.span } } @@ -295,7 +295,7 @@ pub trait get_type_for_node { fn ty(node: N) -> ty::t; } -pub impl ty::ctxt: get_type_for_node { +pub impl get_type_for_node for ty::ctxt { fn ty(node: N) -> ty::t { ty::node_id_to_type(self, node.id()) } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index acb73e90c5d58..44b0da626b68d 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -96,8 +96,8 @@ pub type BindingMap = HashMap; // Implementation resolution // -// XXX: This kind of duplicates information kept in ty::method. Maybe it -// should go away. +// FIXME #4946: This kind of duplicates information kept in +// ty::method. Maybe it should go away. pub type MethodInfo = { did: def_id, @@ -268,8 +268,8 @@ pub enum MethodSort { // allows it to reference private names. Currently, this is used for the test // runner. // -// XXX: The X-ray flag is kind of questionable in the first place. It might -// be better to introduce an expr_xray_path instead. +// FIXME #4947: The X-ray flag is kind of questionable in the first +// place. It might be better to introduce an expr_xray_path instead. #[deriving_eq] pub enum XrayFlag { @@ -469,14 +469,6 @@ pub struct Module { anonymous_children: HashMap, - // XXX: This is about to be reworked so that exports are on individual - // items, not names. - // - // The ident is the name of the exported item, while the node ID is the - // ID of the export path. - - exported_names: HashMap, - // The status of resolving each import in this module. import_resolutions: HashMap, @@ -498,7 +490,6 @@ pub fn Module(parent_link: ParentLink, children: HashMap(), imports: DVec(), anonymous_children: HashMap(), - exported_names: HashMap(), import_resolutions: HashMap(), glob_count: 0, resolved_import_count: 0 @@ -806,7 +797,7 @@ pub fn Resolver(session: Session, intr: session.intr() }; - move self + self } /// The main resolver class. @@ -831,7 +822,7 @@ pub struct Resolver { mut current_module: @Module, // The current set of local scopes, for values. - // XXX: Reuse ribs to avoid allocation. + // FIXME #4948: Reuse ribs to avoid allocation. value_ribs: @DVec<@Rib>, // The current set of local scopes, for types. @@ -2137,8 +2128,9 @@ pub impl Resolver { // We need to resolve both namespaces for this to succeed. // - // XXX: See if there's some way of handling namespaces in a more - // generic way. We have two of them; it seems worth doing... + // FIXME #4949: See if there's some way of handling namespaces in + // a more generic way. We have two of them; it seems worth + // doing... let mut value_result = UnknownResult; let mut type_result = UnknownResult; @@ -3206,8 +3198,8 @@ pub impl Resolver { // This pass simply determines what all "export" keywords refer to and // writes the results into the export map. // - // XXX: This pass will be removed once exports change to per-item. Then - // this operation can simply be performed as part of item (or import) + // FIXME #4953 This pass will be removed once exports change to per-item. + // Then this operation can simply be performed as part of item (or import) // processing. fn record_exports() { @@ -3263,7 +3255,7 @@ pub impl Resolver { self.add_exports_for_module(&mut exports2, module_); match copy module_.def_id { Some(def_id) => { - self.export_map2.insert(def_id.node, move exports2); + self.export_map2.insert(def_id.node, exports2); debug!("(computing exports) writing exports for %d (some)", def_id.node); } @@ -3507,8 +3499,8 @@ pub impl Resolver { allow_capturing_self: AllowCapturingSelfFlag) -> Option { - // XXX: This should not use a while loop. - // XXX: Try caching? + // FIXME #4950: This should not use a while loop. + // FIXME #4950: Try caching? let mut i = (*ribs).len(); while i != 0 { @@ -3649,7 +3641,7 @@ pub impl Resolver { // Create a new rib for the method-specific type // parameters. // - // XXX: Do we need a node ID here? + // FIXME #4951: Do we need a node ID here? match *method { required(ref ty_m) => { @@ -4555,7 +4547,7 @@ pub impl Resolver { namespace); } - // XXX: Merge me with resolve_name_in_module? + // FIXME #4952: Merge me with resolve_name_in_module? fn resolve_definition_of_name_in_module(containing_module: @Module, name: ident, namespace: Namespace, @@ -4873,20 +4865,6 @@ pub impl Resolver { expr_struct(path, _, _) => { // Resolve the path to the structure it goes to. - // - // XXX: We might want to support explicit type parameters in - // the path, in which case this gets a little more - // complicated: - // - // 1. Should we go through the ast_path_to_ty() path, which - // handles typedefs and the like? - // - // 2. If so, should programmers be able to write this? - // - // class Foo { ... } - // type Bar = Foo; - // let bar = Bar { ... } // no type parameters - match self.resolve_path(path, TypeNS, false, visitor) { Some(def_ty(class_id)) | Some(def_struct(class_id)) if self.structs.contains_key(&class_id) => { @@ -5320,7 +5298,7 @@ pub impl Resolver { None => { value_repr = ~""; } Some(_) => { value_repr = ~" value:?"; - // XXX + // FIXME #4954 } } @@ -5329,7 +5307,7 @@ pub impl Resolver { None => { type_repr = ~""; } Some(_) => { type_repr = ~" type:?"; - // XXX + // FIXME #4954 } } diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index 492adc8631dc9..8864e2e0a0828 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -372,9 +372,10 @@ pub fn expand_nested_bindings(bcx: block, m: &[@Match/&r], match br.pats[col].node { ast::pat_ident(_, path, Some(inner)) => { let pats = vec::append( - vec::slice(br.pats, 0u, col), + vec::slice(br.pats, 0u, col).to_vec(), vec::append(~[inner], - vec::view(br.pats, col + 1u, br.pats.len()))); + vec::slice(br.pats, col + 1u, + br.pats.len()))); let binding_info = br.data.bindings_map.get(&path_to_ident(path)); @@ -416,8 +417,8 @@ pub fn enter_match(bcx: block, dm: DefMap, m: &[@Match/&r], Some(sub) => { let pats = vec::append( - vec::append(sub, vec::view(br.pats, 0u, col)), - vec::view(br.pats, col + 1u, br.pats.len())); + vec::append(sub, vec::slice(br.pats, 0u, col)), + vec::slice(br.pats, col + 1u, br.pats.len())); let self = br.pats[col]; match self.node { @@ -559,7 +560,7 @@ pub fn enter_opt(bcx: block, m: &[@Match/&r], opt: &Opt, col: uint, Some(fp) => reordered_patterns.push(fp.pat) } } - Some(dvec::unwrap(move reordered_patterns)) + Some(dvec::unwrap(reordered_patterns)) } else { None } @@ -815,7 +816,7 @@ pub fn get_options(ccx: @crate_ctxt, m: &[@Match], col: uint) -> ~[Opt] { _ => {} } } - return dvec::unwrap(move found); + return dvec::unwrap(found); } pub fn extract_variant_args(bcx: block, @@ -1242,7 +1243,7 @@ pub fn compile_submatch(bcx: block, match data.arm.guard { Some(guard_expr) => { bcx = compile_guard(bcx, guard_expr, m[0].data, - vec::view(m, 1, m.len()), + vec::slice(m, 1, m.len()), vals, chk); } _ => () @@ -1261,8 +1262,8 @@ pub fn compile_submatch(bcx: block, } }; - let vals_left = vec::append(vec::slice(vals, 0u, col), - vec::view(vals, col + 1u, vals.len())); + let vals_left = vec::append(vec::slice(vals, 0u, col).to_vec(), + vec::slice(vals, col + 1u, vals.len())); let ccx = bcx.fcx.ccx; let mut pat_id = 0; for vec::each(m) |br| { @@ -1657,7 +1658,7 @@ pub fn trans_match_inner(scope_cx: block, arm_cxs.push(bcx); } - bcx = controlflow::join_blocks(scope_cx, dvec::unwrap(move arm_cxs)); + bcx = controlflow::join_blocks(scope_cx, dvec::unwrap(arm_cxs)); return bcx; fn mk_fail(bcx: block, sp: span, +msg: ~str, diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 8d6d299c92f89..13f29724ba80e 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -108,7 +108,7 @@ pub trait get_insn_ctxt { fn insn_ctxt(s: &str) -> icx_popper; } -pub impl @crate_ctxt: get_insn_ctxt { +pub impl get_insn_ctxt for @crate_ctxt { fn insn_ctxt(s: &str) -> icx_popper { debug!("new insn_ctxt: %s", s); if self.sess.count_llvm_insns() { @@ -118,13 +118,13 @@ pub impl @crate_ctxt: get_insn_ctxt { } } -pub impl block: get_insn_ctxt { +pub impl get_insn_ctxt for block { fn insn_ctxt(s: &str) -> icx_popper { self.ccx().insn_ctxt(s) } } -pub impl fn_ctxt: get_insn_ctxt { +pub impl get_insn_ctxt for fn_ctxt { fn insn_ctxt(s: &str) -> icx_popper { self.ccx.insn_ctxt(s) } @@ -1174,7 +1174,7 @@ pub fn new_block(cx: fn_ctxt, parent: Option, +kind: block_kind, }); let bcx = mk_block(llbb, parent, - move kind, + kind, is_lpad, opt_node_info, cx); @@ -3030,6 +3030,7 @@ pub fn trans_crate(sess: session::Session, const_values: HashMap(), module_data: HashMap(), lltypes: ty::new_ty_hash(), + llsizingtypes: ty::new_ty_hash(), names: new_namegen(sess.parse_sess.interner), next_addrspace: new_addrspace_gen(), symbol_hasher: symbol_hasher, diff --git a/src/librustc/middle/trans/cabi_x86_64.rs b/src/librustc/middle/trans/cabi_x86_64.rs index a3c5e094ea819..9f717682dae09 100644 --- a/src/librustc/middle/trans/cabi_x86_64.rs +++ b/src/librustc/middle/trans/cabi_x86_64.rs @@ -274,11 +274,11 @@ fn classify_ty(ty: TypeRef) -> ~[x86_64_reg_class] { if words > 4 { all_mem(cls); let cls = cls; - return move cls; + return cls; } classify(ty, cls, 0, 0); fixup(ty, cls); - return move cls; + return cls; } fn llreg_ty(cls: &[x86_64_reg_class]) -> TypeRef { diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 03a91fa15fa08..b0ec0e1b90738 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -202,6 +202,7 @@ pub struct crate_ctxt { const_values: HashMap, module_data: HashMap<~str, ValueRef>, lltypes: HashMap, + llsizingtypes: HashMap, names: namegen, next_addrspace: addrspace_gen, symbol_hasher: @hash::State, @@ -484,8 +485,8 @@ pub fn revoke_clean(cx: block, val: ValueRef) { }); for cleanup_pos.each |i| { scope_info.cleanups = - vec::append(vec::slice(scope_info.cleanups, 0u, *i), - vec::view(scope_info.cleanups, + vec::append(vec::slice(scope_info.cleanups, 0u, *i).to_vec(), + vec::slice(scope_info.cleanups, *i + 1u, scope_info.cleanups.len())); scope_clean_changed(scope_info); @@ -532,13 +533,13 @@ pub trait get_node_info { fn info() -> Option; } -pub impl @ast::expr: get_node_info { +pub impl get_node_info for @ast::expr { fn info() -> Option { Some({id: self.id, span: self.span}) } } -pub impl ast::blk: get_node_info { +pub impl get_node_info for ast::blk { fn info() -> Option { Some({id: self.node.id, span: self.span}) } @@ -547,7 +548,7 @@ pub impl ast::blk: get_node_info { // XXX: Work around a trait parsing bug. remove after snapshot pub type optional_boxed_ast_expr = Option<@ast::expr>; -pub impl optional_boxed_ast_expr: get_node_info { +pub impl get_node_info for optional_boxed_ast_expr { fn info() -> Option { self.chain_ref(|s| s.info()) } @@ -593,7 +594,7 @@ pub fn block_(llbb: BasicBlockRef, parent: Option, -kind: block_kind, terminated: false, unreachable: false, parent: parent, - kind: move kind, + kind: kind, is_lpad: is_lpad, node_info: node_info, fcx: fcx @@ -607,7 +608,7 @@ pub enum block = @block_; pub fn mk_block(llbb: BasicBlockRef, parent: Option, -kind: block_kind, is_lpad: bool, node_info: Option, fcx: fn_ctxt) -> block { - block(@block_(llbb, parent, move kind, is_lpad, node_info, fcx)) + block(@block_(llbb, parent, kind, is_lpad, node_info, fcx)) } // First two args are retptr, env @@ -1280,7 +1281,7 @@ pub struct mono_id_ { pub type mono_id = @mono_id_; -pub impl mono_param_id : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for mono_param_id { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { match /*bad*/copy *self { mono_precise(t, mids) => @@ -1294,7 +1295,7 @@ pub impl mono_param_id : to_bytes::IterBytes { } } -pub impl mono_id_ : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for mono_id_ { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { to_bytes::iter_bytes_2(&self.def, &self.params, lsb0, f); } diff --git a/src/librustc/middle/trans/datum.rs b/src/librustc/middle/trans/datum.rs index d301a31357be3..49779b9bbcc8b 100644 --- a/src/librustc/middle/trans/datum.rs +++ b/src/librustc/middle/trans/datum.rs @@ -104,6 +104,7 @@ use core::uint; use core::vec; use syntax::parse::token::special_idents; +#[deriving_eq] pub enum CopyAction { INIT, DROP_EXISTING @@ -150,14 +151,14 @@ pub impl DatumMode { } } -pub impl DatumMode: cmp::Eq { +pub impl cmp::Eq for DatumMode { pure fn eq(&self, other: &DatumMode) -> bool { (*self) as uint == (*other as uint) } pure fn ne(&self, other: &DatumMode) -> bool { !(*self).eq(other) } } -pub impl DatumMode: to_bytes::IterBytes { +pub impl to_bytes::IterBytes for DatumMode { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as uint).iter_bytes(lsb0, f) } @@ -846,14 +847,3 @@ pub impl DatumBlock { } } -pub impl CopyAction : cmp::Eq { - pure fn eq(&self, other: &CopyAction) -> bool { - match ((*self), (*other)) { - (INIT, INIT) => true, - (DROP_EXISTING, DROP_EXISTING) => true, - (INIT, _) => false, - (DROP_EXISTING, _) => false, - } - } - pure fn ne(&self, other: &CopyAction) -> bool { !(*self).eq(other) } -} diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 7c6f03cb364bc..e2e5526eac08b 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -152,7 +152,7 @@ enum debug_metadata { fn cast_safely(val: T) -> U { unsafe { let val2 = val; - return cast::transmute(move val2); + return cast::transmute(val2); } } diff --git a/src/librustc/middle/trans/machine.rs b/src/librustc/middle/trans/machine.rs index 75e494f7bfcd9..58a53cd878a70 100644 --- a/src/librustc/middle/trans/machine.rs +++ b/src/librustc/middle/trans/machine.rs @@ -13,60 +13,8 @@ use middle::trans::common::*; use middle::trans::type_of; -use middle::ty::field; use middle::ty; - -use syntax::parse::token::special_idents; - -// Creates a simpler, size-equivalent type. The resulting type is guaranteed -// to have (a) the same size as the type that was passed in; (b) to be non- -// recursive. This is done by replacing all boxes in a type with boxed unit -// types. -// This should reduce all pointers to some simple pointer type, to -// ensure that we don't recurse endlessly when computing the size of a -// nominal type that has pointers to itself in it. -pub fn simplify_type(tcx: ty::ctxt, typ: ty::t) -> ty::t { - fn nilptr(tcx: ty::ctxt) -> ty::t { - ty::mk_ptr(tcx, ty::mt {ty: ty::mk_nil(tcx), mutbl: ast::m_imm}) - } - fn simplifier(tcx: ty::ctxt, typ: ty::t) -> ty::t { - match ty::get(typ).sty { - ty::ty_box(_) | ty::ty_opaque_box | ty::ty_uniq(_) | - ty::ty_evec(_, ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_box) | - ty::ty_estr(ty::vstore_uniq) | ty::ty_estr(ty::vstore_box) | - ty::ty_ptr(_) | ty::ty_rptr(*) => nilptr(tcx), - - ty::ty_bare_fn(*) | // FIXME(#4804) Bare fn repr - ty::ty_closure(*) => ty::mk_tup(tcx, ~[nilptr(tcx), nilptr(tcx)]), - - ty::ty_evec(_, ty::vstore_slice(_)) | - ty::ty_estr(ty::vstore_slice(_)) => { - ty::mk_tup(tcx, ~[nilptr(tcx), ty::mk_int(tcx)]) - } - // Reduce a class type to a record type in which all the fields are - // simplified - ty::ty_struct(did, ref substs) => { - let simpl_fields = (if ty::ty_dtor(tcx, did).is_present() { - // remember the drop flag - ~[field { - ident: special_idents::dtor, - mt: ty::mt {ty: ty::mk_u8(tcx), mutbl: ast::m_mutbl} - }] } - else { ~[] }) + - do ty::lookup_struct_fields(tcx, did).map |f| { - let t = ty::lookup_field_type(tcx, did, f.id, substs); - field { - ident: f.ident, - mt: ty::mt {ty: simplify_type(tcx, t), mutbl: ast::m_const - }} - }; - ty::mk_rec(tcx, simpl_fields) - } - _ => typ - } - } - ty::fold_ty(tcx, typ, |t| simplifier(tcx, t)) -} +use util::ppaux::ty_to_str; // ______________________________________________________________________ // compute sizeof / alignof @@ -180,27 +128,40 @@ pub fn llalign_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef { // Computes the size of the data part of an enum. pub fn static_size_of_enum(cx: @crate_ctxt, t: ty::t) -> uint { - if cx.enum_sizes.contains_key(&t) { return cx.enum_sizes.get(&t); } + if cx.enum_sizes.contains_key(&t) { + return cx.enum_sizes.get(&t); + } + + debug!("static_size_of_enum %s", ty_to_str(cx.tcx, t)); + match ty::get(t).sty { - ty::ty_enum(tid, ref substs) => { - // Compute max(variant sizes). - let mut max_size = 0u; - let variants = ty::enum_variants(cx.tcx, tid); - for vec::each(*variants) |variant| { - let tup_ty = simplify_type( - cx.tcx, - ty::mk_tup(cx.tcx, /*bad*/copy variant.args)); - // Perform any type parameter substitutions. - let tup_ty = ty::subst(cx.tcx, substs, tup_ty); - // Here we possibly do a recursive call. - let this_size = - llsize_of_real(cx, type_of::type_of(cx, tup_ty)); - if max_size < this_size { max_size = this_size; } + ty::ty_enum(tid, ref substs) => { + // Compute max(variant sizes). + let mut max_size = 0; + let variants = ty::enum_variants(cx.tcx, tid); + for variants.each |variant| { + if variant.args.len() == 0 { + loop; + } + + let lltypes = variant.args.map(|&variant_arg| { + let substituted = ty::subst(cx.tcx, substs, variant_arg); + type_of::sizing_type_of(cx, substituted) + }); + + debug!("static_size_of_enum: variant %s type %s", + cx.tcx.sess.str_of(variant.name), + ty_str(cx.tn, T_struct(lltypes))); + + let this_size = llsize_of_real(cx, T_struct(lltypes)); + if max_size < this_size { + max_size = this_size; + } + } + cx.enum_sizes.insert(t, max_size); + return max_size; } - cx.enum_sizes.insert(t, max_size); - return max_size; - } - _ => cx.sess.bug(~"static_size_of_enum called on non-enum") + _ => cx.sess.bug(~"static_size_of_enum called on non-enum") } } diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index a79a24ba4606f..bc4ec8c07c291 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -561,7 +561,7 @@ pub fn combine_impl_and_methods_origins(bcx: block, let n_m_tps = method_ty_param_count(ccx, mth_did, impl_did); let {bounds: r_m_bounds, _} = ty::lookup_item_type(tcx, mth_did); let n_r_m_tps = r_m_bounds.len(); // rcvr + method tps - let m_boundss = vec::view(*r_m_bounds, n_r_m_tps - n_m_tps, n_r_m_tps); + let m_boundss = vec::slice(*r_m_bounds, n_r_m_tps - n_m_tps, n_r_m_tps); // Flatten out to find the number of vtables the method expects. let m_vtables = ty::count_traits_and_supertraits(tcx, m_boundss); diff --git a/src/librustc/middle/trans/type_of.rs b/src/librustc/middle/trans/type_of.rs index 972f702c18a81..6be82f833a6ae 100644 --- a/src/librustc/middle/trans/type_of.rs +++ b/src/librustc/middle/trans/type_of.rs @@ -89,6 +89,95 @@ pub fn type_of_non_gc_box(cx: @crate_ctxt, t: ty::t) -> TypeRef { } } +// A "sizing type" is an LLVM type, the size and alignment of which are +// guaranteed to be equivalent to what you would get out of `type_of()`. It's +// useful because: +// +// (1) It may be cheaper to compute the sizing type than the full type if all +// you're interested in is the size and/or alignment; +// +// (2) It won't make any recursive calls to determine the structure of the +// type behind pointers. This can help prevent infinite loops for +// recursive types. For example, `static_size_of_enum()` relies on this +// behavior. + +pub fn sizing_type_of(cx: @crate_ctxt, t: ty::t) -> TypeRef { + if cx.llsizingtypes.contains_key(&t) { + return cx.llsizingtypes.get(&t); + } + + let llsizingty = match ty::get(t).sty { + ty::ty_nil | ty::ty_bot => T_nil(), + ty::ty_bool => T_bool(), + ty::ty_int(t) => T_int_ty(cx, t), + ty::ty_uint(t) => T_uint_ty(cx, t), + ty::ty_float(t) => T_float_ty(cx, t), + + ty::ty_estr(ty::vstore_uniq) | + ty::ty_estr(ty::vstore_box) | + ty::ty_evec(_, ty::vstore_uniq) | + ty::ty_evec(_, ty::vstore_box) | + ty::ty_box(*) | + ty::ty_opaque_box | + ty::ty_uniq(*) | + ty::ty_ptr(*) | + ty::ty_rptr(*) | + ty::ty_type | + ty::ty_opaque_closure_ptr(*) => T_ptr(T_i8()), + + ty::ty_estr(ty::vstore_slice(*)) | + ty::ty_evec(_, ty::vstore_slice(*)) => { + T_struct(~[T_ptr(T_i8()), T_ptr(T_i8())]) + } + + // FIXME(#4804) Bare fn repr + ty::ty_bare_fn(*) => T_struct(~[T_ptr(T_i8()), T_ptr(T_i8())]), + ty::ty_closure(*) => T_struct(~[T_ptr(T_i8()), T_ptr(T_i8())]), + ty::ty_trait(_, _, vstore) => T_opaque_trait(cx, vstore), + + ty::ty_estr(ty::vstore_fixed(size)) => T_array(T_i8(), size), + ty::ty_evec(mt, ty::vstore_fixed(size)) => { + T_array(sizing_type_of(cx, mt.ty), size) + } + + ty::ty_unboxed_vec(mt) => T_vec(cx, sizing_type_of(cx, mt.ty)), + + ty::ty_tup(ref elems) => { + T_struct(elems.map(|&t| sizing_type_of(cx, t))) + } + + ty::ty_rec(ref fields) => { + T_struct(fields.map(|f| sizing_type_of(cx, f.mt.ty))) + } + + ty::ty_struct(def_id, ref substs) => { + let fields = ty::lookup_struct_fields(cx.tcx, def_id); + let lltype = T_struct(fields.map(|field| { + let field_type = ty::lookup_field_type(cx.tcx, + def_id, + field.id, + substs); + sizing_type_of(cx, field_type) + })); + if ty::ty_dtor(cx.tcx, def_id).is_present() { + T_struct(~[lltype, T_i8()]) + } else { + lltype + } + } + + ty::ty_enum(def_id, _) => T_struct(enum_body_types(cx, def_id, t)), + + ty::ty_self | ty::ty_infer(*) | ty::ty_param(*) | ty::ty_err(*) => { + cx.tcx.sess.bug(~"fictitious type in sizing_type_of()") + } + }; + + cx.llsizingtypes.insert(t, llsizingty); + llsizingty +} + +// NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of(cx: @crate_ctxt, t: ty::t) -> TypeRef { debug!("type_of %?: %?", t, ty::get(t)); @@ -236,23 +325,32 @@ pub fn type_of(cx: @crate_ctxt, t: ty::t) -> TypeRef { return llty; } -pub fn fill_type_of_enum(cx: @crate_ctxt, did: ast::def_id, t: ty::t, - llty: TypeRef) { - - debug!("type_of_enum %?: %?", t, ty::get(t)); - - let lltys = { - let univar = ty::enum_is_univariant(cx.tcx, did); +pub fn enum_body_types(cx: @crate_ctxt, did: ast::def_id, t: ty::t) + -> ~[TypeRef] { + let univar = ty::enum_is_univariant(cx.tcx, did); + if !univar { let size = machine::static_size_of_enum(cx, t); - if !univar { - ~[T_enum_discrim(cx), T_array(T_i8(), size)] - } - else { - ~[T_array(T_i8(), size)] + ~[T_enum_discrim(cx), T_array(T_i8(), size)] + } + else { + // Use the actual fields, so we get the alignment right. + match ty::get(t).sty { + ty::ty_enum(_, ref substs) => { + do ty::enum_variants(cx.tcx, did)[0].args.map |&field_ty| { + sizing_type_of(cx, ty::subst(cx.tcx, substs, field_ty)) + } + } + _ => cx.sess.bug(~"enum is not an enum") } - }; + } +} - common::set_struct_body(llty, lltys); +pub fn fill_type_of_enum(cx: @crate_ctxt, + did: ast::def_id, + t: ty::t, + llty: TypeRef) { + debug!("type_of_enum %?: %?", t, ty::get(t)); + common::set_struct_body(llty, enum_body_types(cx, did, t)); } // Want refinements! (Or case classes, I guess diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index f7fb5b771aa74..c15010d7b7b24 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -320,7 +320,7 @@ pub pure fn get(t: t) -> t_box { unsafe { let t2 = cast::reinterpret_cast::(&t); let t3 = t2; - cast::forget(move t2); + cast::forget(t2); t3 } } @@ -657,46 +657,46 @@ pub trait Vid { pure fn to_uint() -> uint; } -pub impl TyVid: Vid { +pub impl Vid for TyVid { pure fn to_uint() -> uint { *self } } -pub impl TyVid: ToStr { +pub impl ToStr for TyVid { pure fn to_str(&self) -> ~str { fmt!("", self.to_uint()) } } -pub impl IntVid: Vid { +pub impl Vid for IntVid { pure fn to_uint() -> uint { *self } } -pub impl IntVid: ToStr { +pub impl ToStr for IntVid { pure fn to_str(&self) -> ~str { fmt!("", self.to_uint()) } } -pub impl FloatVid: Vid { +pub impl Vid for FloatVid { pure fn to_uint() -> uint { *self } } -pub impl FloatVid: ToStr { +pub impl ToStr for FloatVid { pure fn to_str(&self) -> ~str { fmt!("", self.to_uint()) } } -pub impl RegionVid: Vid { +pub impl Vid for RegionVid { pure fn to_uint() -> uint { *self } } -pub impl RegionVid: ToStr { +pub impl ToStr for RegionVid { pure fn to_str(&self) -> ~str { fmt!("%?", self) } } -pub impl FnSig : ToStr { +pub impl ToStr for FnSig { pure fn to_str(&self) -> ~str { // grr, without tcx not much we can do. return ~"(...)"; } } -pub impl InferTy: ToStr { +pub impl ToStr for InferTy { pure fn to_str(&self) -> ~str { match *self { TyVar(ref v) => v.to_str(), @@ -706,7 +706,7 @@ pub impl InferTy: ToStr { } } -pub impl IntVarValue : ToStr { +pub impl ToStr for IntVarValue { pure fn to_str(&self) -> ~str { match *self { IntType(ref v) => v.to_str(), @@ -715,25 +715,25 @@ pub impl IntVarValue : ToStr { } } -pub impl TyVid : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for TyVid { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { self.to_uint().iter_bytes(lsb0, f) } } -pub impl IntVid : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for IntVid { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { self.to_uint().iter_bytes(lsb0, f) } } -pub impl FloatVid : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for FloatVid { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { self.to_uint().iter_bytes(lsb0, f) } } -pub impl RegionVid : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for RegionVid { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { self.to_uint().iter_bytes(lsb0, f) } @@ -830,7 +830,7 @@ pub fn mk_ctxt(s: session::Session, inferred_modes: HashMap(), adjustments: HashMap(), normalized_cache: new_ty_hash(), - lang_items: move lang_items, + lang_items: lang_items, legacy_boxed_traits: HashMap(), provided_methods: HashMap(), provided_method_sources: HashMap(), @@ -909,10 +909,10 @@ fn mk_t_with_id(cx: ctxt, +st: sty, o_def_id: Option) -> t { } } - let t = @{sty: move st, id: cx.next_id, flags: flags, o_def_id: o_def_id}; + let t = @{sty: st, id: cx.next_id, flags: flags, o_def_id: o_def_id}; let key = intern_key {sty: to_unsafe_ptr(&t.sty), o_def_id: o_def_id}; - cx.interner.insert(move key, t); + cx.interner.insert(key, t); cx.next_id += 1u; unsafe { cast::reinterpret_cast(&t) } @@ -1178,7 +1178,7 @@ pub fn fold_sig(sig: &FnSig, fldop: fn(t) -> t) -> FnSig { }; FnSig { - inputs: move args, + inputs: args, output: fldop(sig.output) } } @@ -3110,7 +3110,7 @@ pub fn expr_kind(tcx: ctxt, ast::def_local(*) | ast::def_self(*) => LvalueExpr, - move def => { + def => { tcx.sess.span_bug(expr.span, fmt!( "Uncategorized def for expr %?: %?", expr.id, def)); @@ -3617,7 +3617,7 @@ pub fn trait_supertraits(cx: ctxt, } // Unwrap and return the result. - return @dvec::unwrap(move result); + return @dvec::unwrap(result); } pub fn trait_methods(cx: ctxt, id: ast::def_id) -> @~[method] { diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index eca368e5d7673..3524636fe2b77 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -139,7 +139,7 @@ pub fn lookup( let mme = lcx.do_lookup(self_ty); debug!("method lookup for %s yielded %?", expr_repr(fcx.tcx(), expr), mme); - return move mme; + return mme; } pub struct LookupContext { @@ -204,26 +204,26 @@ pub impl LookupContext { check::DontDerefArgs => { match self.search_for_autoderefd_method(self_ty, autoderefs) { - Some(move mme) => { return Some(mme); } + Some(mme) => { return Some(mme); } None => {} } match self.search_for_autoptrd_method(self_ty, autoderefs) { - Some(move mme) => { return Some(move mme); } + Some(mme) => { return Some(mme); } None => {} } } check::DoDerefArgs => { match self.search_for_autoptrd_method(self_ty, autoderefs) { - Some(move mme) => { return Some(move mme); } + Some(mme) => { return Some(mme); } None => {} } match self.search_for_autoderefd_method(self_ty, autoderefs) { - Some(move mme) => { return Some(mme); } + Some(mme) => { return Some(mme); } None => {} } } @@ -457,7 +457,7 @@ pub impl LookupContext { self.create_rcvr_ty_and_substs_for_method( method.self_ty, rcvr_ty, - move init_substs, + init_substs, TransformTypeNormally); let cand = Candidate { @@ -525,12 +525,12 @@ pub impl LookupContext { let (rcvr_ty, rcvr_substs) = self.create_rcvr_ty_and_substs_for_method(method.self_ty, self_ty, - move rcvr_substs, + rcvr_substs, TransformTypeForObject); self.inherent_candidates.push(Candidate { rcvr_ty: rcvr_ty, - rcvr_substs: move rcvr_substs, + rcvr_substs: rcvr_substs, explicit_self: method.self_ty, num_method_tps: method.tps.len(), self_mode: get_mode_from_self_type(method.self_ty), @@ -585,7 +585,7 @@ pub impl LookupContext { self.create_rcvr_ty_and_substs_for_method( method_self_ty, self_ty, - move rcvr_substs, + rcvr_substs, TransformTypeNormally); let origin = if trait_did == did { method_self(trait_did, index) @@ -595,7 +595,7 @@ pub impl LookupContext { }; self.inherent_candidates.push(Candidate { rcvr_ty: rcvr_ty, - rcvr_substs: move rcvr_substs, + rcvr_substs: rcvr_substs, explicit_self: method_self_ty, num_method_tps: method_num_tps, self_mode: get_mode_from_self_type(method_self_ty), @@ -648,12 +648,12 @@ pub impl LookupContext { self.create_rcvr_ty_and_substs_for_method( method.self_type, impl_ty, - move impl_substs, + impl_substs, TransformTypeNormally); candidates.push(Candidate { rcvr_ty: impl_ty, - rcvr_substs: move impl_substs, + rcvr_substs: impl_substs, explicit_self: method.self_type, num_method_tps: method.n_tps, self_mode: get_mode_from_self_type(method.self_type), @@ -693,7 +693,7 @@ pub impl LookupContext { candidates.push(Candidate { rcvr_ty: impl_ty, - rcvr_substs: move impl_substs, + rcvr_substs: impl_substs, explicit_self: provided_method_info.method_info.self_type, num_method_tps: provided_method_info.method_info.n_tps, self_mode: get_mode_from_self_type( @@ -722,10 +722,10 @@ pub impl LookupContext { match self_decl { sty_static | sty_value | sty_by_ref | sty_box(_) | sty_uniq(_) => { - move self_substs + self_substs } sty_region(_) if self_substs.self_r.is_some() => { - move self_substs + self_substs } sty_region(_) => { substs { @@ -761,7 +761,7 @@ pub impl LookupContext { self.consider_reborrow(self_ty, autoderefs); match self.search_for_method(self_ty) { None => None, - Some(move mme) => { + Some(mme) => { debug!("(searching for autoderef'd method) writing \ adjustment (%u) to %d", autoderefs, @@ -945,7 +945,7 @@ pub impl LookupContext { let autoref_ty = mk_autoref_ty(*mutbl, region); match self.search_for_method(autoref_ty) { None => {} - Some(move mme) => { + Some(mme) => { self.fcx.write_adjustment( self.self_expr.id, @ty::AutoAdjustment { @@ -977,8 +977,8 @@ pub impl LookupContext { debug!("searching inherent candidates"); match self.consider_candidates(self_ty, &self.inherent_candidates) { None => {} - Some(move mme) => { - return Some(move mme); + Some(mme) => { + return Some(mme); } } @@ -987,8 +987,8 @@ pub impl LookupContext { None => { return None; } - Some(move mme) => { - return Some(move mme); + Some(mme) => { + return Some(mme); } } } diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index a8439c3c45964..1ad3bd9cae6e1 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -620,7 +620,7 @@ pub fn check_item(ccx: @mut CrateCtxt, it: @ast::item) { } } -pub impl FnCtxt: AstConv { +pub impl AstConv for FnCtxt { fn tcx(@mut self) -> ty::ctxt { self.ccx.tcx } fn ccx(@mut self) -> @mut CrateCtxt { self.ccx } @@ -654,7 +654,7 @@ pub impl FnCtxt { } } -pub impl @mut FnCtxt: region_scope { +pub impl region_scope for @mut FnCtxt { pure fn anon_region(span: span) -> Result { // XXX: Unsafe to work around purity unsafe { @@ -870,7 +870,7 @@ pub impl FnCtxt { self.region_lb = lb; let v = f(); self.region_lb = old_region_lb; - move v + v } fn region_var_if_parameterized(@mut self, diff --git a/src/librustc/middle/typeck/coherence.rs b/src/librustc/middle/typeck/coherence.rs index 64ac5a9ae820e..7594b2690a4a3 100644 --- a/src/librustc/middle/typeck/coherence.rs +++ b/src/librustc/middle/typeck/coherence.rs @@ -553,7 +553,7 @@ pub impl CoherenceChecker { UniversalQuantificationResult { monotype: monotype, - type_variables: move type_parameters, + type_variables: type_parameters, bounds: polytype.bounds } } diff --git a/src/librustc/middle/typeck/collect.rs b/src/librustc/middle/typeck/collect.rs index 2a42e75f53d47..972d1b609454b 100644 --- a/src/librustc/middle/typeck/collect.rs +++ b/src/librustc/middle/typeck/collect.rs @@ -121,7 +121,7 @@ pub impl @mut CrateCtxt { } } -pub impl CrateCtxt: AstConv { +pub impl AstConv for CrateCtxt { fn tcx(@mut self) -> ty::ctxt { self.tcx } fn ccx(@mut self) -> @mut CrateCtxt { self } @@ -320,7 +320,7 @@ pub fn ensure_supertraits(ccx: @mut CrateCtxt, instantiated.push(InstantiatedTraitRef { def_id: did, tpt: tpt }); } tcx.supertraits.insert(local_def(id), - @dvec::unwrap(move instantiated)); + @dvec::unwrap(instantiated)); } /** diff --git a/src/librustc/middle/typeck/infer/combine.rs b/src/librustc/middle/typeck/infer/combine.rs index 54b5867bfa239..89719564adaa6 100644 --- a/src/librustc/middle/typeck/infer/combine.rs +++ b/src/librustc/middle/typeck/infer/combine.rs @@ -121,9 +121,9 @@ pub struct CombineFields { pub fn expected_found( self: &C, +a: T, +b: T) -> ty::expected_found { if self.a_is_expected() { - ty::expected_found {expected: move a, found: move b} + ty::expected_found {expected: a, found: b} } else { - ty::expected_found {expected: move b, found: move a} + ty::expected_found {expected: b, found: a} } } diff --git a/src/librustc/middle/typeck/infer/glb.rs b/src/librustc/middle/typeck/infer/glb.rs index 9778ac670c849..464a149a488ff 100644 --- a/src/librustc/middle/typeck/infer/glb.rs +++ b/src/librustc/middle/typeck/infer/glb.rs @@ -27,7 +27,7 @@ use std::list; pub enum Glb = CombineFields; // "greatest lower bound" (common subtype) -pub impl Glb: Combine { +pub impl Combine for Glb { fn infcx() -> @mut InferCtxt { self.infcx } fn tag() -> ~str { ~"glb" } fn a_is_expected() -> bool { self.a_is_expected } @@ -186,7 +186,7 @@ pub impl Glb: Combine { new_vars, a_isr, a_vars, b_vars, r)); debug!("sig1 = %s", sig1.inf_str(self.infcx)); - return Ok(move sig1); + return Ok(sig1); fn generalize_region(self: &Glb, snapshot: uint, diff --git a/src/librustc/middle/typeck/infer/lattice.rs b/src/librustc/middle/typeck/infer/lattice.rs index 709864c0d13e2..df4bc46ba632b 100644 --- a/src/librustc/middle/typeck/infer/lattice.rs +++ b/src/librustc/middle/typeck/infer/lattice.rs @@ -57,7 +57,7 @@ pub trait LatticeValue { pub type LatticeOp = &fn(cf: &CombineFields, a: &T, b: &T) -> cres; -pub impl ty::t: LatticeValue { +pub impl LatticeValue for ty::t { static fn sub(cf: &CombineFields, a: &ty::t, b: &ty::t) -> ures { Sub(*cf).tys(*a, *b).to_ures() } @@ -301,7 +301,7 @@ pub trait TyLatticeDir { fn ty_bot(t: ty::t) -> cres; } -pub impl Lub: LatticeDir { +pub impl LatticeDir for Lub { fn combine_fields() -> CombineFields { *self } fn bnd(b: &Bounds) -> Option { b.ub } fn with_bnd(b: &Bounds, +t: T) -> Bounds { @@ -309,13 +309,13 @@ pub impl Lub: LatticeDir { } } -pub impl Lub: TyLatticeDir { +pub impl TyLatticeDir for Lub { fn ty_bot(t: ty::t) -> cres { Ok(t) } } -pub impl Glb: LatticeDir { +pub impl LatticeDir for Glb { fn combine_fields() -> CombineFields { *self } fn bnd(b: &Bounds) -> Option { b.lb } fn with_bnd(b: &Bounds, +t: T) -> Bounds { @@ -323,7 +323,7 @@ pub impl Glb: LatticeDir { } } -pub impl Glb: TyLatticeDir { +pub impl TyLatticeDir for Glb { fn ty_bot(_t: ty::t) -> cres { Ok(ty::mk_bot(self.infcx.tcx)) } diff --git a/src/librustc/middle/typeck/infer/lub.rs b/src/librustc/middle/typeck/infer/lub.rs index e19d5b3f47bed..60f6cd40e0430 100644 --- a/src/librustc/middle/typeck/infer/lub.rs +++ b/src/librustc/middle/typeck/infer/lub.rs @@ -36,7 +36,7 @@ pub impl Lub { fn ty_bot(b: ty::t) -> cres { self.bot_ty(b) } // commutative } -pub impl Lub: Combine { +pub impl Combine for Lub { fn infcx() -> @mut InferCtxt { self.infcx } fn tag() -> ~str { ~"lub" } fn a_is_expected() -> bool { self.a_is_expected } @@ -144,7 +144,7 @@ pub impl Lub: Combine { &sig0, |r, _in_fn| generalize_region(&self, snapshot, new_vars, a_isr, r)); - return Ok(move sig1); + return Ok(sig1); fn generalize_region(self: &Lub, snapshot: uint, diff --git a/src/librustc/middle/typeck/infer/macros.rs b/src/librustc/middle/typeck/infer/macros.rs index 8cccf75d6dc4e..01174d1620ada 100644 --- a/src/librustc/middle/typeck/infer/macros.rs +++ b/src/librustc/middle/typeck/infer/macros.rs @@ -13,8 +13,8 @@ macro_rules! if_ok( ($inp: expr) => ( match $inp { - Ok(move v) => { move v } - Err(move e) => { return Err(e); } + Ok(v) => { v } + Err(e) => { return Err(e); } } ) ); diff --git a/src/librustc/middle/typeck/infer/mod.rs b/src/librustc/middle/typeck/infer/mod.rs index f6af29c1a8df9..4f7507d4c5a2b 100644 --- a/src/librustc/middle/typeck/infer/mod.rs +++ b/src/librustc/middle/typeck/infer/mod.rs @@ -599,7 +599,7 @@ impl @mut InferCtxt { self.ty_var_bindings.bindings.truncate(0); self.int_var_bindings.bindings.truncate(0); self.region_vars.commit(); - move r + r } } @@ -613,7 +613,7 @@ impl @mut InferCtxt { Ok(_) => (), Err(_) => self.rollback_to(&snapshot) } - move r + r } } @@ -624,7 +624,7 @@ impl @mut InferCtxt { let snapshot = self.start_snapshot(); let r = self.try(f); self.rollback_to(&snapshot); - move r + r } } } diff --git a/src/librustc/middle/typeck/infer/region_inference.rs b/src/librustc/middle/typeck/infer/region_inference.rs index c838a52a6892f..cc5e860715d6d 100644 --- a/src/librustc/middle/typeck/infer/region_inference.rs +++ b/src/librustc/middle/typeck/infer/region_inference.rs @@ -899,7 +899,7 @@ pub impl RegionVarBindings { // replace the NoValue entry with ErrorValue. let mut values = self.values.take(); values[*rid] = ErrorValue; - self.values.put_back(move values); + self.values.put_back(values); re_static } @@ -999,9 +999,9 @@ pub impl RegionVarBindings { None => {} Some((ref r1, ref r2)) => { result_set = - consider_adding_edge(move result_set, &r, r1, r2); + consider_adding_edge(result_set, &r, r1, r2); result_set = - consider_adding_edge(move result_set, &r, r2, r1); + consider_adding_edge(result_set, &r, r2, r1); } } @@ -1018,13 +1018,13 @@ pub impl RegionVarBindings { r1: &Region, r2: &Region) -> ~[Region] { - let mut result_set = move result_set; + let mut result_set = result_set; if *r == *r1 { // Clearly, this is potentially inefficient. if !result_set.contains(r2) { result_set.push(*r2); } } - return move result_set; + return result_set; } } @@ -1254,8 +1254,8 @@ impl RegionVarBindings { } let mut graph = Graph { - nodes: move nodes, - edges: move edges + nodes: nodes, + edges: edges }; for uint::range(0, num_edges) |edge_idx| { @@ -1273,7 +1273,7 @@ impl RegionVarBindings { } } - return (move graph); + return (graph); fn insert_edge(+graph: &mut Graph, node_id: RegionVid, diff --git a/src/librustc/middle/typeck/infer/sub.rs b/src/librustc/middle/typeck/infer/sub.rs index 33a3220f68a31..8b37b668ff712 100644 --- a/src/librustc/middle/typeck/infer/sub.rs +++ b/src/librustc/middle/typeck/infer/sub.rs @@ -32,7 +32,7 @@ pub fn macros() { pub enum Sub = CombineFields; // "subtype", "subregion" etc -pub impl Sub: Combine { +pub impl Combine for Sub { fn infcx() -> @mut InferCtxt { self.infcx } fn tag() -> ~str { ~"sub" } fn a_is_expected() -> bool { self.a_is_expected } diff --git a/src/librustc/middle/typeck/infer/test.rs b/src/librustc/middle/typeck/infer/test.rs index d79343e64a69d..27355da4b9aee 100644 --- a/src/librustc/middle/typeck/infer/test.rs +++ b/src/librustc/middle/typeck/infer/test.rs @@ -69,7 +69,7 @@ fn setup_env(test_name: &str, source_string: &str) -> Env { cfg, parse_sess); let tcx = ty::mk_ctxt(sess, dm, amap, freevars, region_map, - region_paramd_items, move lang_items, crate); + region_paramd_items, lang_items, crate); let infcx = infer::new_infer_ctxt(tcx); @@ -192,7 +192,7 @@ impl Env { onceness: ast::Many, region: ty::re_static, bounds: @~[]}, - sig: FnSig {inputs: move inputs, + sig: FnSig {inputs: inputs, output: output_ty} }) } diff --git a/src/librustc/middle/typeck/infer/to_str.rs b/src/librustc/middle/typeck/infer/to_str.rs index bade7639e4baf..89de219f7f638 100644 --- a/src/librustc/middle/typeck/infer/to_str.rs +++ b/src/librustc/middle/typeck/infer/to_str.rs @@ -28,13 +28,13 @@ pub trait InferStr { fn inf_str(&self, cx: &InferCtxt) -> ~str; } -pub impl ty::t : InferStr { +pub impl InferStr for ty::t { fn inf_str(&self, cx: &InferCtxt) -> ~str { ty_to_str(cx.tcx, *self) } } -pub impl FnSig : InferStr { +pub impl InferStr for FnSig { fn inf_str(&self, cx: &InferCtxt) -> ~str { fmt!("(%s) -> %s", str::connect(self.inputs.map(|a| a.ty.inf_str(cx)), ", "), @@ -42,19 +42,19 @@ pub impl FnSig : InferStr { } } -pub impl ty::mt : InferStr { +pub impl InferStr for ty::mt { fn inf_str(&self, cx: &InferCtxt) -> ~str { mt_to_str(cx.tcx, *self) } } -pub impl ty::Region : InferStr { +pub impl InferStr for ty::Region { fn inf_str(&self, _cx: &InferCtxt) -> ~str { fmt!("%?", *self) } } -pub impl Bound : InferStr { +pub impl InferStr for Bound { fn inf_str(&self, cx: &InferCtxt) -> ~str { match *self { Some(ref v) => v.inf_str(cx), @@ -63,7 +63,7 @@ pub impl Bound : InferStr { } } -pub impl Bounds : InferStr { +pub impl InferStr for Bounds { fn inf_str(&self, cx: &InferCtxt) -> ~str { fmt!("{%s <: %s}", self.lb.inf_str(cx), @@ -71,7 +71,7 @@ pub impl Bounds : InferStr { } } -pub impl VarValue : InferStr { +pub impl InferStr for VarValue { fn inf_str(&self, cx: &InferCtxt) -> ~str { match *self { Redirect(ref vid) => fmt!("Redirect(%s)", vid.to_str()), @@ -81,13 +81,13 @@ pub impl VarValue : InferStr { } } -pub impl IntVarValue : InferStr { +pub impl InferStr for IntVarValue { fn inf_str(&self, _cx: &InferCtxt) -> ~str { self.to_str() } } -pub impl ast::float_ty : InferStr { +pub impl InferStr for ast::float_ty { fn inf_str(&self, _cx: &InferCtxt) -> ~str { self.to_str() } diff --git a/src/librustc/middle/typeck/infer/unify.rs b/src/librustc/middle/typeck/infer/unify.rs index 69e4f373f9742..b2aac9192f305 100644 --- a/src/librustc/middle/typeck/infer/unify.rs +++ b/src/librustc/middle/typeck/infer/unify.rs @@ -237,35 +237,35 @@ pub impl InferCtxt { // ______________________________________________________________________ -pub impl ty::TyVid : UnifyVid> { +pub impl UnifyVid> for ty::TyVid { static fn appropriate_vals_and_bindings(infcx: &v/mut InferCtxt) -> &v/mut ValsAndBindings> { return &mut infcx.ty_var_bindings; } } -pub impl ty::IntVid : UnifyVid> { +pub impl UnifyVid> for ty::IntVid { static fn appropriate_vals_and_bindings(infcx: &v/mut InferCtxt) -> &v/mut ValsAndBindings> { return &mut infcx.int_var_bindings; } } -pub impl IntVarValue : SimplyUnifiable { +pub impl SimplyUnifiable for IntVarValue { static fn to_type_err(err: expected_found) -> ty::type_err { return ty::terr_int_mismatch(err); } } -pub impl ty::FloatVid : UnifyVid> { +pub impl UnifyVid> for ty::FloatVid { static fn appropriate_vals_and_bindings(infcx: &v/mut InferCtxt) -> &v/mut ValsAndBindings> { return &mut infcx.float_var_bindings; } } -pub impl ast::float_ty : SimplyUnifiable { +pub impl SimplyUnifiable for ast::float_ty { static fn to_type_err(err: expected_found) -> ty::type_err { return ty::terr_float_mismatch(err); diff --git a/src/librustc/middle/typeck/rscope.rs b/src/librustc/middle/typeck/rscope.rs index fab86ef69fe11..4739a183cb884 100644 --- a/src/librustc/middle/typeck/rscope.rs +++ b/src/librustc/middle/typeck/rscope.rs @@ -26,7 +26,7 @@ pub trait region_scope { } pub enum empty_rscope { empty_rscope } -pub impl empty_rscope: region_scope { +pub impl region_scope for empty_rscope { pure fn anon_region(_span: span) -> Result { result::Ok(ty::re_static) } @@ -40,7 +40,7 @@ pub impl empty_rscope: region_scope { } pub enum type_rscope = Option; -pub impl type_rscope: region_scope { +pub impl region_scope for type_rscope { pure fn anon_region(_span: span) -> Result { match *self { Some(_) => result::Ok(ty::re_bound(ty::br_self)), @@ -73,7 +73,7 @@ pub fn in_anon_rscope(self: RS, r: ty::Region) -> @anon_rscope { @anon_rscope({anon: r, base: self as region_scope}) } -pub impl @anon_rscope: region_scope { +pub impl region_scope for @anon_rscope { pure fn anon_region(_span: span) -> Result { result::Ok(self.anon) } @@ -96,7 +96,7 @@ pub fn in_binding_rscope(self: RS) let base = self as region_scope; @mut binding_rscope { base: base, anon_bindings: 0 } } -pub impl @mut binding_rscope: region_scope { +pub impl region_scope for @mut binding_rscope { pure fn anon_region(_span: span) -> Result { // XXX: Unsafe to work around purity unsafe { diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index 62067a4bd7aae..b726ecacc4573 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -296,18 +296,12 @@ pub fn run_compiler(args: &~[~str], demitter: diagnostic::Emitter) { compile_input(sess, cfg, input, &odir, &ofile); } +#[deriving_eq] pub enum monitor_msg { fatal, done, } -pub impl monitor_msg : cmp::Eq { - pure fn eq(&self, other: &monitor_msg) -> bool { - ((*self) as uint) == ((*other) as uint) - } - pure fn ne(&self, other: &monitor_msg) -> bool { !(*self).eq(other) } -} - /* This is a sanity check that any failure of the compiler is performed through the diagnostic module and reported properly - we shouldn't be calling @@ -326,7 +320,7 @@ pub fn monitor(+f: fn~(diagnostic::Emitter)) { let (p, ch) = stream(); let ch = SharedChan(ch); let ch_capture = ch.clone(); - match do task::try |move f| { + match do task::try || { let ch = ch_capture.clone(); let ch_capture = ch.clone(); // The 'diagnostics emitter'. Every error, warning, etc. should @@ -375,7 +369,7 @@ pub fn monitor(+f: fn~(diagnostic::Emitter)) { pub fn main() { let args = os::args(); - do monitor |move args, demitter| { + do monitor |demitter| { run_compiler(&args, demitter); } } diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 85f4ba94e5a9b..7b980b9de0db6 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -27,7 +27,7 @@ pub fn indent(op: fn() -> R) -> R { debug!(">>"); let r = op(); debug!("<< (Result = %?)", r); - move r + r } pub struct _indenter { diff --git a/src/librustdoc/astsrv.rs b/src/librustdoc/astsrv.rs index f07701f05e799..f34a7ffbbdbcf 100644 --- a/src/librustdoc/astsrv.rs +++ b/src/librustdoc/astsrv.rs @@ -91,7 +91,7 @@ fn run(owner: SrvOwner, source: ~str, parse: Parser) -> T { let res = owner(srv_.clone()); srv_.ch.send(Exit); - move res + res } fn act(po: &Port, source: ~str, parse: Parser) { @@ -120,10 +120,10 @@ pub fn exec( f: fn~(ctxt: Ctxt) -> T ) -> T { let (po, ch) = stream(); - let msg = HandleRequest(fn~(move f, ctxt: Ctxt) { + let msg = HandleRequest(fn~(ctxt: Ctxt) { ch.send(f(ctxt)) }); - srv.ch.send(move msg); + srv.ch.send(msg); po.recv() } diff --git a/src/librustdoc/attr_pass.rs b/src/librustdoc/attr_pass.rs index 9669beae57589..85ac952d6d481 100644 --- a/src/librustdoc/attr_pass.rs +++ b/src/librustdoc/attr_pass.rs @@ -115,7 +115,7 @@ fn parse_item_attrs( srv: astsrv::Srv, id: doc::AstId, parse_attrs: fn~(a: ~[ast::attribute]) -> T) -> T { - do astsrv::exec(srv) |move parse_attrs, ctxt| { + do astsrv::exec(srv) |ctxt| { let attrs = match ctxt.ast_map.get(&id) { ast_map::node_item(item, _) => copy item.attrs, ast_map::node_foreign_item(item, _, _) => copy item.attrs, diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index f75f4b83a1d62..e904015e419f6 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -59,7 +59,7 @@ pub struct Config { pandoc_cmd: Option<~str> } -pub impl Config: Clone { +pub impl Clone for Config { fn clone(&self) -> Config { copy *self } } @@ -133,7 +133,7 @@ pub fn parse_config_( result::Ok(matches) => { if matches.free.len() == 1 { let input_crate = Path(vec::head(matches.free)); - config_from_opts(&input_crate, &matches, move program_output) + config_from_opts(&input_crate, &matches, program_output) } else if matches.free.is_empty() { result::Err(~"no crates specified") } else { @@ -191,11 +191,11 @@ fn config_from_opts( } } }; - let program_output = Cell(move program_output); + let program_output = Cell(program_output); let result = do result::chain(result) |config| { let pandoc_cmd = getopts::opt_maybe_str(matches, opt_pandoc_cmd()); let pandoc_cmd = maybe_find_pandoc( - &config, pandoc_cmd, move program_output.take()); + &config, pandoc_cmd, program_output.take()); do result::chain(pandoc_cmd) |pandoc_cmd| { result::Ok(Config { pandoc_cmd: pandoc_cmd, @@ -268,7 +268,7 @@ fn should_find_pandoc() { status: 0, out: ~"pandoc 1.8.2.1", err: ~"" } }; - let result = maybe_find_pandoc(&config, None, move mock_program_output); + let result = maybe_find_pandoc(&config, None, mock_program_output); assert result == result::Ok(Some(~"pandoc")); } @@ -284,7 +284,7 @@ fn should_error_with_no_pandoc() { status: 1, out: ~"", err: ~"" } }; - let result = maybe_find_pandoc(&config, None, move mock_program_output); + let result = maybe_find_pandoc(&config, None, mock_program_output); assert result == result::Err(~"couldn't find pandoc"); } diff --git a/src/librustdoc/fold.rs b/src/librustdoc/fold.rs index b9e598dc19d66..113cce422c474 100644 --- a/src/librustdoc/fold.rs +++ b/src/librustdoc/fold.rs @@ -87,25 +87,25 @@ fn mk_fold( fold_struct: FoldStruct ) -> Fold { Fold { - ctxt: move ctxt, - fold_doc: move fold_doc, - fold_crate: move fold_crate, - fold_item: move fold_item, - fold_mod: move fold_mod, - fold_nmod: move fold_nmod, - fold_fn: move fold_fn, - fold_const: move fold_const, - fold_enum: move fold_enum, - fold_trait: move fold_trait, - fold_impl: move fold_impl, - fold_type: move fold_type, - fold_struct: move fold_struct + ctxt: ctxt, + fold_doc: fold_doc, + fold_crate: fold_crate, + fold_item: fold_item, + fold_mod: fold_mod, + fold_nmod: fold_nmod, + fold_fn: fold_fn, + fold_const: fold_const, + fold_enum: fold_enum, + fold_trait: fold_trait, + fold_impl: fold_impl, + fold_type: fold_type, + fold_struct: fold_struct } } pub fn default_any_fold(ctxt: T) -> Fold { mk_fold( - move ctxt, + ctxt, |f, d| default_seq_fold_doc(f, d), |f, d| default_seq_fold_crate(f, d), |f, d| default_seq_fold_item(f, d), @@ -123,7 +123,7 @@ pub fn default_any_fold(ctxt: T) -> Fold { pub fn default_seq_fold(ctxt: T) -> Fold { mk_fold( - move ctxt, + ctxt, |f, d| default_seq_fold_doc(f, d), |f, d| default_seq_fold_crate(f, d), |f, d| default_seq_fold_item(f, d), @@ -141,7 +141,7 @@ pub fn default_seq_fold(ctxt: T) -> Fold { pub fn default_par_fold(ctxt: T) -> Fold { mk_fold( - move ctxt, + ctxt, |f, d| default_seq_fold_doc(f, d), |f, d| default_seq_fold_crate(f, d), |f, d| default_seq_fold_item(f, d), diff --git a/src/librustdoc/markdown_pass.rs b/src/librustdoc/markdown_pass.rs index bf499e2c5d0ec..ff9faabaec24b 100644 --- a/src/librustdoc/markdown_pass.rs +++ b/src/librustdoc/markdown_pass.rs @@ -74,7 +74,7 @@ fn run( ~"mods last", mods_last ).f)(srv, copy doc); - write_markdown(sorted_doc, move writer_factory); + write_markdown(sorted_doc, writer_factory); return doc; } @@ -148,7 +148,7 @@ fn should_request_new_writer_for_each_page() { let (srv, doc) = test::create_doc_srv(~"mod a { }"); // Split the document up into pages let doc = (page_pass::mk_pass(config::DocPerMod).f)(srv, doc); - write_markdown(doc, move writer_factory); + write_markdown(doc, writer_factory); // We expect two pages to have been written for iter::repeat(2) { po.recv(); @@ -180,7 +180,7 @@ fn should_write_title_for_each_page() { let (srv, doc) = test::create_doc_srv( ~"#[link(name = \"core\")]; mod a { }"); let doc = (page_pass::mk_pass(config::DocPerMod).f)(srv, doc); - write_markdown(doc, move writer_factory); + write_markdown(doc, writer_factory); for iter::repeat(2) { let (page, markdown) = po.recv(); match page { @@ -761,7 +761,7 @@ fn should_write_impl_header() { #[test] fn should_write_impl_header_with_trait() { - let markdown = test::render(~"impl int: j { fn a() { } }"); + let markdown = test::render(~"impl j for int { fn a() { } }"); assert str::contains(markdown, ~"## Implementation of `j` for `int`"); } @@ -894,7 +894,7 @@ mod test { doc: doc::Doc ) -> ~str { let (writer_factory, po) = markdown_writer::future_writer_factory(); - write_markdown(doc, move writer_factory); + write_markdown(doc, writer_factory); return po.recv().second(); } @@ -903,7 +903,7 @@ mod test { doc: doc::Doc ) -> ~str { let (writer_factory, po) = markdown_writer::future_writer_factory(); - let pass = mk_pass(move writer_factory); + let pass = mk_pass(writer_factory); (pass.f)(srv, doc); return po.recv().second(); } diff --git a/src/librustdoc/markdown_writer.rs b/src/librustdoc/markdown_writer.rs index f0d9effe6fc51..a6cc517079693 100644 --- a/src/librustdoc/markdown_writer.rs +++ b/src/librustdoc/markdown_writer.rs @@ -129,12 +129,12 @@ fn pandoc_writer( os::close(pipe_in.out); let (stdout_po, stdout_ch) = pipes::stream(); - do task::spawn_sched(task::SingleThreaded) |move stdout_ch| { + do task::spawn_sched(task::SingleThreaded) || { stdout_ch.send(readclose(pipe_out.in)); } let (stderr_po, stderr_ch) = pipes::stream(); - do task::spawn_sched(task::SingleThreaded) |move stderr_ch| { + do task::spawn_sched(task::SingleThreaded) || { stderr_ch.send(readclose(pipe_err.in)); } let stdout = stdout_po.recv(); @@ -169,7 +169,7 @@ fn readclose(fd: libc::c_int) -> ~str { fn generic_writer(process: fn~(markdown: ~str)) -> Writer { let (po, ch) = stream::(); - do task::spawn |move process, move setup_ch| { + do task::spawn || { let mut markdown = ~""; let mut keep_going = true; while keep_going { @@ -178,7 +178,7 @@ fn generic_writer(process: fn~(markdown: ~str)) -> Writer { Done => keep_going = false } } - process(move markdown); + process(markdown); }; fn~(instr: WriteInstr) { ch.send(instr); @@ -298,24 +298,24 @@ pub fn future_writer_factory( let writer_factory = fn~(page: doc::Page) -> Writer { let (writer_po, writer_ch) = pipes::stream(); let markdown_ch = markdown_ch.clone(); - do task::spawn |move writer_ch| { + do task::spawn || { let (writer, future) = future_writer(); - writer_ch.send(move writer); + writer_ch.send(writer); let s = future.get(); markdown_ch.send((copy page, s)); } writer_po.recv() }; - (move writer_factory, markdown_po) + (writer_factory, markdown_po) } fn future_writer() -> (Writer, future::Future<~str>) { let (port, chan) = pipes::stream(); - let writer = fn~(move chan, instr: WriteInstr) { + let writer = fn~(instr: WriteInstr) { chan.send(copy instr); }; - let future = do future::from_fn |move port| { + let future = do future::from_fn || { let mut res = ~""; loop { match port.recv() { @@ -325,5 +325,5 @@ fn future_writer() -> (Writer, future::Future<~str>) { } res }; - (move writer, move future) + (writer, future) } diff --git a/src/librustdoc/page_pass.rs b/src/librustdoc/page_pass.rs index 08abe4b351b6f..4971806c7ed81 100644 --- a/src/librustdoc/page_pass.rs +++ b/src/librustdoc/page_pass.rs @@ -71,7 +71,7 @@ fn make_doc_from_pages(page_port: &PagePort) -> doc::Doc { loop { let val = page_port.recv(); if val.is_some() { - pages += ~[option::unwrap(move val)]; + pages += ~[option::unwrap(val)]; } else { break; } diff --git a/src/librustdoc/path_pass.rs b/src/librustdoc/path_pass.rs index 7dc8d0202cbf1..ac50221445f73 100644 --- a/src/librustdoc/path_pass.rs +++ b/src/librustdoc/path_pass.rs @@ -54,7 +54,7 @@ fn run(srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc { fold_item: fold_item, fold_mod: fold_mod, fold_nmod: fold_nmod, - .. fold::default_any_fold(move ctxt) + .. fold::default_any_fold(ctxt) }; (fold.fold_doc)(&fold, doc) } diff --git a/src/librustdoc/rustdoc.rc b/src/librustdoc/rustdoc.rc index b3e9c43e87a1e..7d94352cc8233 100644 --- a/src/librustdoc/rustdoc.rc +++ b/src/librustdoc/rustdoc.rc @@ -149,5 +149,5 @@ fn time(what: ~str, f: fn() -> T) -> T { let rv = f(); let end = std::time::precise_time_s(); info!("time: %3.3f s %s", end - start, what); - move rv + rv } diff --git a/src/librustdoc/sort_pass.rs b/src/librustdoc/sort_pass.rs index b7614a785c742..3bdb08974044d 100644 --- a/src/librustdoc/sort_pass.rs +++ b/src/librustdoc/sort_pass.rs @@ -42,7 +42,7 @@ fn run( ) -> doc::Doc { let fold = Fold { fold_mod: fold_mod, - .. fold::default_any_fold(move lteq) + .. fold::default_any_fold(lteq) }; (fold.fold_doc)(&fold, doc) } diff --git a/src/librustdoc/text_pass.rs b/src/librustdoc/text_pass.rs index 79ba8f0684a58..b9dbe523fdd33 100644 --- a/src/librustdoc/text_pass.rs +++ b/src/librustdoc/text_pass.rs @@ -42,14 +42,14 @@ fn run( op: Op ) -> doc::Doc { let op = NominalOp { - op: move op + op: op }; let fold = Fold { fold_item: fold_item, fold_enum: fold_enum, fold_trait: fold_trait, fold_impl: fold_impl, - .. fold::default_any_fold(move op) + .. fold::default_any_fold(op) }; (fold.fold_doc)(&fold, doc) } @@ -76,7 +76,7 @@ fn apply_to_sections( op: NominalOp, sections: ~[doc::Section] ) -> ~[doc::Section] { - sections.map(|section, copy op| doc::Section { + sections.map(|section| doc::Section { header: (op.op)(copy section.header), body: (op.op)(copy section.body) }) @@ -89,7 +89,7 @@ fn fold_enum( let fold_copy = copy *fold; doc::EnumDoc { - variants: do doc.variants.map |variant, copy fold_copy| { + variants: do doc.variants.map |variant| { doc::VariantDoc { desc: maybe_apply_op(copy fold_copy.ctxt, &variant.desc), .. copy *variant diff --git a/src/librustdoc/tystr_pass.rs b/src/librustdoc/tystr_pass.rs index c14eb32022fb1..b39cee875251a 100644 --- a/src/librustdoc/tystr_pass.rs +++ b/src/librustdoc/tystr_pass.rs @@ -137,7 +137,7 @@ fn fold_enum( variants: do vec::map(doc.variants) |variant| { let sig = { let variant = copy *variant; - do astsrv::exec(srv.clone()) |copy variant, ctxt| { + do astsrv::exec(srv.clone()) |ctxt| { match ctxt.ast_map.get(&doc_id) { ast_map::node_item(@ast::item { node: ast::item_enum(ref enum_definition, _), _ @@ -198,7 +198,7 @@ fn get_method_sig( item_id: doc::AstId, method_name: ~str ) -> Option<~str> { - do astsrv::exec(srv) |copy method_name, ctxt| { + do astsrv::exec(srv) |ctxt| { match ctxt.ast_map.get(&item_id) { ast_map::node_item(@ast::item { node: ast::item_trait(_, _, ref methods), _ @@ -297,7 +297,7 @@ fn fold_impl( #[test] fn should_add_impl_trait_types() { - let doc = test::mk_doc(~"impl int: j { fn a() { } }"); + let doc = test::mk_doc(~"impl j for int { fn a() { } }"); assert doc.cratemod().impls()[0].trait_types[0] == ~"j"; } diff --git a/src/librusti/rusti.rc b/src/librusti/rusti.rc index 87beeaf4ec210..cd479aadb2561 100644 --- a/src/librusti/rusti.rc +++ b/src/librusti/rusti.rc @@ -351,7 +351,7 @@ fn run_line(repl: &mut Repl, in: io::Reader, out: io::Writer, line: ~str) if !cmd.is_empty() { let args = if len > 1 { - vec::slice(split, 1, len) + vec::slice(split, 1, len).to_vec() } else { ~[] }; match run_cmd(repl, in, out, cmd, args) { @@ -368,7 +368,7 @@ fn run_line(repl: &mut Repl, in: io::Reader, out: io::Writer, line: ~str) } let r = *repl; - let result = do task::try |copy r| { + let result = do task::try { run(r, line) }; diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc new file mode 100644 index 0000000000000..5b610bbb1f8ea --- /dev/null +++ b/src/librustpkg/rustpkg.rc @@ -0,0 +1,1038 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// rustpkg - a purely function package manager and build system + +#[link(name = "rustpkg", + vers = "0.6", + uuid = "25de5e6e-279e-4a20-845c-4cabae92daaf", + url = "https://github.com/mozilla/rust/tree/master/src/librustpkg")]; + +#[crate_type = "lib"]; +#[no_core]; +#[allow(vecs_implicitly_copyable, + non_implicitly_copyable_typarams)]; + +#[legacy_records]; + +extern mod core(vers = "0.6"); +extern mod std(vers = "0.6"); +extern mod rustc(vers = "0.6"); +extern mod syntax(vers = "0.6"); + +use core::*; +use io::{ReaderUtil, WriterUtil}; +use std::{json, semver, getopts}; +use std::net::url; +use hashmap::linear::LinearMap; +use rustc::metadata::filesearch; +use rustc::driver::{driver, session}; +use syntax::{ast, attr, codemap, diagnostic, parse, visit}; +use syntax::codemap::spanned; + +mod usage; +mod util; + +use util::Package; + +struct PackageScript { + id: ~str, + name: ~str, + vers: semver::Version, + crates: ~[~str], + deps: ~[(~str, Option<~str>)], + input: driver::input, + sess: session::Session, + cfg: ast::crate_cfg, + crate: @ast::crate, + custom: bool +} + +impl PackageScript { + static fn parse(parent: &Path) -> Result { + let script = parent.push(~"pkg.rs"); + + if !os::path_exists(&script) { + return result::Err(~"no pkg.rs file"); + } + + let binary = os::args()[0]; + let options: @session::options = @{ + binary: binary, + crate_type: session::bin_crate, + .. *session::basic_options() + }; + let input = driver::file_input(script); + let sess = driver::build_session(options, diagnostic::emit); + let cfg = driver::build_configuration(sess, binary, input); + let {crate, _} = driver::compile_upto(sess, cfg, input, + driver::cu_parse, None); + let mut id = None; + let mut vers = None; + let mut crates = ~[]; + let mut deps = ~[]; + + fn load_pkg_attr(mis: ~[@ast::meta_item]) -> (Option<~str>, + Option<~str>) { + let mut id = None; + let mut vers = None; + + for mis.each |a| { + match a.node { + ast::meta_name_value(v, spanned { + node: ast::lit_str(s), + span: _}) => { + match v { + ~"id" => id = Some(*s), + ~"vers" => vers = Some(*s), + _ => () + } + } + _ => {} + } + } + + (id, vers) + } + + fn load_pkg_dep_attr(mis: ~[@ast::meta_item]) -> (Option<~str>, + Option<~str>) { + let mut url = None; + let mut target = None; + + for mis.each |a| { + match a.node { + ast::meta_name_value(v, spanned { + node: ast::lit_str(s), + span: _}) => { + match v { + ~"url" => url = Some(*s), + ~"target" => target = Some(*s), + _ => () + } + } + _ => {} + } + } + + (url, target) + } + + fn load_pkg_crate_attr(mis: ~[@ast::meta_item]) -> Option<~str> { + let mut file = None; + + for mis.each |a| { + match a.node { + ast::meta_name_value(v, spanned { + node: ast::lit_str(s), + span: _}) => { + match v { + ~"file" => file = Some(*s), + _ => () + } + } + _ => {} + } + } + + file + } + + for crate.node.attrs.each |a| { + match a.node.value.node { + ast::meta_list(v, mis) => { + match v { + ~"pkg" => { + let (i, v) = load_pkg_attr(mis); + + id = i; + vers = v; + } + ~"pkg_dep" => { + let (u, t) = load_pkg_dep_attr(mis); + + if u.is_none() { + fail!(~"pkg_dep attr without a url value"); + } + + deps.push((u.get(), t)); + } + ~"pkg_crate" => { + let f = load_pkg_crate_attr(mis); + + if f.is_none() { + fail!(~"pkg_file attr without a file value"); + } + + crates.push(f.get()); + } + _ => {} + } + } + _ => {} + } + } + + let mut custom = false; + + // If we hit a function, we assume they want to use + // the build API. + for crate.node.module.items.each |i| { + match i.node { + ast::item_fn(_, _, _, _) => { + custom = true; + + break; + } + _ => {} + } + } + + if id.is_none() || vers.is_none() { + return result::Err(~"pkg attr without (id, vers) values"); + } + + let id = id.get(); + let name = match util::parse_name(id) { + result::Ok(name) => name, + result::Err(err) => return result::Err(err) + }; + let vers = match util::parse_vers(vers.get()) { + result::Ok(vers) => vers, + result::Err(err) => return result::Err(err) + }; + + result::Ok(PackageScript { + id: id, + name: name, + vers: vers, + crates: crates, + deps: deps, + input: input, + sess: sess, + cfg: cfg, + crate: crate, + custom: custom + }) + } + + // Build the bootstrap and run a command + // FIXME (#4432): Use workcache to only compile the script when changed + fn run(&self, cmd: ~str, test: bool) -> int { + let work_dir = self.work_dir(); + let input = self.input; + let sess = self.sess; + let cfg = self.cfg; + let crate = util::ready_crate(sess, self.crate); + let outputs = driver::build_output_filenames(input, &Some(work_dir), + &None, sess); + let exe = work_dir.push(~"pkg" + util::exe_suffix()); + let root = filesearch::get_rustpkg_sysroot().get().pop().pop(); + + driver::compile_rest(sess, cfg, driver::cu_parse, + Some(outputs), Some(crate)); + run::run_program(exe.to_str(), ~[root.to_str(), cmd, test.to_str()]) + } + + fn hash(&self) -> ~str { + fmt!("%s-%s-%s", self.name, util::hash(self.id + self.vers.to_str()), + self.vers.to_str()) + } + + fn work_dir(&self) -> Path { + util::root().push(~"work").push(self.hash()) + } +} + +struct Ctx { + cfgs: ~[~str], + json: bool, + mut dep_cache: LinearMap<~str, bool> +} + +impl Ctx { + fn run(&self, cmd: ~str, args: ~[~str]) { + let root = util::root(); + + util::need_dir(&root); + util::need_dir(&root.push(~"work")); + util::need_dir(&root.push(~"lib")); + util::need_dir(&root.push(~"bin")); + util::need_dir(&root.push(~"tmp")); + + fn sep_name_vers(in: ~str) -> (Option<~str>, Option<~str>) { + let mut name = None; + let mut vers = None; + let parts = str::split_char(in, '@'); + + if parts.len() >= 1 { + name = Some(parts[0]); + + if parts.len() >= 2 { + vers = Some(parts[1]); + } + } + + (name, vers) + } + + match cmd { + ~"build" => { + self.build(&os::getcwd(), true, false, false); + } + ~"clean" => { + self.clean(); + } + ~"do" => { + if args.len() < 1 { + return usage::do_cmd(); + } + + self.do_cmd(args[0]); + } + ~"info" => { + self.info(); + } + ~"install" => { + self.install(if args.len() >= 1 { Some(args[0]) } + else { None }, + if args.len() >= 2 { Some(args[1]) } + else { None }, false); + } + ~"prefer" => { + if args.len() < 1 { + return usage::uninstall(); + } + + let (name, vers) = sep_name_vers(args[0]); + + self.prefer(name.get(), vers); + } + ~"test" => { + self.test(); + } + ~"uninstall" => { + if args.len() < 1 { + return usage::uninstall(); + } + + let (name, vers) = sep_name_vers(args[0]); + + self.uninstall(name.get(), vers); + } + ~"unprefer" => { + if args.len() < 1 { + return usage::uninstall(); + } + + let (name, vers) = sep_name_vers(args[0]); + + self.unprefer(name.get(), vers); + } + _ => fail!(~"reached an unhandled command") + } + } + + fn do_cmd(&self, cmd: ~str) -> bool { + match cmd { + ~"build" | ~"test" => { + util::error(~"that command cannot be manually called"); + + return false; + } + _ => {} + } + + let cwd = &os::getcwd(); + let script = match PackageScript::parse(cwd) { + result::Ok(script) => script, + result::Err(err) => { + util::error(err); + + return false; + } + }; + let status = script.run(cmd, false); + + if status == 42 { + util::error(~"no fns are listening for that cmd"); + + return false; + } + + status == 0 + } + + fn build(&self, dir: &Path, verbose: bool, opt: bool, + test: bool) -> Option { + let cwd = &os::getcwd(); + let script = match PackageScript::parse(dir) { + result::Ok(script) => script, + result::Err(err) => { + util::error(err); + + return None; + } + }; + let work_dir = script.work_dir(); + let mut success = true; + + util::need_dir(&work_dir); + + if script.deps.len() >= 1 { + util::note(~"installing dependencies"); + + for script.deps.each |&dep| { + let (url, target) = dep; + + success = self.install(Some(url), target, true); + + if !success { break; } + } + + + if !success { + util::error( + fmt!("building %s v%s failed: a dep wasn't installed", + script.name, script.vers.to_str())); + + return None; + } + + util::note(~"installed dependencies"); + } + + // Build imperative crates + os::change_dir(dir); + + if script.custom { + let status = script.run(~"build", test); + + if status != 0 && status != 42 { + util::error( + fmt!("building %s v%s failed: custom logic failed (%d)", + script.name, script.vers.to_str(), status)); + + return None; + } + } + + os::change_dir(cwd); + + for script.crates.each |&crate| { + let crate = &dir.push_rel(&Path(crate)).normalize(); + + util::note(fmt!("compiling %s", crate.to_str())); + + success = self.compile(crate, &work_dir, ~[], + ~[], opt, test); + + if !success { break; } + } + + if !success { + util::error( + fmt!("building %s v%s failed: a crate failed to compile", + script.name, script.vers.to_str())); + + return None; + } + + if verbose { + util::note(fmt!("built %s v%s", script.name, + script.vers.to_str())); + } + + Some(script) + } + + fn compile(&self, crate: &Path, dir: &Path, flags: ~[~str], + cfgs: ~[~str], opt: bool, test: bool) -> bool { + util::compile_crate(None, crate, dir, flags, cfgs, opt, test) + } + + fn clean(&self) -> bool { + let script = match PackageScript::parse(&os::getcwd()) { + result::Ok(script) => script, + result::Err(err) => { + util::error(err); + + return false; + } + }; + let dir = script.work_dir(); + + util::note(fmt!("cleaning %s v%s (%s)", script.name, + script.vers.to_str(), script.id)); + + if os::path_exists(&dir) { + util::remove_dir_r(&dir); + util::note(fmt!("removed %s", dir.to_str())); + } + + util::note(fmt!("cleaned %s v%s", script.name, + script.vers.to_str())); + + true + } + + fn info(&self) { + if self.json { + match PackageScript::parse(&os::getcwd()) { + result::Ok(script) => { + let mut map = ~LinearMap::new(); + + map.insert(~"id", json::String(script.id)); + map.insert(~"name", json::String(script.name)); + map.insert(~"vers", json::String(script.vers.to_str())); + map.insert(~"deps", json::List(do script.deps.map |&dep| { + let (url, target) = dep; + let mut inner = ~LinearMap::new(); + + inner.insert(~"url", json::String(url)); + + if !target.is_none() { + inner.insert(~"target", + json::String(target.get())); + } + + json::Object(inner) + })); + + io::println(json::to_pretty_str(&json::Object(map))); + } + result::Err(_) => io::println(~"{}") + } + } else { + let script = match PackageScript::parse(&os::getcwd()) { + result::Ok(script) => script, + result::Err(err) => { + util::error(err); + + return; + } + }; + + util::note(fmt!("id: %s", script.id)); + util::note(fmt!("name: %s", script.name)); + util::note(fmt!("vers: %s", script.vers.to_str())); + util::note(fmt!("deps: %s", + if script.deps.len() > 0 { + ~"" + } else { + ~"none" + })); + + for script.deps.each |&dep| { + let (url, target) = dep; + + util::note(fmt!(" <%s> (%s)", url, match target { + Some(target) => target, + None => ~"" + })); + } + } + } + + fn install(&self, url: Option<~str>, + target: Option<~str>, cache: bool) -> bool { + let mut success; + let mut dir; + + if url.is_none() { + util::note(~"installing from the cwd"); + + dir = os::getcwd(); + } else { + let url = url.get(); + let hash = util::hash(if !target.is_none() { url + target.get() } + else { url }); + + if self.dep_cache.contains_key(&hash) { + util::warn(~"already installed dep this run"); + + return true; + } + + self.dep_cache.insert(hash, true); + + dir = util::root().push(~"tmp").push(hash); + + if cache && os::path_exists(&dir) { + return true; + } + + success = self.fetch(&dir, url, target); + + if !success { + return false; + } + } + + let script = match self.build(&dir, false, true, false) { + Some(script) => script, + None => { + return false; + } + }; + let work_dir = script.work_dir(); + let from_bin_dir = work_dir.push(~"bin"); + let from_lib_dir = work_dir.push(~"lib"); + let to_bin_dir = util::root().push(~"bin"); + let to_lib_dir = util::root().push(~"lib"); + let mut bins = ~[]; + let mut libs = ~[]; + + for os::walk_dir(&from_bin_dir) |bin| { + let to = to_bin_dir.push_rel(&bin.file_path()); + + os::copy_file(bin, &to); + bins.push(to.to_str()); + } + + for os::walk_dir(&from_lib_dir) |lib| { + let to = to_lib_dir.push_rel(&lib.file_path()); + + os::copy_file(lib, &to); + libs.push(to.to_str()); + } + + let package = Package { + id: script.id, + vers: script.vers, + bins: bins, + libs: libs + }; + + util::note(fmt!("installed %s v%s", script.name, + script.vers.to_str())); + util::add_pkg(&package); + + true + } + + fn fetch(&self, dir: &Path, url: ~str, target: Option<~str>) -> bool { + let url = if str::find_str(url, "://").is_none() { + ~"http://" + url } + else { url }; + let url = match url::from_str(url) { + result::Ok(url) => url, + result::Err(err) => { + util::error(fmt!("failed parsing %s", err.to_lower())); + + return false; + } + }; + let str = url.to_str(); + + match Path(url.path).filetype() { + Some(ext) => { + if ext == ~".git" { + return self.fetch_git(dir, str, target); + } + } + None => {} + } + + match url.scheme { + ~"git" => self.fetch_git(dir, str, target), + ~"http" | ~"ftp" | ~"file" => self.fetch_curl(dir, str), + _ => { + util::warn(~"unknown url scheme to fetch, using curl"); + self.fetch_curl(dir, str) + } + } + } + + fn fetch_curl(&self, dir: &Path, url: ~str) -> bool { + util::note(fmt!("fetching from %s using curl", url)); + + let tar = dir.dir_path().push(&dir.file_path().to_str() + ~".tar"); + + if run::program_output(~"curl", ~[~"-f", ~"-s", + ~"-o", tar.to_str(), + url]).status != 0 { + util::error(~"fetching failed: downloading using curl failed"); + + return false; + } + + if run::program_output(~"tar", ~[~"-x", ~"--strip-components=1", + ~"-C", dir.to_str(), ~"-f", + tar.to_str()]).status != 0 { + util::error(~"fetching failed: extracting using tar failed" + + ~"(is it a valid tar archive?)"); + + return false; + } + + true + } + + fn fetch_git(&self, dir: &Path, url: ~str, target: Option<~str>) -> bool { + util::note(fmt!("fetching from %s using git", url)); + + // Git can't clone into a non-empty directory + util::remove_dir_r(dir); + + if run::program_output(~"git", ~[~"clone", url, + dir.to_str()]).status != 0 { + util::error(~"fetching failed: can't clone repository"); + + return false; + } + + if !target.is_none() { + let mut success = true; + + do util::temp_change_dir(dir) { + success = run::program_output(~"git", + ~[~"checkout", + target.get()]).status != 0 + } + + if !success { + util::error(~"fetching failed: can't checkout target"); + + return false; + } + } + + true + } + + fn prefer(&self, id: ~str, vers: Option<~str>) -> bool { + let package = match util::get_pkg(id, vers) { + result::Ok(package) => package, + result::Err(err) => { + util::error(err); + + return false; + } + }; + let name = match util::parse_name(package.id) { + result::Ok(name) => name, + result::Err(err) => { + util::error(err); + + return false; + } + }; + + util::note(fmt!("preferring %s v%s (%s)", name, package.vers.to_str(), + package.id)); + + let bin_dir = util::root().push(~"bin"); + + for package.bins.each |&bin| { + let path = Path(bin); + let name = str::split_char(path.file_path().to_str(), '-')[0]; + let out = bin_dir.push(name); + + util::link_exe(&path, &out); + util::note(fmt!("linked %s", out.to_str())); + } + + util::note(fmt!("preferred %s v%s", name, package.vers.to_str())); + + true + } + + fn test(&self) -> bool { + let script = match self.build(&os::getcwd(), false, false, true) { + Some(script) => script, + None => { + return false; + } + }; + let work_dir = script.work_dir(); + let test_dir = work_dir.push(~"test"); + + for os::walk_dir(&test_dir) |test| { + util::note(fmt!("running %s", test.to_str())); + + let status = run::run_program(test.to_str(), ~[]); + + if status != 0 { + os::set_exit_status(status); + } + } + + // Run custom test listener + if script.custom { + let status = script.run(~"test", false); + + if status != 0 && status != 42 { + util::error( + fmt!("testing %s v%s failed: custom logic failed (%d)", + script.name, script.vers.to_str(), status)); + + os::set_exit_status(status); + } + } + + util::note(fmt!("tested %s v%s", script.name, script.vers.to_str())); + + true + } + + fn uninstall(&self, id: ~str, vers: Option<~str>) -> bool { + let package = match util::get_pkg(id, vers) { + result::Ok(package) => package, + result::Err(err) => { + util::error(err); + + return false; + } + }; + let name = match util::parse_name(package.id) { + result::Ok(name) => name, + result::Err(err) => { + util::error(err); + + return false; + } + }; + + util::note(fmt!("uninstalling %s v%s (%s)", name, + package.vers.to_str(), package.id)); + + for vec::append(package.bins, package.libs).each |&file| { + let path = Path(file); + + if os::path_exists(&path) { + if os::remove_file(&path) { + util::note(fmt!("removed %s", path.to_str())); + } else { + util::error(fmt!("could not remove %s", path.to_str())); + } + } + } + + util::note(fmt!("uninstalled %s v%s", name, package.vers.to_str())); + util::remove_pkg(&package); + + true + } + + fn unprefer(&self, id: ~str, vers: Option<~str>) -> bool { + let package = match util::get_pkg(id, vers) { + result::Ok(package) => package, + result::Err(err) => { + util::error(err); + + return false; + } + }; + let name = match util::parse_name(package.id) { + result::Ok(name) => name, + result::Err(err) => { + util::error(err); + + return false; + } + }; + + util::note(fmt!("unpreferring %s v%s (%s)", name, + package.vers.to_str(), package.id)); + + let bin_dir = util::root().push(~"bin"); + + for package.bins.each |&bin| { + let path = Path(bin); + let name = str::split_char(path.file_path().to_str(), '-')[0]; + let out = bin_dir.push(name); + + if os::path_exists(&out) { + if os::remove_file(&out) { + util::note(fmt!("unlinked %s", out.to_str())); + } else { + util::error(fmt!("could not unlink %s", out.to_str())); + } + } + } + + util::note(fmt!("unpreferred %s v%s", name, package.vers.to_str())); + + true + } +} + +pub fn main() { + let args = os::args(); + let opts = ~[getopts::optflag(~"h"), getopts::optflag(~"help"), + getopts::optflag(~"j"), getopts::optflag(~"json"), + getopts::optmulti(~"c"), getopts::optmulti(~"cfg")]; + let matches = &match getopts::getopts(args, opts) { + result::Ok(m) => m, + result::Err(f) => { + util::error(fmt!("%s", getopts::fail_str(f))); + + return; + } + }; + let help = getopts::opt_present(matches, ~"h") || + getopts::opt_present(matches, ~"help"); + let json = getopts::opt_present(matches, ~"j") || + getopts::opt_present(matches, ~"json"); + let cfgs = vec::append(getopts::opt_strs(matches, ~"cfg"), + getopts::opt_strs(matches, ~"c")); + let mut args = copy matches.free; + + args.shift(); + + if (args.len() < 1) { + return usage::general(); + } + + let cmd = args.shift(); + + if !util::is_cmd(cmd) { + return usage::general(); + } else if help { + return match cmd { + ~"build" => usage::build(), + ~"clean" => usage::clean(), + ~"do" => usage::do_cmd(), + ~"info" => usage::info(), + ~"install" => usage::install(), + ~"prefer" => usage::prefer(), + ~"test" => usage::test(), + ~"uninstall" => usage::uninstall(), + ~"unprefer" => usage::unprefer(), + _ => usage::general() + }; + } + + Ctx { + cfgs: cfgs, + json: json, + mut dep_cache: LinearMap::new() + }.run(cmd, args); +} + +/// A crate is a unit of Rust code to be compiled into a binary or library +pub struct Crate { + file: ~str, + flags: ~[~str], + cfgs: ~[~str] +} + +pub struct Listener { + cmds: ~[~str], + cb: fn~() +} + +pub fn run(listeners: ~[Listener]) { + let rcmd = os::args()[2]; + let mut found = false; + + for listeners.each |listener| { + for listener.cmds.each |&cmd| { + if cmd == rcmd { + (listener.cb)(); + + found = true; + + break; + } + } + } + + if !found { + os::set_exit_status(42); + } +} + +pub impl Crate { + pub fn flag(&self, flag: ~str) -> Crate { + Crate { + flags: vec::append(copy self.flags, ~[flag]), + .. copy *self + } + } + + pub fn flags(&self, flags: ~[~str]) -> Crate { + Crate { + flags: vec::append(copy self.flags, flags), + .. copy *self + } + } + + pub fn cfg(&self, cfg: ~str) -> Crate { + Crate { + cfgs: vec::append(copy self.cfgs, ~[cfg]), + .. copy *self + } + } + + pub fn cfgs(&self, cfgs: ~[~str]) -> Crate { + Crate { + cfgs: vec::append(copy self.cfgs, cfgs), + .. copy *self + } + } +} + +/// Create a crate target from a source file +pub fn Crate(file: ~str) -> Crate { + Crate { + file: file, + flags: ~[], + cfgs: ~[] + } +} + +/** + * Get the working directory of the package script. + * Assumes that the package script has been compiled + * in is the working directory. + */ +pub fn work_dir() -> Path { + os::self_exe_path().get() +} + +/** + * Get the source directory of the package (i.e. + * where the crates are located). Assumes + * that the cwd is changed to it before + * running this executable. + */ +pub fn src_dir() -> Path { + os::getcwd() +} + +/// Build a set of crates, should be called once +pub fn build(crates: ~[Crate]) -> bool { + let args = os::args(); + let dir = src_dir(); + let work_dir = work_dir(); + let mut success = true; + let sysroot = Path(args[1]); + let test = args[3] == ~"true"; + + for crates.each |&crate| { + let path = &dir.push_rel(&Path(crate.file)).normalize(); + + util::note(fmt!("compiling %s", path.to_str())); + + success = util::compile_crate(Some(sysroot), path, &work_dir, + crate.flags, crate.cfgs, + false, test); + + if !success { break; } + } + + if !success { + os::set_exit_status(101); + } + + success +} diff --git a/src/librustpkg/usage.rs b/src/librustpkg/usage.rs new file mode 100644 index 0000000000000..cfda56f777ab2 --- /dev/null +++ b/src/librustpkg/usage.rs @@ -0,0 +1,121 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::io; + +pub fn general() { + io::println(~"Usage: rustpkg [options] [args..] + +Where is one of: + build, clean, do, info, install, prefer, test, uninstall, unprefer + +Options: + + -h, --help Display this message + -h, --help Display help for "); +} + +pub fn build() { + io::println(~"rustpkg [options..] build + +Build all targets described in the package script in the current +directory. + +Options: + -c, --cfg Pass a cfg flag to the package script"); +} + +pub fn clean() { + io::println(~"rustpkg clean + +Remove all build files in the work cache for the package in the current +directory."); +} + +pub fn do_cmd() { + io::println(~"rustpkg do + +Runs a command in the package script. You can listen to a command +by tagging a function with the attribute `#[pkg_do(cmd)]`."); +} + +pub fn info() { + io::println(~"rustpkg [options..] info + +Probe the package script in the current directory for information. + +Options: + -j, --json Output the result as JSON"); +} + +pub fn install() { + io::println(~"rustpkg [options..] install [url] [target] + +Install a package from a URL by Git or cURL (FTP, HTTP, etc.). +If target is provided, Git will checkout the branch or tag before +continuing. If the URL is a TAR file (with or without compression), +extract it before installing. If a URL isn't provided, the package will +be built and installed from the current directory (which is +functionally the same as `rustpkg build` and installing the result). + +Examples: + rustpkg install + rustpkg install git://github.com/mozilla/servo.git + rustpkg install git://github.com/mozilla/servo.git v0.1.2 + rustpkg install http://rust-lang.org/servo-0.1.2.tar.gz + +Options: + -c, --cfg Pass a cfg flag to the package script"); +} + +pub fn uninstall() { + io::println(~"rustpkg uninstall [@version] + +Remove a package by id or name and optionally version. If the package(s) +is/are depended on by another package then they cannot be removed."); +} + +pub fn prefer() { + io::println(~"rustpkg [options..] prefer [@version] + +By default all binaries are given a unique name so that multiple versions can +coexist. The prefer command will symlink the uniquely named binary to +the binary directory under its bare name. If version is not supplied, the +latest version of the package will be preferred. + +Example: + export PATH=$PATH:/home/user/.rustpkg/bin + rustpkg prefer machine@1.2.4 + machine -v + ==> v1.2.4 + rustpkg prefer machine@0.4.6 + machine -v + ==> v0.4.6"); +} + +pub fn unprefer() { + io::println(~"rustpkg [options..] unprefer [@version] + +Remove all symlinks from the store to the binary directory for a package +name and optionally version. If version is not supplied, the latest version +of the package will be unpreferred. See `rustpkg prefer -h` for more +information."); +} + +pub fn test() { + io::println(~"rustpkg [options..] test + +Build all targets described in the package script in the current directory +with the test flag. The test bootstraps will be run afterwards and the output +and exit code will be redirected. + +Options: + -c, --cfg Pass a cfg flag to the package script"); +} diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs new file mode 100644 index 0000000000000..1ad706742a8f6 --- /dev/null +++ b/src/librustpkg/util.rs @@ -0,0 +1,803 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::*; +use hashmap::linear::LinearMap; +use rustc::metadata::filesearch; +use rustc::driver::{driver, session}; +use syntax::ast_util::*; +use syntax::{ast, attr, codemap, diagnostic, fold, parse, visit}; +use codemap::{span, dummy_sp, spanned}; +use std::semver; +use std::{json, term, sort, getopts}; +use getopts::groups::getopts; +use Listener; + +use syntax::ext::base::{mk_ctxt, ext_ctxt}; +use syntax::ext::build; + +pub struct Package { + id: ~str, + vers: semver::Version, + bins: ~[~str], + libs: ~[~str], +} + +pub fn root() -> Path { + match filesearch::get_rustpkg_root() { + result::Ok(path) => path, + result::Err(err) => fail!(err) + } +} + +pub fn is_cmd(cmd: ~str) -> bool { + let cmds = &[~"build", ~"clean", ~"do", ~"info", ~"install", ~"prefer", + ~"test", ~"uninstall", ~"unprefer"]; + + vec::contains(cmds, &cmd) +} + +pub fn parse_name(id: ~str) -> result::Result<~str, ~str> { + let parts = str::split_char(id, '.'); + + for parts.each |&part| { + for str::chars(part).each |&char| { + if char::is_whitespace(char) { + return result::Err( + ~"could not parse id: contains whitespace"); + } else if char::is_uppercase(char) { + return result::Err( + ~"could not parse id: should be all lowercase"); + } + } + } + + result::Ok(parts.last()) +} + +struct ListenerFn { + cmds: ~[~str], + span: codemap::span, + path: ~[ast::ident] +} + +struct ReadyCtx { + sess: session::Session, + crate: @ast::crate, + ext_cx: ext_ctxt, + mut path: ~[ast::ident], + mut fns: ~[ListenerFn] +} + +fn fold_mod(_ctx: @ReadyCtx, m: ast::_mod, + fold: fold::ast_fold) -> ast::_mod { + fn strip_main(item: @ast::item) -> @ast::item { + @ast::item { + attrs: do item.attrs.filtered |attr| { + attr::get_attr_name(*attr) != ~"main" + }, + .. copy *item + } + } + + fold::noop_fold_mod(ast::_mod { + items: do vec::map(m.items) |item| { + strip_main(*item) + }, + .. m + }, fold) +} + +fn fold_item(ctx: @ReadyCtx, item: @ast::item, + fold: fold::ast_fold) -> Option<@ast::item> { + + ctx.path.push(item.ident); + + let attrs = attr::find_attrs_by_name(item.attrs, ~"pkg_do"); + + if attrs.len() > 0 { + let mut cmds = ~[]; + + for attrs.each |attr| { + match attr.node.value.node { + ast::meta_list(_, mis) => { + for mis.each |mi| { + match mi.node { + ast::meta_word(cmd) => cmds.push(cmd), + _ => {} + }; + } + } + _ => cmds.push(~"build") + }; + } + + ctx.fns.push(ListenerFn { + cmds: cmds, + span: item.span, + path: /*bad*/copy ctx.path + }); + } + + let res = fold::noop_fold_item(item, fold); + + ctx.path.pop(); + + res +} + +fn add_pkg_module(ctx: @ReadyCtx, m: ast::_mod) -> ast::_mod { + let listeners = mk_listener_vec(ctx); + let ext_cx = ctx.ext_cx; + let item = quote_item! ( + mod __pkg { + extern mod rustpkg (vers="0.6"); + const listeners : &[rustpkg::Listener] = $listeners; + #[main] + fn main() { + rustpkg::run(listeners); + } + } + ); + ast::_mod { + items: vec::append_one(/*bad*/copy m.items, item.get()), + .. m + } +} + +fn mk_listener_vec(ctx: @ReadyCtx) -> @ast::expr { + let fns = ctx.fns; + let descs = do fns.map |listener| { + mk_listener_rec(ctx, *listener) + }; + build::mk_slice_vec_e(ctx.ext_cx, dummy_sp(), descs) +} + +fn mk_listener_rec(ctx: @ReadyCtx, listener: ListenerFn) -> @ast::expr { + + let span = listener.span; + let cmds = do listener.cmds.map |&cmd| { + build::mk_base_str(ctx.ext_cx, span, cmd) + }; + + let cmds_expr = build::mk_slice_vec_e(ctx.ext_cx, span, cmds); + let cb_expr = build::mk_path(ctx.ext_cx, span, copy listener.path); + let ext_cx = ctx.ext_cx; + + quote_expr!( + Listener { + cmds: $cmds_expr, + cb: $cb_expr + } + ) +} + +/// Generate/filter main function, add the list of commands, etc. +pub fn ready_crate(sess: session::Session, + crate: @ast::crate) -> @ast::crate { + let ctx = @ReadyCtx { + sess: sess, + crate: crate, + ext_cx: mk_ctxt(sess.parse_sess, copy sess.opts.cfg), + mut path: ~[], + mut fns: ~[] + }; + let precursor = @fold::AstFoldFns { + // fold_crate: fold::wrap(|a, b| fold_crate(ctx, a, b)), + fold_item: |a, b| fold_item(ctx, a, b), + fold_mod: |a, b| fold_mod(ctx, a, b), + .. *fold::default_ast_fold() + }; + + let fold = fold::make_fold(precursor); + + @fold.fold_crate(*crate) +} + +pub fn parse_vers(vers: ~str) -> result::Result { + match semver::parse(vers) { + Some(vers) => result::Ok(vers), + None => result::Err(~"could not parse version: invalid") + } +} + +pub fn need_dir(s: &Path) { + if !os::path_is_dir(s) && !os::make_dir(s, 493_i32) { + fail!(fmt!("can't create dir: %s", s.to_str())); + } +} + +pub fn note(msg: ~str) { + let out = io::stdout(); + + if term::color_supported() { + term::fg(out, term::color_green); + out.write_str(~"note: "); + term::reset(out); + out.write_line(msg); + } else { + out.write_line(~"note: " + msg); + } +} + +pub fn warn(msg: ~str) { + let out = io::stdout(); + + if term::color_supported() { + term::fg(out, term::color_yellow); + out.write_str(~"warning: "); + term::reset(out); + out.write_line(msg); + } else { + out.write_line(~"warning: " + msg); + } +} + +pub fn error(msg: ~str) { + let out = io::stdout(); + + if term::color_supported() { + term::fg(out, term::color_red); + out.write_str(~"error: "); + term::reset(out); + out.write_line(msg); + } else { + out.write_line(~"error: " + msg); + } +} + +pub fn hash(data: ~str) -> ~str { + let hasher = hash::default_state(); + + hasher.write_str(data); + hasher.result_str() +} + +pub fn temp_change_dir(dir: &Path, cb: fn() -> T) { + let cwd = os::getcwd(); + + os::change_dir(dir); + cb(); + os::change_dir(&cwd); +} + +pub fn touch(path: &Path) { + match io::mk_file_writer(path, ~[io::Create]) { + result::Ok(writer) => writer.write_line(~""), + _ => {} + } +} + +pub fn remove_dir_r(path: &Path) { + for os::walk_dir(path) |&file| { + let mut cdir = file; + + loop { + if os::path_is_dir(&cdir) { + os::remove_dir(&cdir); + } else { + os::remove_file(&cdir); + } + + cdir = cdir.dir_path(); + + if cdir == *path { break; } + } + } + + os::remove_dir(path); +} + +pub fn wait_for_lock(path: &Path) { + if os::path_exists(path) { + warn(fmt!("the database appears locked, please wait (or rm %s)", + path.to_str())); + + loop { + if !os::path_exists(path) { break; } + } + } +} + +fn _add_pkg(packages: ~[json::Json], pkg: &Package) -> ~[json::Json] { + for packages.each |&package| { + match &package { + &json::Object(ref map) => { + let mut has_id = false; + + match map.get(&~"id") { + &json::String(ref str) => { + if pkg.id == *str { + has_id = true; + } + } + _ => {} + } + + match map.get(&~"vers") { + &json::String(ref str) => { + if has_id && pkg.vers.to_str() == *str { + return copy packages; + } + } + _ => {} + } + } + _ => {} + } + } + + let mut map = ~LinearMap::new(); + + map.insert(~"id", json::String(pkg.id)); + map.insert(~"vers", json::String(pkg.vers.to_str())); + map.insert(~"bins", json::List(do pkg.bins.map |&bin| { + json::String(bin) + })); + map.insert(~"libs", json::List(do pkg.libs.map |&lib| { + json::String(lib) + })); + + vec::append(packages, ~[json::Object(map)]) +} + +fn _rm_pkg(packages: ~[json::Json], pkg: &Package) -> ~[json::Json] { + do packages.filter_mapped |&package| { + match &package { + &json::Object(ref map) => { + let mut has_id = false; + + match map.get(&~"id") { + &json::String(str) => { + if pkg.id == str { + has_id = true; + } + } + _ => {} + } + + match map.get(&~"vers") { + &json::String(ref str) => { + if has_id && pkg.vers.to_str() == *str { + None + } else { + Some(copy package) + } + } + _ => { Some(copy package) } + } + } + _ => { Some(copy package) } + } + } +} + +pub fn load_pkgs() -> result::Result<~[json::Json], ~str> { + let root = root(); + let db = root.push(~"db.json"); + let db_lock = root.push(~"db.json.lck"); + + wait_for_lock(&db_lock); + touch(&db_lock); + + let packages = if os::path_exists(&db) { + match io::read_whole_file_str(&db) { + result::Ok(str) => { + match json::from_str(str) { + result::Ok(json) => { + match json { + json::List(list) => list, + _ => { + os::remove_file(&db_lock); + + return result::Err( + ~"package db's json is not a list"); + } + } + } + result::Err(err) => { + os::remove_file(&db_lock); + + return result::Err( + fmt!("failed to parse package db: %s", + err.to_str())); + } + } + } + result::Err(err) => { + os::remove_file(&db_lock); + + return result::Err(fmt!("failed to read package db: %s", + err)); + } + } + } else { ~[] }; + + os::remove_file(&db_lock); + + result::Ok(packages) +} + +pub fn get_pkg(id: ~str, + vers: Option<~str>) -> result::Result { + let name = match parse_name(id) { + result::Ok(name) => name, + result::Err(err) => return result::Err(err) + }; + let packages = match load_pkgs() { + result::Ok(packages) => packages, + result::Err(err) => return result::Err(err) + }; + let mut sel = None; + let mut possibs = ~[]; + let mut err = None; + + for packages.each |&package| { + match package { + json::Object(map) => { + let pid = match map.get(&~"id") { + &json::String(str) => str, + _ => loop + }; + let pname = match parse_name(pid) { + result::Ok(pname) => pname, + result::Err(perr) => { + err = Some(perr); + + break; + } + }; + let pvers = match map.get(&~"vers") { + &json::String(str) => str, + _ => loop + }; + if pid == id || pname == name { + let bins = match map.get(&~"bins") { + &json::List(ref list) => { + do list.map |&bin| { + match bin { + json::String(str) => str, + _ => ~"" + } + } + } + _ => ~[] + }; + let libs = match map.get(&~"libs") { + &json::List(ref list) => { + do list.map |&lib| { + match lib { + json::String(str) => str, + _ => ~"" + } + } + } + _ => ~[] + }; + let package = Package { + id: pid, + vers: match parse_vers(pvers) { + result::Ok(vers) => vers, + result::Err(verr) => { + err = Some(verr); + + break; + } + }, + bins: bins, + libs: libs + }; + + if !vers.is_none() && vers.get() == pvers { + sel = Some(package); + } + else { + possibs.push(package); + } + } + } + _ => {} + } + } + + if !err.is_none() { + return result::Err(err.get()); + } + if !sel.is_none() { + return result::Ok(sel.get()); + } + if !vers.is_none() || possibs.len() < 1 { + return result::Err(~"package not found"); + } + + result::Ok(sort::merge_sort(possibs, |v1, v2| { + v1.vers <= v2.vers + }).last()) +} + +pub fn add_pkg(pkg: &Package) -> bool { + let root = root(); + let db = root.push(~"db.json"); + let db_lock = root.push(~"db.json.lck"); + let packages = match load_pkgs() { + result::Ok(packages) => packages, + result::Err(err) => { + error(err); + + return false; + } + }; + + wait_for_lock(&db_lock); + touch(&db_lock); + os::remove_file(&db); + + match io::mk_file_writer(&db, ~[io::Create]) { + result::Ok(writer) => { + writer.write_line(json::to_pretty_str(&json::List( + _add_pkg(packages, pkg)))); + } + result::Err(err) => { + error(fmt!("failed to dump package db: %s", err)); + os::remove_file(&db_lock); + + return false; + } + } + + os::remove_file(&db_lock); + + true +} + +pub fn remove_pkg(pkg: &Package) -> bool { + let root = root(); + let db = root.push(~"db.json"); + let db_lock = root.push(~"db.json.lck"); + let packages = match load_pkgs() { + result::Ok(packages) => packages, + result::Err(err) => { + error(err); + + return false; + } + }; + + wait_for_lock(&db_lock); + touch(&db_lock); + os::remove_file(&db); + + match io::mk_file_writer(&db, ~[io::Create]) { + result::Ok(writer) => { + writer.write_line(json::to_pretty_str(&json::List( + _rm_pkg(packages, pkg)))); + } + result::Err(err) => { + error(fmt!("failed to dump package db: %s", err)); + os::remove_file(&db_lock); + + return false; + } + } + + os::remove_file(&db_lock); + + true +} + +pub fn compile_input(sysroot: Option, input: driver::input, dir: &Path, + flags: ~[~str], cfgs: ~[~str], opt: bool, test: bool) -> bool { + let lib_dir = dir.push(~"lib"); + let bin_dir = dir.push(~"bin"); + let test_dir = dir.push(~"test"); + let binary = os::args()[0]; + let matches = getopts(flags, driver::optgroups()).get(); + let options = @{ + crate_type: session::unknown_crate, + optimize: if opt { session::Aggressive } else { session::No }, + test: test, + maybe_sysroot: sysroot, + .. *driver::build_session_options(binary, &matches, diagnostic::emit) + }; + let mut crate_cfg = options.cfg; + + for cfgs.each |&cfg| { + crate_cfg.push(attr::mk_word_item(cfg)); + } + + let options = @{ + cfg: vec::append(options.cfg, crate_cfg), + .. *options + }; + let sess = driver::build_session(options, diagnostic::emit); + let cfg = driver::build_configuration(sess, binary, input); + let mut outputs = driver::build_output_filenames(input, &None, &None, + sess); + let {crate, _} = driver::compile_upto(sess, cfg, input, driver::cu_parse, + Some(outputs)); + + let mut name = None; + let mut vers = None; + let mut uuid = None; + let mut crate_type = None; + + fn load_link_attr(mis: ~[@ast::meta_item]) -> (Option<~str>, + Option<~str>, + Option<~str>) { + let mut name = None; + let mut vers = None; + let mut uuid = None; + + for mis.each |a| { + match a.node { + ast::meta_name_value(v, spanned {node: ast::lit_str(s), + span: _}) => { + match v { + ~"name" => name = Some(*s), + ~"vers" => vers = Some(*s), + ~"uuid" => uuid = Some(*s), + _ => { } + } + } + _ => {} + } + } + + (name, vers, uuid) + } + + for crate.node.attrs.each |a| { + match a.node.value.node { + ast::meta_name_value(v, spanned {node: ast::lit_str(s), + span: _}) => { + match v { + ~"crate_type" => crate_type = Some(*s), + _ => {} + } + } + ast::meta_list(v, mis) => { + match v { + ~"link" => { + let (n, v, u) = load_link_attr(mis); + + name = n; + vers = v; + uuid = u; + } + _ => {} + } + } + _ => {} + } + } + + if name.is_none() || vers.is_none() || uuid.is_none() { + error(~"link attr without (name, vers, uuid) values"); + + return false; + } + + let name = name.get(); + let vers = vers.get(); + let uuid = uuid.get(); + + let is_bin = match crate_type { + Some(crate_type) => { + match crate_type { + ~"bin" => true, + ~"lib" => false, + _ => { + warn(~"unknown crate_type, falling back to lib"); + + false + } + } + } + None => { + warn(~"missing crate_type attr, assuming lib"); + + false + } + }; + + if test { + need_dir(&test_dir); + + outputs = driver::build_output_filenames(input, &Some(test_dir), + &None, sess) + } + else if is_bin { + need_dir(&bin_dir); + + let path = bin_dir.push(fmt!("%s-%s-%s%s", name, + hash(name + uuid + vers), + vers, exe_suffix())); + outputs = driver::build_output_filenames(input, &None, &Some(path), + sess); + } else { + need_dir(&lib_dir); + + outputs = driver::build_output_filenames(input, &Some(lib_dir), + &None, sess) + } + + driver::compile_rest(sess, cfg, driver::cu_everything, + Some(outputs), Some(crate)); + + true +} + +#[cfg(windows)] +pub fn exe_suffix() -> ~str { ~".exe" } + +#[cfg(target_os = "linux")] +#[cfg(target_os = "android")] +#[cfg(target_os = "freebsd")] +#[cfg(target_os = "macos")] +pub fn exe_suffix() -> ~str { ~"" } + + +// FIXME (#4432): Use workcache to only compile when needed +pub fn compile_crate(sysroot: Option, crate: &Path, dir: &Path, + flags: ~[~str], cfgs: ~[~str], opt: bool, + test: bool) -> bool { + compile_input(sysroot, driver::file_input(*crate), dir, flags, cfgs, + opt, test) +} + +pub fn compile_str(sysroot: Option, code: ~str, dir: &Path, + flags: ~[~str], cfgs: ~[~str], opt: bool, + test: bool) -> bool { + compile_input(sysroot, driver::str_input(code), dir, flags, cfgs, + opt, test) +} + +#[cfg(windows)] +pub fn link_exe(_src: &Path, _dest: &Path) -> bool { + /* FIXME (#1768): Investigate how to do this on win32 + Node wraps symlinks by having a .bat, + but that won't work with minGW. */ + + false +} + +#[cfg(target_os = "linux")] +#[cfg(target_os = "android")] +#[cfg(target_os = "freebsd")] +#[cfg(target_os = "macos")] +pub fn link_exe(src: &Path, dest: &Path) -> bool { + unsafe { + do str::as_c_str(src.to_str()) |src_buf| { + do str::as_c_str(dest.to_str()) |dest_buf| { + libc::link(src_buf, dest_buf) == 0 as libc::c_int && + libc::chmod(dest_buf, 755) == 0 as libc::c_int + } + } + } +} + +#[test] +fn test_is_cmd() { + assert is_cmd(~"build"); + assert is_cmd(~"clean"); + assert is_cmd(~"do"); + assert is_cmd(~"info"); + assert is_cmd(~"install"); + assert is_cmd(~"prefer"); + assert is_cmd(~"test"); + assert is_cmd(~"uninstall"); + assert is_cmd(~"unprefer"); +} + +#[test] +fn test_parse_name() { + assert parse_name(~"org.mozilla.servo").get() == ~"servo"; + assert parse_name(~"org. mozilla.servo 2131").is_err(); +} diff --git a/src/libstd/arc.rs b/src/libstd/arc.rs index 59e278f17960f..66b02ae553c4e 100644 --- a/src/libstd/arc.rs +++ b/src/libstd/arc.rs @@ -81,7 +81,7 @@ struct ARC { x: SharedMutableState } /// Create an atomically reference counted wrapper. pub fn ARC(data: T) -> ARC { - ARC { x: unsafe { shared_mutable_state(move data) } } + ARC { x: unsafe { shared_mutable_state(data) } } } /** @@ -113,8 +113,8 @@ pub fn clone(rc: &ARC) -> ARC { * guaranteed to deadlock. */ pub fn unwrap(rc: ARC) -> T { - let ARC { x: x } = move rc; - unsafe { unwrap_shared_mutable_state(move x) } + let ARC { x: x } = rc; + unsafe { unwrap_shared_mutable_state(x) } } impl Clone for ARC { @@ -134,7 +134,7 @@ struct MutexARC { x: SharedMutableState> } /// Create a mutex-protected ARC with the supplied data. pub fn MutexARC(user_data: T) -> MutexARC { - mutex_arc_with_condvars(move user_data, 1) + mutex_arc_with_condvars(user_data, 1) } /** * Create a mutex-protected ARC with the supplied data and a specified number @@ -144,8 +144,8 @@ pub fn mutex_arc_with_condvars(user_data: T, num_condvars: uint) -> MutexARC { let data = MutexARCInner { lock: mutex_with_condvars(num_condvars), - failed: false, data: move user_data }; - MutexARC { x: unsafe { shared_mutable_state(move data) } } + failed: false, data: user_data }; + MutexARC { x: unsafe { shared_mutable_state(data) } } } impl Clone for MutexARC { @@ -220,13 +220,13 @@ impl &MutexARC { */ // FIXME(#3724) make this a by-move method on the arc pub fn unwrap_mutex_arc(arc: MutexARC) -> T { - let MutexARC { x: x } = move arc; - let inner = unsafe { unwrap_shared_mutable_state(move x) }; - let MutexARCInner { failed: failed, data: data, _ } = move inner; + let MutexARC { x: x } = arc; + let inner = unsafe { unwrap_shared_mutable_state(x) }; + let MutexARCInner { failed: failed, data: data, _ } = inner; if failed { fail!(~"Can't unwrap poisoned MutexARC - another task failed inside!") } - move data + data } // Common code for {mutex.access,rwlock.write}{,_cond}. @@ -284,7 +284,7 @@ struct RWARC { /// Create a reader/writer ARC with the supplied data. pub fn RWARC(user_data: T) -> RWARC { - rw_arc_with_condvars(move user_data, 1) + rw_arc_with_condvars(user_data, 1) } /** * Create a reader/writer ARC with the supplied data and a specified number @@ -296,8 +296,8 @@ pub fn rw_arc_with_condvars( { let data = RWARCInner { lock: rwlock_with_condvars(num_condvars), - failed: false, data: move user_data }; - RWARC { x: unsafe { shared_mutable_state(move data) }, cant_nest: () } + failed: false, data: user_data }; + RWARC { x: unsafe { shared_mutable_state(data) }, cant_nest: () } } impl RWARC { @@ -386,7 +386,7 @@ impl &RWARC { do (*borrow_rwlock(state)).write_downgrade |write_mode| { check_poison(false, (*state).failed); blk(RWWriteMode((&mut (*state).data, - move write_mode, + write_mode, PoisonOnFail(&mut (*state).failed)))) } } @@ -396,9 +396,9 @@ impl &RWARC { fn downgrade(token: RWWriteMode/&a) -> RWReadMode/&a { // The rwlock should assert that the token belongs to us for us. let state = unsafe { get_shared_immutable_state(&self.x) }; - let RWWriteMode((data, t, _poison)) = move token; + let RWWriteMode((data, t, _poison)) = token; // Let readers in - let new_token = (&state.lock).downgrade(move t); + let new_token = (&state.lock).downgrade(t); // Whatever region the input reference had, it will be safe to use // the same region for the output reference. (The only 'unsafe' part // of this cast is removing the mutability.) @@ -406,7 +406,7 @@ impl &RWARC { // Downgrade ensured the token belonged to us. Just a sanity check. assert ptr::ref_eq(&state.data, new_data); // Produce new token - RWReadMode((new_data, move new_token)) + RWReadMode((new_data, new_token)) } } @@ -419,13 +419,13 @@ impl &RWARC { */ // FIXME(#3724) make this a by-move method on the arc pub fn unwrap_rw_arc(arc: RWARC) -> T { - let RWARC { x: x, _ } = move arc; - let inner = unsafe { unwrap_shared_mutable_state(move x) }; - let RWARCInner { failed: failed, data: data, _ } = move inner; + let RWARC { x: x, _ } = arc; + let inner = unsafe { unwrap_shared_mutable_state(x) }; + let RWARCInner { failed: failed, data: data, _ } = inner; if failed { fail!(~"Can't unwrap poisoned RWARC - another task failed inside!") } - move data + data } // Borrowck rightly complains about immutably aliasing the rwlock in order to @@ -509,7 +509,7 @@ mod tests { let (p, c) = pipes::stream(); - do task::spawn() |move c| { + do task::spawn() || { let p = pipes::PortSet(); c.send(p.chan()); @@ -532,8 +532,8 @@ mod tests { let arc = ~MutexARC(false); let arc2 = ~arc.clone(); let (p,c) = pipes::oneshot(); - let (c,p) = (~mut Some(move c), ~mut Some(move p)); - do task::spawn |move arc2, move p| { + let (c,p) = (~mut Some(c), ~mut Some(p)); + do task::spawn || { // wait until parent gets in pipes::recv_one(option::swap_unwrap(p)); do arc2.access_cond |state, cond| { @@ -555,7 +555,7 @@ mod tests { let arc2 = ~arc.clone(); let (p, c) = pipes::stream(); - do task::spawn_unlinked |move arc2, move p| { + do task::spawn_unlinked || { let _ = p.recv(); do arc2.access_cond |one, cond| { cond.signal(); @@ -574,7 +574,7 @@ mod tests { pub fn test_mutex_arc_poison() { let arc = ~MutexARC(1); let arc2 = ~arc.clone(); - do task::try |move arc2| { + do task::try || { do arc2.access |one| { assert *one == 2; } @@ -588,21 +588,21 @@ mod tests { let arc = MutexARC(1); let arc2 = ~(&arc).clone(); let (p, c) = pipes::stream(); - do task::spawn |move c, move arc2| { + do task::spawn || { do arc2.access |one| { c.send(()); assert *one == 2; } } let _ = p.recv(); - let one = unwrap_mutex_arc(move arc); + let one = unwrap_mutex_arc(arc); assert one == 1; } #[test] #[should_fail] #[ignore(cfg(windows))] pub fn test_rw_arc_poison_wr() { let arc = ~RWARC(1); let arc2 = ~arc.clone(); - do task::try |move arc2| { + do task::try || { do arc2.write |one| { assert *one == 2; } @@ -615,7 +615,7 @@ mod tests { pub fn test_rw_arc_poison_ww() { let arc = ~RWARC(1); let arc2 = ~arc.clone(); - do task::try |move arc2| { + do task::try || { do arc2.write |one| { assert *one == 2; } @@ -628,7 +628,7 @@ mod tests { pub fn test_rw_arc_poison_dw() { let arc = ~RWARC(1); let arc2 = ~arc.clone(); - do task::try |move arc2| { + do task::try || { do arc2.write_downgrade |write_mode| { do (&write_mode).write |one| { assert *one == 2; @@ -643,7 +643,7 @@ mod tests { pub fn test_rw_arc_no_poison_rr() { let arc = ~RWARC(1); let arc2 = ~arc.clone(); - do task::try |move arc2| { + do task::try || { do arc2.read |one| { assert *one == 2; } @@ -656,7 +656,7 @@ mod tests { pub fn test_rw_arc_no_poison_rw() { let arc = ~RWARC(1); let arc2 = ~arc.clone(); - do task::try |move arc2| { + do task::try || { do arc2.read |one| { assert *one == 2; } @@ -669,9 +669,9 @@ mod tests { pub fn test_rw_arc_no_poison_dr() { let arc = ~RWARC(1); let arc2 = ~arc.clone(); - do task::try |move arc2| { + do task::try || { do arc2.write_downgrade |write_mode| { - let read_mode = arc2.downgrade(move write_mode); + let read_mode = arc2.downgrade(write_mode); do (&read_mode).read |one| { assert *one == 2; } @@ -687,7 +687,7 @@ mod tests { let arc2 = ~arc.clone(); let (p,c) = pipes::stream(); - do task::spawn |move arc2, move c| { + do task::spawn || { do arc2.write |num| { for 10.times { let tmp = *num; @@ -703,8 +703,8 @@ mod tests { let mut children = ~[]; for 5.times { let arc3 = ~arc.clone(); - do task::task().future_result(|+r| children.push(move r)).spawn - |move arc3| { + do task::task().future_result(|+r| children.push(r)).spawn + || { do arc3.read |num| { assert *num >= 0; } @@ -732,9 +732,9 @@ mod tests { let mut reader_convos = ~[]; for 10.times { let ((rp1,rc1),(rp2,rc2)) = (pipes::stream(),pipes::stream()); - reader_convos.push((move rc1, move rp2)); + reader_convos.push((rc1, rp2)); let arcn = ~arc.clone(); - do task::spawn |move rp1, move rc2, move arcn| { + do task::spawn || { rp1.recv(); // wait for downgrader to give go-ahead do arcn.read |state| { assert *state == 31337; @@ -746,7 +746,7 @@ mod tests { // Writer task let arc2 = ~arc.clone(); let ((wp1,wc1),(wp2,wc2)) = (pipes::stream(),pipes::stream()); - do task::spawn |move arc2, move wc2, move wp1| { + do task::spawn || { wp1.recv(); do arc2.write_cond |state, cond| { assert *state == 0; @@ -779,7 +779,7 @@ mod tests { } } } - let read_mode = arc.downgrade(move write_mode); + let read_mode = arc.downgrade(write_mode); do (&read_mode).read |state| { // complete handshake with other readers for vec::each(reader_convos) |x| { diff --git a/src/libstd/bigint.rs b/src/libstd/bigint.rs index ab622438511bb..23a4769775c00 100644 --- a/src/libstd/bigint.rs +++ b/src/libstd/bigint.rs @@ -216,8 +216,9 @@ impl Mul for BigUint { pure fn cut_at(a: &BigUint, n: uint) -> (BigUint, BigUint) { let mid = uint::min(a.data.len(), n); - return (BigUint::from_slice(vec::view(a.data, mid, a.data.len())), - BigUint::from_slice(vec::view(a.data, 0, mid))); + return (BigUint::from_slice(vec::slice(a.data, mid, + a.data.len())), + BigUint::from_slice(vec::slice(a.data, 0, mid))); } pure fn sub_sign(a: BigUint, b: BigUint) -> (int, BigUint) { @@ -301,7 +302,7 @@ pub impl BigUint { let mut power: BigUint = One::one(); loop { let start = uint::max(end, unit_len) - unit_len; - match uint::parse_bytes(vec::view(buf, start, end), radix) { + match uint::parse_bytes(vec::slice(buf, start, end), radix) { Some(d) => n += BigUint::from_uint(d) * power, None => return None } @@ -380,7 +381,7 @@ pub impl BigUint { return (Zero::zero(), Zero::zero(), copy *a); } - let an = vec::view(a.data, a.data.len() - n, a.data.len()); + let an = vec::slice(a.data, a.data.len() - n, a.data.len()); let bn = b.data.last(); let mut d = ~[]; let mut carry = 0; @@ -487,7 +488,7 @@ pub impl BigUint { if n_unit == 0 { return self; } if self.data.len() < n_unit { return Zero::zero(); } return BigUint::from_slice( - vec::view(self.data, n_unit, self.data.len()) + vec::slice(self.data, n_unit, self.data.len()) ); } @@ -770,7 +771,7 @@ pub impl BigInt { sign = Minus; start = 1; } - return BigUint::parse_bytes(vec::view(buf, start, buf.len()), radix) + return BigUint::parse_bytes(vec::slice(buf, start, buf.len()), radix) .map(|bu| BigInt::from_biguint(sign, *bu)); } @@ -885,7 +886,7 @@ mod biguint_tests { let data = [ &[], &[1], &[2], &[-1], &[0, 1], &[2, 1], &[1, 1, 1] ] .map(|v| BigUint::from_slice(*v)); for data.eachi |i, ni| { - for vec::view(data, i, data.len()).eachi |j0, nj| { + for vec::slice(data, i, data.len()).eachi |j0, nj| { let j = j0 + i; if i == j { assert ni.cmp(nj) == 0; @@ -1298,7 +1299,7 @@ mod bigint_tests { nums.push_all_move(vs.map(|s| BigInt::from_slice(Plus, *s))); for nums.eachi |i, ni| { - for vec::view(nums, i, nums.len()).eachi |j0, nj| { + for vec::slice(nums, i, nums.len()).eachi |j0, nj| { let j = i + j0; if i == j { assert ni.cmp(nj) == 0; diff --git a/src/libstd/bitv.rs b/src/libstd/bitv.rs index e6557d163f9db..75b97f494bd6f 100644 --- a/src/libstd/bitv.rs +++ b/src/libstd/bitv.rs @@ -108,7 +108,7 @@ struct BigBitv { } fn BigBitv(storage: ~[uint]) -> BigBitv { - BigBitv {storage: move storage} + BigBitv {storage: storage} } /** @@ -232,9 +232,9 @@ pub fn Bitv (nbits: uint, init: bool) -> Bitv { if nbits % uint_bits == 0 {0} else {1}; let elem = if init {!0} else {0}; let s = from_elem(nelems, elem); - Big(~BigBitv(move s)) + Big(~BigBitv(s)) }; - Bitv {rep: move rep, nbits: nbits} + Bitv {rep: rep, nbits: nbits} } priv impl Bitv { @@ -519,7 +519,7 @@ impl Clone for Bitv { let mut st = from_elem(self.nbits / uint_bits + 1, 0); let len = st.len(); for uint::range(0, len) |i| { st[i] = b.storage[i]; }; - Bitv{nbits: self.nbits, rep: Big(~BigBitv{storage: move st})} + Bitv{nbits: self.nbits, rep: Big(~BigBitv{storage: st})} } } } @@ -555,7 +555,7 @@ pub fn from_fn(len: uint, f: fn(index: uint) -> bool) -> Bitv { for uint::range(0, len) |i| { bitv.set(i, f(i)); } - move bitv + bitv } const uint_bits: uint = 32u + (1u << 32u >> 27u); diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs index f0ec3c1b9d767..c8121daddabd0 100644 --- a/src/libstd/cell.rs +++ b/src/libstd/cell.rs @@ -21,7 +21,7 @@ pub struct Cell { /// Creates a new full cell with the given value. pub fn Cell(value: T) -> Cell { - Cell { value: Some(move value) } + Cell { value: Some(value) } } pub pure fn empty_cell() -> Cell { @@ -37,7 +37,7 @@ impl Cell { let mut value = None; value <-> self.value; - return option::unwrap(move value); + return option::unwrap(value); } /// Returns the value, failing if the cell is full. @@ -45,7 +45,7 @@ impl Cell { if !self.is_empty() { fail!(~"attempt to put a value back into a full cell"); } - self.value = Some(move value); + self.value = Some(value); } /// Returns true if the cell is empty and false if the cell is full. @@ -57,8 +57,8 @@ impl Cell { fn with_ref(op: fn(v: &T) -> R) -> R { let v = self.take(); let r = op(&v); - self.put_back(move v); - move r + self.put_back(v); + r } } @@ -69,7 +69,7 @@ fn test_basic() { let value = value_cell.take(); assert value == ~10; assert value_cell.is_empty(); - value_cell.put_back(move value); + value_cell.put_back(value); assert !value_cell.is_empty(); } diff --git a/src/libstd/comm.rs b/src/libstd/comm.rs index 47f3c70352c3b..c2c21002b195d 100644 --- a/src/libstd/comm.rs +++ b/src/libstd/comm.rs @@ -27,13 +27,13 @@ pub struct DuplexStream { impl GenericChan for DuplexStream { fn send(x: T) { - self.chan.send(move x) + self.chan.send(x) } } impl GenericSmartChan for DuplexStream { fn try_send(x: T) -> bool { - self.chan.try_send(move x) + self.chan.try_send(x) } } @@ -66,12 +66,12 @@ pub fn DuplexStream() let (p1, c2) = pipes::stream(); let (p2, c1) = pipes::stream(); (DuplexStream { - chan: move c1, - port: move p1 + chan: c1, + port: p1 }, DuplexStream { - chan: move c2, - port: move p2 + chan: c2, + port: p2 }) } diff --git a/src/libstd/deque.rs b/src/libstd/deque.rs index 772cacf47a11b..2c90100a6f654 100644 --- a/src/libstd/deque.rs +++ b/src/libstd/deque.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -8,178 +8,158 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! A deque. Untested as of yet. Likely buggy -#[forbid(non_camel_case_types)]; - +use core::container::{Container, Mutable}; use core::cmp::Eq; -use core::dvec::DVec; -use core::dvec; use core::prelude::*; use core::uint; use core::vec; -pub trait Deque { - fn size() -> uint; - fn add_front(v: T); - fn add_back(v: T); - fn pop_front() -> T; - fn pop_back() -> T; - fn peek_front() -> T; - fn peek_back() -> T; - fn get(int) -> T; +const initial_capacity: uint = 32u; // 2^5 + +pub struct Deque { + priv nelts: uint, + priv lo: uint, + priv hi: uint, + priv elts: ~[Option] } -// FIXME (#2343) eventually, a proper datatype plus an exported impl would -// be preferrable. -pub fn create() -> Deque { - type Cell = Option; +impl Container for Deque { + pure fn len(&self) -> uint { self.nelts } + pure fn is_empty(&self) -> bool { self.len() == 0 } +} - let initial_capacity: uint = 32u; // 2^5 - /** - * Grow is only called on full elts, so nelts is also len(elts), unlike - * elsewhere. - */ - fn grow(nelts: uint, lo: uint, elts: ~[Cell]) - -> ~[Cell] { - let mut elts = move elts; - assert (nelts == vec::len(elts)); - let mut rv = ~[]; +impl Mutable for Deque { + fn clear(&mut self) { + for vec::each_mut(self.elts) |x| { *x = None } + self.nelts = 0; + self.lo = 0; + self.hi = 0; + } +} - let mut i = 0u; - let nalloc = uint::next_power_of_two(nelts + 1u); - while i < nalloc { - if i < nelts { - rv.push(elts[(lo + i) % nelts]); - } else { rv.push(None); } - i += 1u; - } +impl Deque { + static pure fn new() -> Deque { + Deque{nelts: 0, lo: 0, hi: 0, + elts: vec::from_fn(initial_capacity, |_| None)} + } + + fn peek_front(&self) -> &self/T { get(self.elts, self.lo) } + fn peek_back(&self) -> &self/T { get(self.elts, self.hi - 1u) } - move rv + fn get(&self, i: int) -> &self/T { + let idx = (self.lo + (i as uint)) % self.elts.len(); + get(self.elts, idx) } - fn get(elts: &DVec>, i: uint) -> T { - match (*elts).get_elt(i) { Some(move t) => t, _ => fail!() } + + fn pop_front(&mut self) -> T { + let mut result = self.elts[self.lo].swap_unwrap(); + self.lo = (self.lo + 1u) % self.elts.len(); + self.nelts -= 1u; + result } - struct Repr { - mut nelts: uint, - mut lo: uint, - mut hi: uint, - elts: DVec>, + fn pop_back(&mut self) -> T { + if self.hi == 0u { + self.hi = self.elts.len() - 1u; + } else { self.hi -= 1u; } + let mut result = self.elts[self.hi].swap_unwrap(); + self.elts[self.hi] = None; + self.nelts -= 1u; + result } - impl Deque for Repr { - fn size() -> uint { return self.nelts; } - fn add_front(t: T) { - let oldlo: uint = self.lo; - if self.lo == 0u { - self.lo = self.elts.len() - 1u; - } else { self.lo -= 1u; } - if self.lo == self.hi { - self.elts.swap(|v| grow(self.nelts, oldlo, move v)); - self.lo = self.elts.len() - 1u; - self.hi = self.nelts; - } - self.elts.set_elt(self.lo, Some(t)); - self.nelts += 1u; - } - fn add_back(t: T) { - if self.lo == self.hi && self.nelts != 0u { - self.elts.swap(|v| grow(self.nelts, self.lo, move v)); - self.lo = 0u; - self.hi = self.nelts; - } - self.elts.set_elt(self.hi, Some(t)); - self.hi = (self.hi + 1u) % self.elts.len(); - self.nelts += 1u; - } - /** - * We actually release (turn to none()) the T we're popping so - * that we don't keep anyone's refcount up unexpectedly. - */ - fn pop_front() -> T { - let t: T = get(&self.elts, self.lo); - self.elts.set_elt(self.lo, None); - self.lo = (self.lo + 1u) % self.elts.len(); - self.nelts -= 1u; - return t; - } - fn pop_back() -> T { - if self.hi == 0u { - self.hi = self.elts.len() - 1u; - } else { self.hi -= 1u; } - let t: T = get(&self.elts, self.hi); - self.elts.set_elt(self.hi, None); - self.nelts -= 1u; - return t; + fn add_front(&mut self, t: T) { + let oldlo = self.lo; + if self.lo == 0u { + self.lo = self.elts.len() - 1u; + } else { self.lo -= 1u; } + if self.lo == self.hi { + self.elts = grow(self.nelts, oldlo, self.elts); + self.lo = self.elts.len() - 1u; + self.hi = self.nelts; } - fn peek_front() -> T { return get(&self.elts, self.lo); } - fn peek_back() -> T { return get(&self.elts, self.hi - 1u); } - fn get(i: int) -> T { - let idx = (self.lo + (i as uint)) % self.elts.len(); - return get(&self.elts, idx); + self.elts[self.lo] = Some(t); + self.nelts += 1u; + } + + fn add_back(&mut self, t: T) { + if self.lo == self.hi && self.nelts != 0u { + self.elts = grow(self.nelts, self.lo, self.elts); + self.lo = 0u; + self.hi = self.nelts; } + self.elts[self.hi] = Some(t); + self.hi = (self.hi + 1u) % self.elts.len(); + self.nelts += 1u; + } +} + +/// Grow is only called on full elts, so nelts is also len(elts), unlike +/// elsewhere. +fn grow(nelts: uint, lo: uint, elts: &mut [Option]) -> ~[Option] { + assert nelts == elts.len(); + let mut rv = ~[]; + + do vec::grow_fn(&mut rv, nelts + 1) |i| { + let mut element = None; + element <-> elts[(lo + i) % nelts]; + element } - let repr: Repr = Repr { - nelts: 0u, - lo: 0u, - hi: 0u, - elts: dvec::from_vec(vec::from_elem(initial_capacity, None)), - }; + rv +} - repr as Deque:: +fn get(elts: &r/[Option], i: uint) -> &r/T { + match elts[i] { Some(ref t) => t, _ => fail!() } } #[cfg(test)] mod tests { - use core::prelude::*; - - use deque::*; - use deque; + use super::*; #[test] fn test_simple() { - let d: deque::Deque = deque::create::(); - assert (d.size() == 0u); + let mut d = Deque::new(); + assert d.len() == 0u; d.add_front(17); d.add_front(42); d.add_back(137); - assert (d.size() == 3u); + assert d.len() == 3u; d.add_back(137); - assert (d.size() == 4u); + assert d.len() == 4u; log(debug, d.peek_front()); - assert (d.peek_front() == 42); + assert *d.peek_front() == 42; log(debug, d.peek_back()); - assert (d.peek_back() == 137); + assert *d.peek_back() == 137; let mut i: int = d.pop_front(); log(debug, i); - assert (i == 42); + assert i == 42; i = d.pop_back(); log(debug, i); - assert (i == 137); + assert i == 137; i = d.pop_back(); log(debug, i); - assert (i == 137); + assert i == 137; i = d.pop_back(); log(debug, i); - assert (i == 17); - assert (d.size() == 0u); + assert i == 17; + assert d.len() == 0u; d.add_back(3); - assert (d.size() == 1u); + assert d.len() == 1u; d.add_front(2); - assert (d.size() == 2u); + assert d.len() == 2u; d.add_back(4); - assert (d.size() == 3u); + assert d.len() == 3u; d.add_front(1); - assert (d.size() == 4u); + assert d.len() == 4u; log(debug, d.get(0)); log(debug, d.get(1)); log(debug, d.get(2)); log(debug, d.get(3)); - assert (d.get(0) == 1); - assert (d.get(1) == 2); - assert (d.get(2) == 3); - assert (d.get(3) == 4); + assert *d.get(0) == 1; + assert *d.get(1) == 2; + assert *d.get(2) == 3; + assert *d.get(3) == 4; } #[test] @@ -189,63 +169,63 @@ mod tests { let c: @int = @64; let d: @int = @175; - let deq: deque::Deque<@int> = deque::create::<@int>(); - assert (deq.size() == 0u); + let mut deq = Deque::new(); + assert deq.len() == 0; deq.add_front(a); deq.add_front(b); deq.add_back(c); - assert (deq.size() == 3u); + assert deq.len() == 3; deq.add_back(d); - assert (deq.size() == 4u); - assert (deq.peek_front() == b); - assert (deq.peek_back() == d); - assert (deq.pop_front() == b); - assert (deq.pop_back() == d); - assert (deq.pop_back() == c); - assert (deq.pop_back() == a); - assert (deq.size() == 0u); + assert deq.len() == 4; + assert *deq.peek_front() == b; + assert *deq.peek_back() == d; + assert deq.pop_front() == b; + assert deq.pop_back() == d; + assert deq.pop_back() == c; + assert deq.pop_back() == a; + assert deq.len() == 0; deq.add_back(c); - assert (deq.size() == 1u); + assert deq.len() == 1; deq.add_front(b); - assert (deq.size() == 2u); + assert deq.len() == 2; deq.add_back(d); - assert (deq.size() == 3u); + assert deq.len() == 3; deq.add_front(a); - assert (deq.size() == 4u); - assert (deq.get(0) == a); - assert (deq.get(1) == b); - assert (deq.get(2) == c); - assert (deq.get(3) == d); + assert deq.len() == 4; + assert *deq.get(0) == a; + assert *deq.get(1) == b; + assert *deq.get(2) == c; + assert *deq.get(3) == d; } fn test_parameterized(a: T, b: T, c: T, d: T) { - let deq: deque::Deque = deque::create::(); - assert (deq.size() == 0u); + let mut deq = Deque::new(); + assert deq.len() == 0; deq.add_front(a); deq.add_front(b); deq.add_back(c); - assert (deq.size() == 3u); + assert deq.len() == 3; deq.add_back(d); - assert (deq.size() == 4u); - assert deq.peek_front() == b; - assert deq.peek_back() == d; + assert deq.len() == 4; + assert *deq.peek_front() == b; + assert *deq.peek_back() == d; assert deq.pop_front() == b; assert deq.pop_back() == d; assert deq.pop_back() == c; assert deq.pop_back() == a; - assert (deq.size() == 0u); + assert deq.len() == 0; deq.add_back(c); - assert (deq.size() == 1u); + assert deq.len() == 1; deq.add_front(b); - assert (deq.size() == 2u); + assert deq.len() == 2; deq.add_back(d); - assert (deq.size() == 3u); + assert deq.len() == 3; deq.add_front(a); - assert (deq.size() == 4u); - assert deq.get(0) == a; - assert deq.get(1) == b; - assert deq.get(2) == c; - assert deq.get(3) == d; + assert deq.len() == 4; + assert *deq.get(0) == a; + assert *deq.get(1) == b; + assert *deq.get(2) == c; + assert *deq.get(3) == d; } #[deriving_eq] diff --git a/src/libstd/ebml.rs b/src/libstd/ebml.rs index f691dfe6a6273..84df1785503dc 100644 --- a/src/libstd/ebml.rs +++ b/src/libstd/ebml.rs @@ -177,10 +177,12 @@ pub mod reader { } } - pub fn doc_data(d: Doc) -> ~[u8] { vec::slice::(*d.data, d.start, - d.end) } + pub fn doc_data(d: Doc) -> ~[u8] { + vec::slice::(*d.data, d.start, d.end).to_vec() + } + pub fn with_doc_data(d: Doc, f: fn(x: &[u8]) -> T) -> T { - f(vec::view(*d.data, d.start, d.end)) + f(vec::slice(*d.data, d.start, d.end)) } pub fn doc_as_str(d: Doc) -> ~str { str::from_bytes(doc_data(d)) } @@ -259,7 +261,7 @@ pub mod reader { r_doc } - fn push_doc(d: Doc, f: fn() -> T) -> T{ + fn push_doc(d: Doc, f: fn() -> T) -> T { let old_parent = self.parent; let old_pos = self.pos; self.parent = d; @@ -267,7 +269,7 @@ pub mod reader { let r = f(); self.parent = old_parent; self.pos = old_pos; - move r + r } fn _next_uint(exp_tag: EbmlEncoderTag) -> uint { diff --git a/src/libstd/flatpipes.rs b/src/libstd/flatpipes.rs index dad761ac20d7c..cff30587607f5 100644 --- a/src/libstd/flatpipes.rs +++ b/src/libstd/flatpipes.rs @@ -28,7 +28,7 @@ This example sends boxed integers across tasks using serialization. ~~~ let (port, chan) = serial::pipe_stream(); -do task::spawn |move chan| { +do task::spawn || { for int::range(0, 10) |i| { chan.send(@i) } @@ -114,8 +114,8 @@ pub mod serial { let unflat: DeserializingUnflattener = DeserializingUnflattener::new( deserialize_buffer::); - let byte_port = ReaderBytePort::new(move reader); - FlatPort::new(move unflat, move byte_port) + let byte_port = ReaderBytePort::new(reader); + FlatPort::new(unflat, byte_port) } /// Create a `FlatChan` from a `Writer` @@ -124,8 +124,8 @@ pub mod serial { let flat: SerializingFlattener = SerializingFlattener::new( serialize_value::); - let byte_chan = WriterByteChan::new(move writer); - FlatChan::new(move flat, move byte_chan) + let byte_chan = WriterByteChan::new(writer); + FlatChan::new(flat, byte_chan) } /// Create a `FlatPort` from a `Port<~[u8]>` @@ -135,8 +135,8 @@ pub mod serial { let unflat: DeserializingUnflattener = DeserializingUnflattener::new( deserialize_buffer::); - let byte_port = PipeBytePort::new(move port); - FlatPort::new(move unflat, move byte_port) + let byte_port = PipeBytePort::new(port); + FlatPort::new(unflat, byte_port) } /// Create a `FlatChan` from a `Chan<~[u8]>` @@ -146,8 +146,8 @@ pub mod serial { let flat: SerializingFlattener = SerializingFlattener::new( serialize_value::); - let byte_chan = PipeByteChan::new(move chan); - FlatChan::new(move flat, move byte_chan) + let byte_chan = PipeByteChan::new(chan); + FlatChan::new(flat, byte_chan) } /// Create a pair of `FlatChan` and `FlatPort`, backed by pipes @@ -155,7 +155,7 @@ pub mod serial { Decodable>( ) -> (PipePort, PipeChan) { let (port, chan) = pipes::stream(); - return (pipe_port(move port), pipe_chan(move chan)); + return (pipe_port(port), pipe_chan(chan)); } } @@ -193,8 +193,8 @@ pub mod pod { reader: R ) -> ReaderPort { let unflat: PodUnflattener = PodUnflattener::new(); - let byte_port = ReaderBytePort::new(move reader); - FlatPort::new(move unflat, move byte_port) + let byte_port = ReaderBytePort::new(reader); + FlatPort::new(unflat, byte_port) } /// Create a `FlatChan` from a `Writer` @@ -202,28 +202,28 @@ pub mod pod { writer: W ) -> WriterChan { let flat: PodFlattener = PodFlattener::new(); - let byte_chan = WriterByteChan::new(move writer); - FlatChan::new(move flat, move byte_chan) + let byte_chan = WriterByteChan::new(writer); + FlatChan::new(flat, byte_chan) } /// Create a `FlatPort` from a `Port<~[u8]>` pub fn pipe_port(port: Port<~[u8]>) -> PipePort { let unflat: PodUnflattener = PodUnflattener::new(); - let byte_port = PipeBytePort::new(move port); - FlatPort::new(move unflat, move byte_port) + let byte_port = PipeBytePort::new(port); + FlatPort::new(unflat, byte_port) } /// Create a `FlatChan` from a `Chan<~[u8]>` pub fn pipe_chan(chan: Chan<~[u8]>) -> PipeChan { let flat: PodFlattener = PodFlattener::new(); - let byte_chan = PipeByteChan::new(move chan); - FlatChan::new(move flat, move byte_chan) + let byte_chan = PipeByteChan::new(chan); + FlatChan::new(flat, byte_chan) } /// Create a pair of `FlatChan` and `FlatPort`, backed by pipes pub fn pipe_stream() -> (PipePort, PipeChan) { let (port, chan) = pipes::stream(); - return (pipe_port(move port), pipe_chan(move chan)); + return (pipe_port(port), pipe_chan(chan)); } } @@ -258,16 +258,16 @@ pub trait ByteChan { const CONTINUE: [u8 * 4] = [0xAA, 0xBB, 0xCC, 0xDD]; -pub impl,P:BytePort> FlatPort: GenericPort { +pub impl,P:BytePort> GenericPort for FlatPort { fn recv() -> T { match self.try_recv() { - Some(move val) => move val, + Some(val) => val, None => fail!(~"port is closed") } } fn try_recv() -> Option { let command = match self.byte_port.try_recv(CONTINUE.len()) { - Some(move c) => move c, + Some(c) => c, None => { warn!("flatpipe: broken pipe"); return None; @@ -288,8 +288,8 @@ pub impl,P:BytePort> FlatPort: GenericPort { let msg_len = msg_len as uint; match self.byte_port.try_recv(msg_len) { - Some(move bytes) => { - Some(self.unflattener.unflatten(move bytes)) + Some(bytes) => { + Some(self.unflattener.unflatten(bytes)) } None => { warn!("flatpipe: broken pipe"); @@ -306,20 +306,20 @@ pub impl,P:BytePort> FlatPort: GenericPort { impl,C:ByteChan> GenericChan for FlatChan { fn send(val: T) { self.byte_chan.send(CONTINUE.to_vec()); - let bytes = self.flattener.flatten(move val); + let bytes = self.flattener.flatten(val); let len = bytes.len() as u64; do io::u64_to_be_bytes(len, size_of::()) |len_bytes| { self.byte_chan.send(len_bytes.to_vec()); } - self.byte_chan.send(move bytes); + self.byte_chan.send(bytes); } } pub impl,P:BytePort> FlatPort { static fn new(u: U, p: P) -> FlatPort { FlatPort { - unflattener: move u, - byte_port: move p + unflattener: u, + byte_port: p } } } @@ -327,8 +327,8 @@ pub impl,P:BytePort> FlatPort { pub impl,C:ByteChan> FlatChan { static fn new(f: F, c: C) -> FlatChan { FlatChan { - flattener: move f, - byte_chan: move c + flattener: f, + byte_chan: c } } } @@ -358,7 +358,7 @@ pub mod flatteners { bogus: () } - pub impl PodUnflattener: Unflattener { + pub impl Unflattener for PodUnflattener { fn unflatten(&self, buf: ~[u8]) -> T { assert size_of::() != 0; assert size_of::() == buf.len(); @@ -368,7 +368,7 @@ pub mod flatteners { } } - pub impl PodFlattener: Flattener { + pub impl Flattener for PodFlattener { fn flatten(&self, val: T) -> ~[u8] { assert size_of::() != 0; let val: *T = ptr::to_unsafe_ptr(&val); @@ -406,38 +406,34 @@ pub mod flatteners { serialize_value: SerializeValue } - pub impl> - DeserializingUnflattener: Unflattener { + pub impl> Unflattener + for DeserializingUnflattener { fn unflatten(&self, buf: ~[u8]) -> T { (self.deserialize_buffer)(buf) } } - pub impl> - SerializingFlattener: Flattener { + pub impl> Flattener + for SerializingFlattener { fn flatten(&self, val: T) -> ~[u8] { (self.serialize_value)(&val) } } - pub impl> - DeserializingUnflattener { - - static fn new(deserialize_buffer: DeserializeBuffer - ) -> DeserializingUnflattener { + pub impl> DeserializingUnflattener { + static fn new(deserialize_buffer: DeserializeBuffer) + -> DeserializingUnflattener { DeserializingUnflattener { - deserialize_buffer: move deserialize_buffer + deserialize_buffer: deserialize_buffer } } } - pub impl> - SerializingFlattener { - - static fn new(serialize_value: SerializeValue - ) -> SerializingFlattener { + pub impl> SerializingFlattener { + static fn new(serialize_value: SerializeValue) + -> SerializingFlattener { SerializingFlattener { - serialize_value: move serialize_value + serialize_value: serialize_value } } } @@ -450,7 +446,7 @@ pub mod flatteners { pub fn deserialize_buffer>(buf: &[u8]) -> T { let buf = vec::from_slice(buf); - let buf_reader = @BufReader::new(move buf); + let buf_reader = @BufReader::new(buf); let reader = buf_reader as @Reader; let deser: D = FromReader::from_reader(reader); Decodable::decode(&deser) @@ -462,8 +458,8 @@ pub mod flatteners { let writer = bytes_writer as @Writer; let ser = FromWriter::from_writer(writer); val.encode(&ser); - let bytes = bytes_writer.bytes.check_out(|bytes| move bytes); - return move bytes; + let bytes = bytes_writer.bytes.check_out(|bytes| bytes); + return bytes; } pub trait FromReader { @@ -477,8 +473,8 @@ pub mod flatteners { impl FromReader for json::Decoder { static fn from_reader(r: Reader) -> json::Decoder { match json::from_reader(r) { - Ok(move json) => { - json::Decoder(move json) + Ok(json) => { + json::Decoder(json) } Err(e) => fail!(fmt!("flatpipe: can't parse json: %?", e)) } @@ -487,7 +483,7 @@ pub mod flatteners { impl FromWriter for json::Encoder { static fn from_writer(w: Writer) -> json::Encoder { - json::Encoder(move w) + json::Encoder(w) } } @@ -495,13 +491,13 @@ pub mod flatteners { static fn from_reader(r: Reader) -> ebml::reader::Decoder { let buf = @r.read_whole_stream(); let doc = ebml::reader::Doc(buf); - ebml::reader::Decoder(move doc) + ebml::reader::Decoder(doc) } } impl FromWriter for ebml::writer::Encoder { static fn from_writer(w: Writer) -> ebml::writer::Encoder { - ebml::writer::Encoder(move w) + ebml::writer::Encoder(w) } } @@ -523,7 +519,7 @@ pub mod bytepipes { writer: W } - pub impl ReaderBytePort: BytePort { + pub impl BytePort for ReaderBytePort { fn try_recv(&self, count: uint) -> Option<~[u8]> { let mut left = count; let mut bytes = ~[]; @@ -537,7 +533,7 @@ pub mod bytepipes { } if left == 0 { - return Some(move bytes); + return Some(bytes); } else { warn!("flatpipe: dropped %? broken bytes", left); return None; @@ -545,7 +541,7 @@ pub mod bytepipes { } } - pub impl WriterByteChan: ByteChan { + pub impl ByteChan for WriterByteChan { fn send(&self, val: ~[u8]) { self.writer.write(val); } @@ -554,7 +550,7 @@ pub mod bytepipes { pub impl ReaderBytePort { static fn new(r: R) -> ReaderBytePort { ReaderBytePort { - reader: move r + reader: r } } } @@ -562,7 +558,7 @@ pub mod bytepipes { pub impl WriterByteChan { static fn new(w: W) -> WriterByteChan { WriterByteChan { - writer: move w + writer: w } } } @@ -576,7 +572,7 @@ pub mod bytepipes { chan: pipes::Chan<~[u8]> } - pub impl PipeBytePort: BytePort { + pub impl BytePort for PipeBytePort { fn try_recv(&self, count: uint) -> Option<~[u8]> { if self.buf.len() >= count { let mut bytes = ::core::util::replace(&mut self.buf, ~[]); @@ -587,17 +583,17 @@ pub mod bytepipes { let mut bytes = ::core::util::replace(&mut self.buf, ~[]); assert count > bytes.len(); match self.try_recv(count - bytes.len()) { - Some(move rest) => { + Some(rest) => { bytes.push_all(rest); - return Some(move bytes); + return Some(bytes); } None => return None } } else if self.buf.is_empty() { match self.port.try_recv() { - Some(move buf) => { + Some(buf) => { assert !buf.is_empty(); - self.buf = move buf; + self.buf = buf; return self.try_recv(count); } None => return None @@ -608,16 +604,16 @@ pub mod bytepipes { } } - pub impl PipeByteChan: ByteChan { + pub impl ByteChan for PipeByteChan { fn send(&self, val: ~[u8]) { - self.chan.send(move val) + self.chan.send(val) } } pub impl PipeBytePort { static fn new(p: Port<~[u8]>) -> PipeBytePort { PipeBytePort { - port: move p, + port: p, buf: ~[] } } @@ -626,7 +622,7 @@ pub mod bytepipes { pub impl PipeByteChan { static fn new(c: Chan<~[u8]>) -> PipeByteChan { PipeByteChan { - chan: move c + chan: c } } } @@ -661,14 +657,14 @@ mod test { #[test] fn test_serializing_memory_stream() { let writer = BytesWriter(); - let chan = serial::writer_chan(move writer); + let chan = serial::writer_chan(writer); chan.send(10); let bytes = chan.byte_chan.writer.bytes.get(); - let reader = BufReader::new(move bytes); - let port = serial::reader_port(move reader); + let reader = BufReader::new(bytes); + let port = serial::reader_port(reader); let res: int = port.recv(); assert res == 10i; @@ -678,7 +674,7 @@ mod test { fn test_serializing_pipes() { let (port, chan) = serial::pipe_stream(); - do task::spawn |move chan| { + do task::spawn || { for int::range(0, 10) |i| { chan.send(i) } @@ -693,7 +689,7 @@ mod test { fn test_serializing_boxes() { let (port, chan) = serial::pipe_stream(); - do task::spawn |move chan| { + do task::spawn || { for int::range(0, 10) |i| { chan.send(@i) } @@ -707,14 +703,14 @@ mod test { #[test] fn test_pod_memory_stream() { let writer = BytesWriter(); - let chan = pod::writer_chan(move writer); + let chan = pod::writer_chan(writer); chan.send(10); let bytes = chan.byte_chan.writer.bytes.get(); - let reader = BufReader::new(move bytes); - let port = pod::reader_port(move reader); + let reader = BufReader::new(bytes); + let port = pod::reader_port(reader); let res: int = port.recv(); assert res == 10; @@ -724,7 +720,7 @@ mod test { fn test_pod_pipes() { let (port, chan) = pod::pipe_stream(); - do task::spawn |move chan| { + do task::spawn || { for int::range(0, 10) |i| { chan.send(i) } @@ -741,11 +737,11 @@ mod test { fn test_pod_tcp_stream() { fn reader_port(buf: TcpSocketBuf ) -> pod::ReaderPort { - pod::reader_port(move buf) + pod::reader_port(buf) } fn writer_chan(buf: TcpSocketBuf ) -> pod::WriterChan { - pod::writer_chan(move buf) + pod::writer_chan(buf) } test_some_tcp_stream(reader_port, writer_chan, 9666); } @@ -755,11 +751,11 @@ mod test { fn test_serializing_tcp_stream() { fn reader_port(buf: TcpSocketBuf ) -> serial::ReaderPort { - serial::reader_port(move buf) + serial::reader_port(buf) } fn writer_chan(buf: TcpSocketBuf ) -> serial::WriterChan { - serial::writer_chan(move buf) + serial::writer_chan(buf) } test_some_tcp_stream(reader_port, writer_chan, 9667); } @@ -790,27 +786,25 @@ mod test { let addr0 = ip::v4::parse_addr("127.0.0.1"); - let begin_connect_chan = Cell(move begin_connect_chan); - let accept_chan = Cell(move accept_chan); + let begin_connect_chan = Cell(begin_connect_chan); + let accept_chan = Cell(accept_chan); // The server task let addr = copy addr0; - do task::spawn |move begin_connect_chan, - move accept_chan| { + do task::spawn || { let iotask = &uv::global_loop::get(); let begin_connect_chan = begin_connect_chan.take(); let accept_chan = accept_chan.take(); let listen_res = do tcp::listen( - copy addr, port, 128, iotask, - |move begin_connect_chan, _kill_ch| { + copy addr, port, 128, iotask, |_kill_ch| { // Tell the sender to initiate the connection debug!("listening"); begin_connect_chan.send(()) - }) |move accept_chan, new_conn, kill_ch| { + }) |new_conn, kill_ch| { // Incoming connection. Send it to the receiver task to accept let (res_port, res_chan) = pipes::stream(); - accept_chan.send((move new_conn, move res_chan)); + accept_chan.send((new_conn, res_chan)); // Wait until the connection is accepted res_port.recv(); @@ -823,8 +817,7 @@ mod test { // Client task let addr = copy addr0; - do task::spawn |move begin_connect_port, - move writer_chan| { + do task::spawn || { // Wait for the server to start listening begin_connect_port.recv(); @@ -833,11 +826,11 @@ mod test { let iotask = &uv::global_loop::get(); let connect_result = tcp::connect(copy addr, port, iotask); assert connect_result.is_ok(); - let sock = result::unwrap(move connect_result); - let socket_buf: tcp::TcpSocketBuf = tcp::socket_buf(move sock); + let sock = result::unwrap(connect_result); + let socket_buf: tcp::TcpSocketBuf = tcp::socket_buf(sock); // TcpSocketBuf is a Writer! - let chan = writer_chan(move socket_buf); + let chan = writer_chan(socket_buf); for int::range(0, 10) |i| { debug!("sending %?", i); @@ -846,9 +839,7 @@ mod test { } // Reciever task - do task::spawn |move accept_port, move finish_chan, - move reader_port| { - + do task::spawn || { // Wait for a connection let (conn, res_chan) = accept_port.recv(); @@ -856,13 +847,13 @@ mod test { let accept_result = tcp::accept(conn); debug!("accepted"); assert accept_result.is_ok(); - let sock = result::unwrap(move accept_result); + let sock = result::unwrap(accept_result); res_chan.send(()); - let socket_buf: tcp::TcpSocketBuf = tcp::socket_buf(move sock); + let socket_buf: tcp::TcpSocketBuf = tcp::socket_buf(sock); // TcpSocketBuf is a Reader! - let port = reader_port(move socket_buf); + let port = reader_port(socket_buf); for int::range(0, 10) |i| { let j = port.recv(); @@ -897,22 +888,22 @@ mod test { fn reader_port_loader(bytes: ~[u8] ) -> pod::ReaderPort { - let reader = BufReader::new(move bytes); - pod::reader_port(move reader) + let reader = BufReader::new(bytes); + pod::reader_port(reader) } fn pipe_port_loader(bytes: ~[u8] ) -> pod::PipePort { let (port, chan) = pipes::stream(); if !bytes.is_empty() { - chan.send(move bytes); + chan.send(bytes); } - pod::pipe_port(move port) + pod::pipe_port(port) } fn test_try_recv_none1(loader: PortLoader

) { let bytes = ~[]; - let port = loader(move bytes); + let port = loader(bytes); let res: Option = port.try_recv(); assert res.is_none(); } @@ -929,7 +920,7 @@ mod test { fn test_try_recv_none2(loader: PortLoader

) { // The control word in the protocol is interrupted let bytes = ~[0]; - let port = loader(move bytes); + let port = loader(bytes); let res: Option = port.try_recv(); assert res.is_none(); } @@ -947,7 +938,7 @@ mod test { const CONTINUE: [u8 * 4] = [0xAA, 0xBB, 0xCC, 0xDD]; // The control word is followed by garbage let bytes = CONTINUE.to_vec() + ~[0]; - let port = loader(move bytes); + let port = loader(bytes); let res: Option = port.try_recv(); assert res.is_none(); } @@ -962,7 +953,7 @@ mod test { } fn test_try_recv_none4(+loader: PortLoader

) { - assert do task::try |move loader| { + assert do task::try || { const CONTINUE: [u8 * 4] = [0xAA, 0xBB, 0xCC, 0xDD]; // The control word is followed by a valid length, // then undeserializable garbage @@ -972,7 +963,7 @@ mod test { }; let bytes = CONTINUE.to_vec() + len_bytes + ~[0, 0, 0, 0]; - let port = loader(move bytes); + let port = loader(bytes); let _res: Option = port.try_recv(); }.is_err(); diff --git a/src/libstd/fun_treemap.rs b/src/libstd/fun_treemap.rs index d6c2cf5a265ee..8af2f350e51f7 100644 --- a/src/libstd/fun_treemap.rs +++ b/src/libstd/fun_treemap.rs @@ -55,7 +55,7 @@ pub fn find(m: Treemap, k: K) -> Option { Node(@ref kk, @copy v, left, right) => { if k == *kk { Some(v) - } else if k < *kk { find(left, move k) } else { find(right, move k) } + } else if k < *kk { find(left, k) } else { find(right, k) } } } } diff --git a/src/libstd/future.rs b/src/libstd/future.rs index 8659e3cbb102c..ff81393a914db 100644 --- a/src/libstd/future.rs +++ b/src/libstd/future.rs @@ -71,10 +71,10 @@ impl Future { let mut state = Evaluating; self.state <-> state; - match move state { + match state { Forced(_) | Evaluating => fail!(~"Logic error."), - Pending(move f) => { - self.state = Forced(move f()); + Pending(f) => { + self.state = Forced(f()); self.get_ref() } } @@ -90,7 +90,7 @@ pub fn from_value(val: A) -> Future { * not block. */ - Future {state: Forced(move val)} + Future {state: Forced(val)} } pub fn from_port(port: PortOne) -> @@ -102,13 +102,13 @@ pub fn from_port(port: PortOne) -> * waiting for the result to be received on the port. */ - let port = ~mut Some(move port); - do from_fn |move port| { + let port = ~mut Some(port); + do from_fn || { let mut port_ = None; port_ <-> *port; - let port = option::unwrap(move port_); - match recv(move port) { - oneshot::send(move data) => move data + let port = option::unwrap(port_); + match recv(port) { + oneshot::send(data) => data } } } @@ -122,7 +122,7 @@ pub fn from_fn(f: ~fn() -> A) -> Future { * function. It is not spawned into another task. */ - Future {state: Pending(move f)} + Future {state: Pending(f)} } pub fn spawn(blk: fn~() -> A) -> Future { @@ -135,13 +135,13 @@ pub fn spawn(blk: fn~() -> A) -> Future { let (chan, port) = oneshot::init(); - let chan = ~mut Some(move chan); - do task::spawn |move blk, move chan| { + let chan = ~mut Some(chan); + do task::spawn || { let chan = option::swap_unwrap(&mut *chan); - send_one(move chan, blk()); + send_one(chan, blk()); } - return from_port(move port); + return from_port(port); } #[allow(non_implicitly_copyable_typarams)] @@ -162,8 +162,8 @@ pub mod test { #[test] pub fn test_from_port() { let (ch, po) = oneshot::init(); - send_one(move ch, ~"whale"); - let f = from_port(move po); + send_one(ch, ~"whale"); + let f = from_port(po); assert f.get() == ~"whale"; } @@ -202,8 +202,8 @@ pub mod test { #[test] pub fn test_sendable_future() { let expected = ~"schlorf"; - let f = do spawn |copy expected| { copy expected }; - do task::spawn |move f, move expected| { + let f = do spawn { copy expected }; + do task::spawn || { let actual = f.get(); assert actual == expected; } diff --git a/src/libstd/getopts.rs b/src/libstd/getopts.rs index 3d6d0b1bb7d6b..3726943321c35 100644 --- a/src/libstd/getopts.rs +++ b/src/libstd/getopts.rs @@ -35,7 +35,7 @@ * fn do_work(in: &str, out: Option<~str>) { * io::println(in); * io::println(match out { - * Some(move x) => x, + * Some(x) => x, * None => ~"No Output" * }); * } @@ -339,7 +339,7 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result { i += 1; } return Ok(Matches {opts: vec::from_slice(opts), - vals: move vals, + vals: vals, free: free}); } } @@ -1178,7 +1178,7 @@ mod tests { let args = ~[~"-e", ~"foo", ~"--encrypt", ~"foo"]; let opts = ~[optopt(~"e"), optopt(~"encrypt")]; let matches = &match getopts(args, opts) { - result::Ok(move m) => m, + result::Ok(m) => m, result::Err(_) => fail!() }; assert opts_present(matches, ~[~"e"]); @@ -1199,7 +1199,7 @@ mod tests { let args = ~[~"-Lfoo", ~"-M."]; let opts = ~[optmulti(~"L"), optmulti(~"M")]; let matches = &match getopts(args, opts) { - result::Ok(move m) => m, + result::Ok(m) => m, result::Err(_) => fail!() }; assert opts_present(matches, ~[~"L"]); diff --git a/src/libstd/io_util.rs b/src/libstd/io_util.rs index 3cc28563e12eb..b1c6e2d44e572 100644 --- a/src/libstd/io_util.rs +++ b/src/libstd/io_util.rs @@ -20,7 +20,7 @@ pub struct BufReader { pub impl BufReader { static pub fn new(v: ~[u8]) -> BufReader { BufReader { - buf: move v, + buf: v, pos: 0 } } @@ -38,7 +38,7 @@ pub impl BufReader { // FIXME #4429: This isn't correct if f fails self.pos = bytes_reader.pos; - return move res; + return res; } } diff --git a/src/libstd/json.rs b/src/libstd/json.rs index fcdd2de5743a3..e8278bb1b3563 100644 --- a/src/libstd/json.rs +++ b/src/libstd/json.rs @@ -82,7 +82,7 @@ pub fn Encoder(wr: io::Writer) -> Encoder { Encoder { wr: wr } } -pub impl Encoder: serialize::Encoder { +pub impl serialize::Encoder for Encoder { fn emit_nil(&self) { self.wr.write_str("null") } fn emit_uint(&self, v: uint) { self.emit_float(v as float); } @@ -217,7 +217,7 @@ pub fn PrettyEncoder(wr: io::Writer) -> PrettyEncoder { PrettyEncoder { wr: wr, indent: 0 } } -pub impl PrettyEncoder: serialize::Encoder { +pub impl serialize::Encoder for PrettyEncoder { fn emit_nil(&self) { self.wr.write_str("null") } fn emit_uint(&self, v: uint) { self.emit_float(v as float); } @@ -323,7 +323,7 @@ pub impl PrettyEncoder: serialize::Encoder { } } -pub impl Json: serialize::Encodable { +pub impl serialize::Encodable for Json { fn encode(&self, s: &S) { match *self { Number(v) => v.encode(s), @@ -388,18 +388,18 @@ pub fn Parser(rdr: io::Reader) -> Parser { pub impl Parser { fn parse() -> Result { - match move self.parse_value() { - Ok(move value) => { + match self.parse_value() { + Ok(value) => { // Skip trailing whitespaces. self.parse_whitespace(); // Make sure there is no trailing characters. if self.eof() { - Ok(move value) + Ok(value) } else { self.error(~"trailing characters") } } - Err(move e) => Err(e) + Err(e) => Err(e) } } } @@ -438,9 +438,9 @@ priv impl Parser { 'f' => self.parse_ident(~"alse", Boolean(false)), '0' .. '9' | '-' => self.parse_number(), '"' => - match move self.parse_str() { - Ok(move s) => Ok(String(s)), - Err(move e) => Err(e), + match self.parse_str() { + Ok(s) => Ok(String(s)), + Err(e) => Err(e), }, '[' => self.parse_list(), '{' => self.parse_object(), @@ -455,7 +455,7 @@ priv impl Parser { fn parse_ident(ident: &str, value: Json) -> Result { if str::all(ident, |c| c == self.next_char()) { self.bump(); - Ok(move value) + Ok(value) } else { self.error(~"invalid syntax") } @@ -662,13 +662,13 @@ priv impl Parser { if self.ch == ']' { self.bump(); - return Ok(List(move values)); + return Ok(List(values)); } loop { - match move self.parse_value() { - Ok(move v) => values.push(move v), - Err(move e) => return Err(e) + match self.parse_value() { + Ok(v) => values.push(v), + Err(e) => return Err(e) } self.parse_whitespace(); @@ -678,7 +678,7 @@ priv impl Parser { match self.ch { ',' => self.bump(), - ']' => { self.bump(); return Ok(List(move values)); } + ']' => { self.bump(); return Ok(List(values)); } _ => return self.error(~"expected `,` or `]`") } }; @@ -692,7 +692,7 @@ priv impl Parser { if self.ch == '}' { self.bump(); - return Ok(Object(move values)); + return Ok(Object(values)); } while !self.eof() { @@ -702,9 +702,9 @@ priv impl Parser { return self.error(~"key must be a string"); } - let key = match move self.parse_str() { - Ok(move key) => key, - Err(move e) => return Err(e) + let key = match self.parse_str() { + Ok(key) => key, + Err(e) => return Err(e) }; self.parse_whitespace(); @@ -715,15 +715,15 @@ priv impl Parser { } self.bump(); - match move self.parse_value() { - Ok(move value) => { values.insert(key, move value); } - Err(move e) => return Err(e) + match self.parse_value() { + Ok(value) => { values.insert(key, value); } + Err(e) => return Err(e) } self.parse_whitespace(); match self.ch { ',' => self.bump(), - '}' => { self.bump(); return Ok(Object(move values)); } + '}' => { self.bump(); return Ok(Object(values)); } _ => { if self.eof() { break; } return self.error(~"expected `,` or `}`"); @@ -753,7 +753,7 @@ pub struct Decoder { } pub fn Decoder(json: Json) -> Decoder { - Decoder { json: move json, stack: ~[] } + Decoder { json: json, stack: ~[] } } priv impl Decoder { @@ -768,7 +768,7 @@ priv impl Decoder { } } -pub impl Decoder: serialize::Decoder { +pub impl serialize::Decoder for Decoder { fn read_nil(&self) -> () { debug!("read_nil"); match *self.pop() { @@ -868,7 +868,7 @@ pub impl Decoder: serialize::Decoder { }; let res = f(len); self.pop(); - move res + res } fn read_managed_vec(&self, f: fn(uint) -> T) -> T { @@ -879,7 +879,7 @@ pub impl Decoder: serialize::Decoder { }; let res = f(len); self.pop(); - move res + res } fn read_vec_elt(&self, idx: uint, f: fn() -> T) -> T { @@ -897,14 +897,14 @@ pub impl Decoder: serialize::Decoder { debug!("read_rec()"); let value = f(); self.pop(); - move value + value } fn read_struct(&self, _name: &str, _len: uint, f: fn() -> T) -> T { debug!("read_struct()"); let value = f(); self.pop(); - move value + value } fn read_field(&self, name: &str, idx: uint, f: fn() -> T) -> T { @@ -934,7 +934,7 @@ pub impl Decoder: serialize::Decoder { debug!("read_tup(len=%u)", len); let value = f(); self.pop(); - move value + value } fn read_tup_elt(&self, idx: uint, f: fn() -> T) -> T { @@ -1219,11 +1219,11 @@ mod tests { for items.each |item| { match *item { - (copy key, copy value) => { d.insert(key, move value); }, + (copy key, copy value) => { d.insert(key, value); }, } }; - Object(move d) + Object(d) } #[test] @@ -1284,13 +1284,13 @@ mod tests { // Should they be in their own crate? pub pure fn check_equal_ptr (given : &T, expected: &T) { if !((given == expected) && (expected == given )) { - die!(fmt!("given %?, expected %?",given,expected)); + fail!(fmt!("given %?, expected %?",given,expected)); } } pub pure fn check_equal (given : T, expected: T) { if !((given == expected) && (expected == given )) { - die!(fmt!("given %?, expected %?",given,expected)); + fail!(fmt!("given %?, expected %?",given,expected)); } } @@ -1298,7 +1298,7 @@ mod tests { // and json... not sure where to put these tests. #[test] fn test_write_enum () { - let bw = @io::BytesWriter {bytes: dvec::DVec(), pos: 0}; + let bw = @io::BytesWriter(); let bww : @io::Writer = (bw as @io::Writer); let encoder = (@Encoder(bww) as @serialize::Encoder); do encoder.emit_enum(~"animal") { @@ -1319,7 +1319,7 @@ mod tests { #[test] fn test_write_some () { - let bw = @io::BytesWriter {bytes: dvec::DVec(), pos: 0}; + let bw = @io::BytesWriter(); let bww : @io::Writer = (bw as @io::Writer); let encoder = (@Encoder(bww) as @serialize::Encoder); do encoder.emit_enum(~"Option") { @@ -1335,7 +1335,7 @@ mod tests { #[test] fn test_write_none () { - let bw = @io::BytesWriter {bytes: dvec::DVec(), pos: 0}; + let bw = @io::BytesWriter(); let bww : @io::Writer = (bw as @io::Writer); let encoder = (@Encoder(bww) as @serialize::Encoder); do encoder.emit_enum(~"Option") { diff --git a/src/libstd/net_ip.rs b/src/libstd/net_ip.rs index 88bacf53e636b..4a185f68e17f9 100644 --- a/src/libstd/net_ip.rs +++ b/src/libstd/net_ip.rs @@ -181,7 +181,7 @@ pub mod v4 { */ pub fn parse_addr(ip: &str) -> IpAddr { match try_parse_addr(ip) { - result::Ok(move addr) => move addr, + result::Ok(addr) => addr, result::Err(ref err_data) => fail!(err_data.err_msg) } } @@ -276,7 +276,7 @@ pub mod v6 { */ pub fn parse_addr(ip: &str) -> IpAddr { match try_parse_addr(ip) { - result::Ok(move addr) => move addr, + result::Ok(addr) => addr, result::Err(copy err_data) => fail!(err_data.err_msg) } } @@ -331,7 +331,7 @@ extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int, result::Err(GetAddrUnknownError)); break; }; - out_vec.push(move new_ip_addr); + out_vec.push(new_ip_addr); let next_addr = ll::get_next_addrinfo(curr_addr); if next_addr == ptr::null::() as *addrinfo { @@ -345,7 +345,7 @@ extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int, } log(debug, fmt!("successful process addrinfo result, len: %?", vec::len(out_vec))); - output_ch.send(result::Ok(move out_vec)); + output_ch.send(result::Ok(out_vec)); } else { log(debug, ~"addrinfo pointer is NULL"); @@ -427,7 +427,7 @@ mod test { } // note really sure how to realiably test/assert // this.. mostly just wanting to see it work, atm. - let results = result::unwrap(move ga_result); + let results = result::unwrap(ga_result); log(debug, fmt!("test_get_addr: Number of results for %s: %?", localhost_name, vec::len(results))); for vec::each(results) |r| { diff --git a/src/libstd/net_tcp.rs b/src/libstd/net_tcp.rs index 4e0b5494883b0..563bc1c203ae4 100644 --- a/src/libstd/net_tcp.rs +++ b/src/libstd/net_tcp.rs @@ -177,7 +177,7 @@ pub fn connect(input_ip: ip::IpAddr, port: uint, // we can send into the interact cb to be handled in libuv.. debug!("stream_handle_ptr outside interact %?", stream_handle_ptr); - do iotask::interact(iotask) |move input_ip, loop_ptr| { + do iotask::interact(iotask) |loop_ptr| { unsafe { debug!("in interact cb for tcp client connect.."); debug!("stream_handle_ptr in interact %?", @@ -629,10 +629,10 @@ pub fn listen(host_ip: ip::IpAddr, port: uint, backlog: uint, new_connect_cb: fn~(TcpNewConnection, SharedChan>)) -> result::Result<(), TcpListenErrData> { - do listen_common(move host_ip, port, backlog, iotask, - move on_establish_cb) + do listen_common(host_ip, port, backlog, iotask, + on_establish_cb) // on_connect_cb - |move new_connect_cb, handle| { + |handle| { unsafe { let server_data_ptr = uv::ll::get_data_for_uv_handle(handle) as *TcpListenFcData; @@ -659,7 +659,7 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint, server_stream_ptr: server_stream_ptr, stream_closed_ch: stream_closed_ch, kill_ch: kill_ch.clone(), - on_connect_cb: move on_connect_cb, + on_connect_cb: on_connect_cb, iotask: iotask.clone(), ipv6: match &host_ip { &ip::Ipv4(_) => { false } @@ -678,7 +678,7 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint, // tcp::connect (because the iotask::interact cb isn't // nested within a core::comm::listen block) let loc_ip = copy(host_ip); - do iotask::interact(iotask) |move loc_ip, loop_ptr| { + do iotask::interact(iotask) |loop_ptr| { unsafe { match uv::ll::tcp_init(loop_ptr, server_stream_ptr) { 0i32 => { @@ -815,7 +815,7 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint, */ pub fn socket_buf(sock: TcpSocket) -> TcpSocketBuf { TcpSocketBuf(@TcpBufferedSocketData { - sock: move sock, mut buf: ~[], buf_off: 0 + sock: sock, mut buf: ~[], buf_off: 0 }) } @@ -851,12 +851,12 @@ impl TcpSocket { let addr = uv::ll::ip6_addr("", 0); uv::ll::tcp_getpeername6(self.socket_data.stream_handle_ptr, ptr::addr_of(&addr)); - ip::Ipv6(move addr) + ip::Ipv6(addr) } else { let addr = uv::ll::ip4_addr("", 0); uv::ll::tcp_getpeername(self.socket_data.stream_handle_ptr, ptr::addr_of(&addr)); - ip::Ipv4(move addr) + ip::Ipv4(addr) } } } @@ -971,7 +971,8 @@ impl io::Writer for TcpSocketBuf { let w_result = write_common_impl(socket_data_ptr, vec::slice(data, 0, - vec::len(data))); + vec::len(data) + ).to_vec()); if w_result.is_err() { let err_data = w_result.get_err(); log(debug, @@ -1047,7 +1048,7 @@ fn read_common_impl(socket_data: *TcpSocketData, timeout_msecs: uint) Some(result::get(&rs_result).recv()) }; log(debug, ~"tcp::read after recv_timeout"); - match move read_result { + match read_result { None => { log(debug, ~"tcp::read: timed out.."); let err_data = TcpErrData { @@ -1057,7 +1058,7 @@ fn read_common_impl(socket_data: *TcpSocketData, timeout_msecs: uint) read_stop_common_impl(socket_data); result::Err(err_data) } - Some(move data_result) => { + Some(data_result) => { log(debug, ~"tcp::read got data"); read_stop_common_impl(socket_data); data_result @@ -1091,7 +1092,7 @@ fn read_stop_common_impl(socket_data: *TcpSocketData) -> } } match stop_po.recv() { - Some(move err_data) => Err(err_data), + Some(err_data) => Err(err_data), None => Ok(()) } } @@ -1183,7 +1184,7 @@ fn write_common_impl(socket_data_ptr: *TcpSocketData, // aftermath, so we don't have to sit here blocking. match result_po.recv() { TcpWriteSuccess => Ok(()), - TcpWriteError(move err_data) => Err(err_data) + TcpWriteError(err_data) => Err(err_data) } } } @@ -1613,10 +1614,10 @@ pub mod test { debug!("server started, firing up client.."); let server_ip_addr = ip::v4::parse_addr(server_ip); let iotask = uv::global_loop::get(); - let connect_result = connect(move server_ip_addr, server_port, + let connect_result = connect(server_ip_addr, server_port, &iotask); - let sock = result::unwrap(move connect_result); + let sock = result::unwrap(connect_result); debug!("testing peer address"); // This is what we are actually testing! @@ -1784,11 +1785,11 @@ pub mod test { // client debug!("server started, firing up client.."); let server_addr = ip::v4::parse_addr(server_ip); - let conn_result = connect(move server_addr, server_port, hl_loop); + let conn_result = connect(server_addr, server_port, hl_loop); if result::is_err(&conn_result) { assert false; } - let sock_buf = @socket_buf(result::unwrap(move conn_result)); + let sock_buf = @socket_buf(result::unwrap(conn_result)); buf_write(sock_buf, expected_req); let buf_reader = sock_buf as Reader; @@ -1819,7 +1820,7 @@ pub mod test { let (server_po, server_ch) = stream::<~str>(); let server_ch = SharedChan(server_ch); let server_ip_addr = ip::v4::parse_addr(server_ip); - let listen_result = listen(move server_ip_addr, server_port, 128, + let listen_result = listen(server_ip_addr, server_port, 128, iotask, // on_establish_cb -- called when listener is set up |kill_ch| { @@ -1849,15 +1850,15 @@ pub mod test { else { debug!("SERVER/WORKER: send on cont ch"); cont_ch.send(()); - let sock = result::unwrap(move accept_result); + let sock = result::unwrap(accept_result); let peer_addr = sock.get_peer_addr(); debug!("SERVER: successfully accepted \ connection from %s:%u", ip::format_addr(&peer_addr), ip::get_port(&peer_addr)); let received_req_bytes = read(&sock, 0u); - match move received_req_bytes { - result::Ok(move data) => { + match received_req_bytes { + result::Ok(data) => { debug!("SERVER: got REQ str::from_bytes.."); debug!("SERVER: REQ data len: %?", vec::len(data)); @@ -1868,7 +1869,7 @@ pub mod test { debug!("SERVER: after write.. die"); kill_ch.send(None); } - result::Err(move err_data) => { + result::Err(err_data) => { debug!("SERVER: error recvd: %s %s", err_data.err_name, err_data.err_msg); kill_ch.send(Some(err_data)); @@ -1904,7 +1905,7 @@ pub mod test { fn run_tcp_test_server_fail(server_ip: &str, server_port: uint, iotask: &IoTask) -> TcpListenErrData { let server_ip_addr = ip::v4::parse_addr(server_ip); - let listen_result = listen(move server_ip_addr, server_port, 128, + let listen_result = listen(server_ip_addr, server_port, 128, iotask, // on_establish_cb -- called when listener is set up |kill_ch| { @@ -1929,7 +1930,7 @@ pub mod test { let server_ip_addr = ip::v4::parse_addr(server_ip); debug!("CLIENT: starting.."); - let connect_result = connect(move server_ip_addr, server_port, + let connect_result = connect(server_ip_addr, server_port, iotask); if result::is_err(&connect_result) { debug!("CLIENT: failed to connect"); @@ -1937,7 +1938,7 @@ pub mod test { Err(err_data) } else { - let sock = result::unwrap(move connect_result); + let sock = result::unwrap(connect_result); let resp_bytes = str::to_bytes(resp); tcp_write_single(&sock, resp_bytes); let read_result = sock.read(0u); diff --git a/src/libstd/net_url.rs b/src/libstd/net_url.rs index 7874899cb27ac..29cb57c01be45 100644 --- a/src/libstd/net_url.rs +++ b/src/libstd/net_url.rs @@ -253,7 +253,7 @@ pub fn decode_form_urlencoded(s: &[u8]) -> LinearMap<~str, ~[~str]> { '&' | ';' => { if key != ~"" && value != ~"" { let mut values = match m.pop(&key) { - Some(move values) => values, + Some(values) => values, None => ~[], }; @@ -287,7 +287,7 @@ pub fn decode_form_urlencoded(s: &[u8]) -> LinearMap<~str, ~[~str]> { if key != ~"" && value != ~"" { let mut values = match m.pop(&key) { - Some(move values) => values, + Some(values) => values, None => ~[], }; @@ -671,7 +671,7 @@ pub pure fn from_str(rawurl: &str) -> Result { impl FromStr for Url { static pure fn from_str(s: &str) -> Option { match from_str(s) { - Ok(move url) => Some(url), + Ok(url) => Some(url), Err(_) => None } } diff --git a/src/libstd/oldmap.rs b/src/libstd/oldmap.rs index 3ad45cf2d5b30..701268e044ae3 100644 --- a/src/libstd/oldmap.rs +++ b/src/libstd/oldmap.rs @@ -132,7 +132,7 @@ pub mod chained { entry.next = new_chains[idx]; new_chains[idx] = Some(entry); } - self.chains = move new_chains; + self.chains = new_chains; } pure fn each_entry(blk: fn(@Entry) -> bool) { @@ -321,7 +321,7 @@ pub mod chained { if opt_v.is_none() { fail!(fmt!("Key not found in table: %?", k)); } - option::unwrap(move opt_v) + option::unwrap(opt_v) } } diff --git a/src/libstd/oldsmallintmap.rs b/src/libstd/oldsmallintmap.rs index 5c3477660706e..c4ba465acea94 100644 --- a/src/libstd/oldsmallintmap.rs +++ b/src/libstd/oldsmallintmap.rs @@ -69,7 +69,7 @@ pub pure fn get(self: SmallIntMap, key: uint) -> T { error!("smallintmap::get(): key not present"); fail!(); } - Some(move v) => return v + Some(v) => return v } } diff --git a/src/libstd/par.rs b/src/libstd/par.rs index 8293ff1c2afdf..c48f56dd143bb 100644 --- a/src/libstd/par.rs +++ b/src/libstd/par.rs @@ -58,7 +58,7 @@ fn map_slices( do vec::as_imm_buf(xs) |p, _len| { let f = f(); let base = base; - let f = do future_spawn() |move f| { + let f = do future_spawn() || { unsafe { let len = end - base; let slice = (ptr::offset(p, base), @@ -72,7 +72,7 @@ fn map_slices( f(base, slice) } }; - futures.push(move f); + futures.push(f); }; base += items_per_task; } @@ -107,7 +107,7 @@ pub fn mapi( { let slices = map_slices(xs, || { let f = fn_factory(); - fn~(base: uint, slice : &[A], copy f) -> ~[B] { + fn~(base: uint, slice : &[A]) -> ~[B] { vec::mapi(slice, |i, x| { f(i + base, x) }) @@ -126,7 +126,7 @@ pub fn alli( { do vec::all(map_slices(xs, || { let f = fn_factory(); - fn~(base: uint, slice : &[A], copy f) -> bool { + fn~(base: uint, slice : &[A]) -> bool { vec::alli(slice, |i, x| { f(i + base, x) }) @@ -140,7 +140,7 @@ pub fn any( fn_factory: &fn() -> ~fn(&A) -> bool) -> bool { do vec::any(map_slices(xs, || { let f = fn_factory(); - fn~(_base : uint, slice: &[A], copy f) -> bool { + fn~(_base : uint, slice: &[A]) -> bool { vec::any(slice, |x| f(x)) } })) |x| { *x } diff --git a/src/libstd/prettyprint.rs b/src/libstd/prettyprint.rs index dc2e3d3da2bd4..cb9090225bf1c 100644 --- a/src/libstd/prettyprint.rs +++ b/src/libstd/prettyprint.rs @@ -22,7 +22,7 @@ pub fn Serializer(wr: io::Writer) -> Serializer { Serializer { wr: wr } } -pub impl Serializer: serialize::Encoder { +pub impl serialize::Encoder for Serializer { fn emit_nil(&self) { self.wr.write_str(~"()") } diff --git a/src/libstd/priority_queue.rs b/src/libstd/priority_queue.rs index a25a4196b4cab..b216834a20500 100644 --- a/src/libstd/priority_queue.rs +++ b/src/libstd/priority_queue.rs @@ -139,27 +139,27 @@ impl PriorityQueue { priv fn siftup(&mut self, start: uint, mut pos: uint) { unsafe { - let new = move *addr_of(&self.data[pos]); + let new = *addr_of(&self.data[pos]); while pos > start { let parent = (pos - 1) >> 1; if new > self.data[parent] { let mut x = rusti::init(); x <-> self.data[parent]; - rusti::move_val_init(&mut self.data[pos], move x); + rusti::move_val_init(&mut self.data[pos], x); pos = parent; loop } break } - rusti::move_val_init(&mut self.data[pos], move new); + rusti::move_val_init(&mut self.data[pos], new); } } priv fn siftdown_range(&mut self, mut pos: uint, end: uint) { unsafe { let start = pos; - let new = move *addr_of(&self.data[pos]); + let new = *addr_of(&self.data[pos]); let mut child = 2 * pos + 1; while child < end { @@ -169,12 +169,12 @@ impl PriorityQueue { } let mut x = rusti::init(); x <-> self.data[child]; - rusti::move_val_init(&mut self.data[pos], move x); + rusti::move_val_init(&mut self.data[pos], x); pos = child; child = 2 * pos + 1; } - rusti::move_val_init(&mut self.data[pos], move new); + rusti::move_val_init(&mut self.data[pos], new); self.siftup(start, pos); } } diff --git a/src/libstd/rl.rs b/src/libstd/rl.rs index 30baa3cc5f15a..1ee67d76af571 100644 --- a/src/libstd/rl.rs +++ b/src/libstd/rl.rs @@ -71,7 +71,7 @@ fn complete_key(_v: @CompletionCb) {} /// Bind to the main completion callback pub unsafe fn complete(cb: CompletionCb) { unsafe { - task::local_data::local_data_set(complete_key, @(move cb)); + task::local_data::local_data_set(complete_key, @(cb)); extern fn callback(line: *c_char, completions: *()) { unsafe { diff --git a/src/libstd/rope.rs b/src/libstd/rope.rs index 8ff90b940fb56..8e878c8fc2e31 100644 --- a/src/libstd/rope.rs +++ b/src/libstd/rope.rs @@ -848,11 +848,11 @@ pub mod node { offset += 1u; i += 1u; } - cast::forget(move local_buf); + cast::forget(local_buf); } } } - return cast::transmute(move buf); + return cast::transmute(buf); } } diff --git a/src/libstd/semver.rs b/src/libstd/semver.rs new file mode 100644 index 0000000000000..97c60330a7e31 --- /dev/null +++ b/src/libstd/semver.rs @@ -0,0 +1,395 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Semver parsing and logic + +use io; +use io::{ReaderUtil}; +use option::{Option, Some, None}; +use uint; +use str; +use to_str::ToStr; +use char; +use core::cmp; + +#[deriving_eq] +pub enum Identifier { + Numeric(uint), + AlphaNumeric(~str) +} + +impl cmp::Ord for Identifier { + #[inline(always)] + pure fn lt(&self, other: &Identifier) -> bool { + match (self, other) { + (&Numeric(a), &Numeric(b)) => a < b, + (&Numeric(_), _) => true, + (&AlphaNumeric(ref a), &AlphaNumeric(ref b)) => *a < *b, + (&AlphaNumeric(_), _) => false + } + } + #[inline(always)] + pure fn le(&self, other: &Identifier) -> bool { + ! (other < self) + } + #[inline(always)] + pure fn gt(&self, other: &Identifier) -> bool { + other < self + } + #[inline(always)] + pure fn ge(&self, other: &Identifier) -> bool { + ! (self < other) + } +} + +impl ToStr for Identifier { + #[inline(always)] + pure fn to_str(&self) -> ~str { + match self { + &Numeric(n) => n.to_str(), + &AlphaNumeric(ref s) => s.to_str() + } + } +} + + +#[deriving_eq] +pub struct Version { + major: uint, + minor: uint, + patch: uint, + pre: ~[Identifier], + build: ~[Identifier], +} + +impl ToStr for Version { + #[inline(always)] + pure fn to_str(&self) -> ~str { + let s = fmt!("%u.%u.%u", self.major, self.minor, self.patch); + let s = if self.pre.is_empty() { + s + } else { + s + "-" + str::connect(self.pre.map(|i| i.to_str()), ".") + }; + if self.build.is_empty() { + s + } else { + s + "+" + str::connect(self.build.map(|i| i.to_str()), ".") + } + } +} + +impl cmp::Ord for Version { + #[inline(always)] + pure fn lt(&self, other: &Version) -> bool { + + self.major < other.major || + + (self.major == other.major && + self.minor < other.minor) || + + (self.major == other.major && + self.minor == other.minor && + self.patch < other.patch) || + + (self.major == other.major && + self.minor == other.minor && + self.patch == other.patch && + // NB: semver spec says 0.0.0-pre < 0.0.0 + // but the version of ord defined for vec + // says that [] < [pre], so we alter it + // here. + (match (self.pre.len(), other.pre.len()) { + (0, 0) => false, + (0, _) => false, + (_, 0) => true, + (_, _) => self.pre < other.pre + })) || + + (self.major == other.major && + self.minor == other.minor && + self.patch == other.patch && + self.pre == other.pre && + self.build < other.build) + } + + #[inline(always)] + pure fn le(&self, other: &Version) -> bool { + ! (other < self) + } + #[inline(always)] + pure fn gt(&self, other: &Version) -> bool { + other < self + } + #[inline(always)] + pure fn ge(&self, other: &Version) -> bool { + ! (self < other) + } +} + +condition! { + bad_parse: () -> (); +} + +fn take_nonempty_prefix(rdr: io::Reader, + ch: char, + pred: fn(char) -> bool) -> (~str, char) { + let mut buf = ~""; + let mut ch = ch; + while pred(ch) { + str::push_char(&mut buf, ch); + ch = rdr.read_char(); + } + if buf.is_empty() { + bad_parse::cond.raise(()) + } + debug!("extracted nonempty prefix: %s", buf); + (buf, ch) +} + +fn take_num(rdr: io::Reader, ch: char) -> (uint, char) { + let (s, ch) = take_nonempty_prefix(rdr, ch, char::is_digit); + match uint::from_str(s) { + None => { bad_parse::cond.raise(()); (0, ch) }, + Some(i) => (i, ch) + } +} + +fn take_ident(rdr: io::Reader, ch: char) -> (Identifier, char) { + let (s,ch) = take_nonempty_prefix(rdr, ch, char::is_alphanumeric); + if s.all(char::is_digit) { + match uint::from_str(s) { + None => { bad_parse::cond.raise(()); (Numeric(0), ch) }, + Some(i) => (Numeric(i), ch) + } + } else { + (AlphaNumeric(s), ch) + } +} + +fn expect(ch: char, c: char) { + if ch != c { + bad_parse::cond.raise(()) + } +} + +fn parse_reader(rdr: io::Reader) -> Version { + + let (major, ch) = take_num(rdr, rdr.read_char()); + expect(ch, '.'); + let (minor, ch) = take_num(rdr, rdr.read_char()); + expect(ch, '.'); + let (patch, ch) = take_num(rdr, rdr.read_char()); + + let mut pre = ~[]; + let mut build = ~[]; + + let mut ch = ch; + if ch == '-' { + loop { + let (id, c) = take_ident(rdr, rdr.read_char()); + pre.push(id); + ch = c; + if ch != '.' { break; } + } + } + + if ch == '+' { + loop { + let (id, c) = take_ident(rdr, rdr.read_char()); + build.push(id); + ch = c; + if ch != '.' { break; } + } + } + + Version { + major: major, + minor: minor, + patch: patch, + pre: pre, + build: build, + } +} + + +pub fn parse(s: &str) -> Option { + if ! str::is_ascii(s) { + return None; + } + let s = s.trim(); + let mut bad = false; + do bad_parse::cond.trap(|_| { debug!("bad"); bad = true }).in { + do io::with_str_reader(s) |rdr| { + let v = parse_reader(rdr); + if bad || v.to_str() != s { + None + } else { + Some(v) + } + } + } +} + +#[test] +fn test_parse() { + assert parse("") == None; + assert parse(" ") == None; + assert parse("1") == None; + assert parse("1.2") == None; + assert parse("1.2") == None; + assert parse("1") == None; + assert parse("1.2") == None; + assert parse("1.2.3-") == None; + assert parse("a.b.c") == None; + assert parse("1.2.3 abc") == None; + + assert parse("1.2.3") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[], + build: ~[], + }); + assert parse(" 1.2.3 ") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[], + build: ~[], + }); + assert parse("1.2.3-alpha1") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[AlphaNumeric(~"alpha1")], + build: ~[] + }); + assert parse(" 1.2.3-alpha1 ") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[AlphaNumeric(~"alpha1")], + build: ~[] + }); + assert parse("1.2.3+build5") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[], + build: ~[AlphaNumeric(~"build5")] + }); + assert parse(" 1.2.3+build5 ") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[], + build: ~[AlphaNumeric(~"build5")] + }); + assert parse("1.2.3-alpha1+build5") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[AlphaNumeric(~"alpha1")], + build: ~[AlphaNumeric(~"build5")] + }); + assert parse(" 1.2.3-alpha1+build5 ") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[AlphaNumeric(~"alpha1")], + build: ~[AlphaNumeric(~"build5")] + }); + assert parse("1.2.3-1.alpha1.9+build5.7.3aedf ") == Some(Version { + major: 1u, + minor: 2u, + patch: 3u, + pre: ~[Numeric(1),AlphaNumeric(~"alpha1"),Numeric(9)], + build: ~[AlphaNumeric(~"build5"), + Numeric(7), + AlphaNumeric(~"3aedf")] + }); + +} + +#[test] +fn test_eq() { + assert parse("1.2.3") == parse("1.2.3"); + assert parse("1.2.3-alpha1") == parse("1.2.3-alpha1"); +} + +#[test] +fn test_ne() { + assert parse("0.0.0") != parse("0.0.1"); + assert parse("0.0.0") != parse("0.1.0"); + assert parse("0.0.0") != parse("1.0.0"); + assert parse("1.2.3-alpha") != parse("1.2.3-beta"); +} + +#[test] +fn test_lt() { + assert parse("0.0.0") < parse("1.2.3-alpha2"); + assert parse("1.0.0") < parse("1.2.3-alpha2"); + assert parse("1.2.0") < parse("1.2.3-alpha2"); + assert parse("1.2.3-alpha1") < parse("1.2.3"); + assert parse("1.2.3-alpha1") < parse("1.2.3-alpha2"); + assert !(parse("1.2.3-alpha2") < parse("1.2.3-alpha2")); +} + +#[test] +fn test_le() { + assert parse("0.0.0") <= parse("1.2.3-alpha2"); + assert parse("1.0.0") <= parse("1.2.3-alpha2"); + assert parse("1.2.0") <= parse("1.2.3-alpha2"); + assert parse("1.2.3-alpha1") <= parse("1.2.3-alpha2"); + assert parse("1.2.3-alpha2") <= parse("1.2.3-alpha2"); +} + +#[test] +fn test_gt() { + assert parse("1.2.3-alpha2") > parse("0.0.0"); + assert parse("1.2.3-alpha2") > parse("1.0.0"); + assert parse("1.2.3-alpha2") > parse("1.2.0"); + assert parse("1.2.3-alpha2") > parse("1.2.3-alpha1"); + assert parse("1.2.3") > parse("1.2.3-alpha2"); + assert !(parse("1.2.3-alpha2") > parse("1.2.3-alpha2")); +} + +#[test] +fn test_ge() { + assert parse("1.2.3-alpha2") >= parse("0.0.0"); + assert parse("1.2.3-alpha2") >= parse("1.0.0"); + assert parse("1.2.3-alpha2") >= parse("1.2.0"); + assert parse("1.2.3-alpha2") >= parse("1.2.3-alpha1"); + assert parse("1.2.3-alpha2") >= parse("1.2.3-alpha2"); +} + +#[test] +fn test_spec_order() { + + let vs = ["1.0.0-alpha", + "1.0.0-alpha.1", + "1.0.0-beta.2", + "1.0.0-beta.11", + "1.0.0-rc.1", + "1.0.0-rc.1+build.1", + "1.0.0", + "1.0.0+0.3.7", + "1.3.7+build", + "1.3.7+build.2.b8f12d7", + "1.3.7+build.11.e0f985a"]; + let mut i = 1; + while i < vs.len() { + let a = parse(vs[i-1]).get(); + let b = parse(vs[i]).get(); + assert a < b; + i += 1; + } +} \ No newline at end of file diff --git a/src/libstd/serialize.rs b/src/libstd/serialize.rs index d4afdbf6f3094..9b7cf8adce553 100644 --- a/src/libstd/serialize.rs +++ b/src/libstd/serialize.rs @@ -113,210 +113,210 @@ pub trait Decodable { static fn decode(&self, d: &D) -> Self; } -pub impl uint: Encodable { +pub impl Encodable for uint { fn encode(&self, s: &S) { s.emit_uint(*self) } } -pub impl uint: Decodable { +pub impl Decodable for uint { static fn decode(&self, d: &D) -> uint { d.read_uint() } } -pub impl u8: Encodable { +pub impl Encodable for u8 { fn encode(&self, s: &S) { s.emit_u8(*self) } } -pub impl u8: Decodable { +pub impl Decodable for u8 { static fn decode(&self, d: &D) -> u8 { d.read_u8() } } -pub impl u16: Encodable { +pub impl Encodable for u16 { fn encode(&self, s: &S) { s.emit_u16(*self) } } -pub impl u16: Decodable { +pub impl Decodable for u16 { static fn decode(&self, d: &D) -> u16 { d.read_u16() } } -pub impl u32: Encodable { +pub impl Encodable for u32 { fn encode(&self, s: &S) { s.emit_u32(*self) } } -pub impl u32: Decodable { +pub impl Decodable for u32 { static fn decode(&self, d: &D) -> u32 { d.read_u32() } } -pub impl u64: Encodable { +pub impl Encodable for u64 { fn encode(&self, s: &S) { s.emit_u64(*self) } } -pub impl u64: Decodable { +pub impl Decodable for u64 { static fn decode(&self, d: &D) -> u64 { d.read_u64() } } -pub impl int: Encodable { +pub impl Encodable for int { fn encode(&self, s: &S) { s.emit_int(*self) } } -pub impl int: Decodable { +pub impl Decodable for int { static fn decode(&self, d: &D) -> int { d.read_int() } } -pub impl i8: Encodable { +pub impl Encodable for i8 { fn encode(&self, s: &S) { s.emit_i8(*self) } } -pub impl i8: Decodable { +pub impl Decodable for i8 { static fn decode(&self, d: &D) -> i8 { d.read_i8() } } -pub impl i16: Encodable { +pub impl Encodable for i16 { fn encode(&self, s: &S) { s.emit_i16(*self) } } -pub impl i16: Decodable { +pub impl Decodable for i16 { static fn decode(&self, d: &D) -> i16 { d.read_i16() } } -pub impl i32: Encodable { +pub impl Encodable for i32 { fn encode(&self, s: &S) { s.emit_i32(*self) } } -pub impl i32: Decodable { +pub impl Decodable for i32 { static fn decode(&self, d: &D) -> i32 { d.read_i32() } } -pub impl i64: Encodable { +pub impl Encodable for i64 { fn encode(&self, s: &S) { s.emit_i64(*self) } } -pub impl i64: Decodable { +pub impl Decodable for i64 { static fn decode(&self, d: &D) -> i64 { d.read_i64() } } -pub impl &str: Encodable { +pub impl Encodable for &str { fn encode(&self, s: &S) { s.emit_borrowed_str(*self) } } -pub impl ~str: Encodable { +pub impl Encodable for ~str { fn encode(&self, s: &S) { s.emit_owned_str(*self) } } -pub impl ~str: Decodable { +pub impl Decodable for ~str { static fn decode(&self, d: &D) -> ~str { d.read_owned_str() } } -pub impl @str: Encodable { +pub impl Encodable for @str { fn encode(&self, s: &S) { s.emit_managed_str(*self) } } -pub impl @str: Decodable { +pub impl Decodable for @str { static fn decode(&self, d: &D) -> @str { d.read_managed_str() } } -pub impl float: Encodable { +pub impl Encodable for float { fn encode(&self, s: &S) { s.emit_float(*self) } } -pub impl float: Decodable { +pub impl Decodable for float { static fn decode(&self, d: &D) -> float { d.read_float() } } -pub impl f32: Encodable { +pub impl Encodable for f32 { fn encode(&self, s: &S) { s.emit_f32(*self) } } -pub impl f32: Decodable { +pub impl Decodable for f32 { static fn decode(&self, d: &D) -> f32 { d.read_f32() } } -pub impl f64: Encodable { +pub impl Encodable for f64 { fn encode(&self, s: &S) { s.emit_f64(*self) } } -pub impl f64: Decodable { +pub impl Decodable for f64 { static fn decode(&self, d: &D) -> f64 { d.read_f64() } } -pub impl bool: Encodable { +pub impl Encodable for bool { fn encode(&self, s: &S) { s.emit_bool(*self) } } -pub impl bool: Decodable { +pub impl Decodable for bool { static fn decode(&self, d: &D) -> bool { d.read_bool() } } -pub impl (): Encodable { +pub impl Encodable for () { fn encode(&self, s: &S) { s.emit_nil() } } -pub impl (): Decodable { +pub impl Decodable for () { static fn decode(&self, d: &D) -> () { d.read_nil() } } -pub impl> &T: Encodable { +pub impl> Encodable for &T { fn encode(&self, s: &S) { s.emit_borrowed(|| (**self).encode(s)) } } -pub impl> ~T: Encodable { +pub impl> Encodable for ~T { fn encode(&self, s: &S) { s.emit_owned(|| (**self).encode(s)) } } -pub impl> ~T: Decodable { +pub impl> Decodable for ~T { static fn decode(&self, d: &D) -> ~T { d.read_owned(|| ~Decodable::decode(d)) } } -pub impl> @T: Encodable { +pub impl> Encodable for @T { fn encode(&self, s: &S) { s.emit_managed(|| (**self).encode(s)) } } -pub impl> @T: Decodable { +pub impl> Decodable for @T { static fn decode(&self, d: &D) -> @T { d.read_managed(|| @Decodable::decode(d)) } } -pub impl> &[T]: Encodable { +pub impl> Encodable for &[T] { fn encode(&self, s: &S) { do s.emit_borrowed_vec(self.len()) { for self.eachi |i, e| { @@ -326,7 +326,7 @@ pub impl> &[T]: Encodable { } } -pub impl> ~[T]: Encodable { +pub impl> Encodable for ~[T] { fn encode(&self, s: &S) { do s.emit_owned_vec(self.len()) { for self.eachi |i, e| { @@ -336,7 +336,7 @@ pub impl> ~[T]: Encodable { } } -pub impl> ~[T]: Decodable { +pub impl> Decodable for ~[T] { static fn decode(&self, d: &D) -> ~[T] { do d.read_owned_vec |len| { do vec::from_fn(len) |i| { @@ -346,7 +346,7 @@ pub impl> ~[T]: Decodable { } } -pub impl> @[T]: Encodable { +pub impl> Encodable for @[T] { fn encode(&self, s: &S) { do s.emit_managed_vec(self.len()) { for self.eachi |i, e| { @@ -356,7 +356,7 @@ pub impl> @[T]: Encodable { } } -pub impl> @[T]: Decodable { +pub impl> Decodable for @[T] { static fn decode(&self, d: &D) -> @[T] { do d.read_managed_vec |len| { do at_vec::from_fn(len) |i| { @@ -366,7 +366,7 @@ pub impl> @[T]: Decodable { } } -pub impl> Option: Encodable { +pub impl> Encodable for Option { fn encode(&self, s: &S) { do s.emit_enum(~"option") { match *self { @@ -381,7 +381,7 @@ pub impl> Option: Encodable { } } -pub impl> Option: Decodable { +pub impl> Decodable for Option { static fn decode(&self, d: &D) -> Option { do d.read_enum(~"option") { do d.read_enum_variant |i| { @@ -396,11 +396,8 @@ pub impl> Option: Decodable { } } -pub impl< - S: Encoder, - T0: Encodable, - T1: Encodable -> (T0, T1): Encodable { +pub impl, T1: Encodable> Encodable + for (T0, T1) { fn encode(&self, s: &S) { match *self { (ref t0, ref t1) => { @@ -413,11 +410,8 @@ pub impl< } } -pub impl< - D: Decoder, - T0: Decodable, - T1: Decodable -> (T0, T1): Decodable { +pub impl, T1: Decodable> Decodable + for (T0, T1) { static fn decode(&self, d: &D) -> (T0, T1) { do d.read_tup(2) { ( @@ -433,7 +427,7 @@ pub impl< T0: Encodable, T1: Encodable, T2: Encodable -> (T0, T1, T2): Encodable { +> Encodable for (T0, T1, T2) { fn encode(&self, s: &S) { match *self { (ref t0, ref t1, ref t2) => { @@ -452,7 +446,7 @@ pub impl< T0: Decodable, T1: Decodable, T2: Decodable -> (T0, T1, T2): Decodable { +> Decodable for (T0, T1, T2) { static fn decode(&self, d: &D) -> (T0, T1, T2) { do d.read_tup(3) { ( @@ -470,7 +464,7 @@ pub impl< T1: Encodable, T2: Encodable, T3: Encodable -> (T0, T1, T2, T3): Encodable { +> Encodable for (T0, T1, T2, T3) { fn encode(&self, s: &S) { match *self { (ref t0, ref t1, ref t2, ref t3) => { @@ -491,7 +485,7 @@ pub impl< T1: Decodable, T2: Decodable, T3: Decodable -> (T0, T1, T2, T3): Decodable { +> Decodable for (T0, T1, T2, T3) { static fn decode(&self, d: &D) -> (T0, T1, T2, T3) { do d.read_tup(4) { ( @@ -511,7 +505,7 @@ pub impl< T2: Encodable, T3: Encodable, T4: Encodable -> (T0, T1, T2, T3, T4): Encodable { +> Encodable for (T0, T1, T2, T3, T4) { fn encode(&self, s: &S) { match *self { (ref t0, ref t1, ref t2, ref t3, ref t4) => { @@ -534,7 +528,7 @@ pub impl< T2: Decodable, T3: Decodable, T4: Decodable -> (T0, T1, T2, T3, T4): Decodable { +> Decodable for (T0, T1, T2, T3, T4) { static fn decode(&self, d: &D) -> (T0, T1, T2, T3, T4) { do d.read_tup(5) { @@ -558,7 +552,7 @@ pub trait EncoderHelpers { fn emit_from_vec(&self, v: &[T], f: fn(v: &T)); } -pub impl S: EncoderHelpers { +pub impl EncoderHelpers for S { fn emit_from_vec(&self, v: &[T], f: fn(v: &T)) { do self.emit_owned_vec(v.len()) { for v.eachi |i, e| { @@ -574,7 +568,7 @@ pub trait DecoderHelpers { fn read_to_vec(&self, f: fn() -> T) -> ~[T]; } -pub impl D: DecoderHelpers { +pub impl DecoderHelpers for D { fn read_to_vec(&self, f: fn() -> T) -> ~[T] { do self.read_owned_vec |len| { do vec::from_fn(len) |i| { diff --git a/src/libstd/sha1.rs b/src/libstd/sha1.rs index 1d91fafa4f962..242e318e8a8f0 100644 --- a/src/libstd/sha1.rs +++ b/src/libstd/sha1.rs @@ -265,7 +265,7 @@ pub fn sha1() -> Sha1 { computed: false, work_buf: @mut vec::from_elem(work_buf_len, 0u32) }; - let mut sh = (move st) as Sha1; + let mut sh = (st) as Sha1; sh.reset(); return sh; } diff --git a/src/libstd/sort.rs b/src/libstd/sort.rs index 98a451dc8abdd..3450205aa9569 100644 --- a/src/libstd/sort.rs +++ b/src/libstd/sort.rs @@ -59,7 +59,7 @@ pub pure fn merge_sort(v: &[const T], le: Le) -> ~[T] { } rs.push_all(vec::slice(a, a_ix, a_len)); rs.push_all(vec::slice(b, b_ix, b_len)); - move rs + rs } } @@ -195,12 +195,12 @@ pub fn tim_sort(array: &mut [T]) { let mut idx = 0; let mut remaining = size; loop { - let arr = vec::mut_view(array, idx, size); + let arr = vec::mut_slice(array, idx, size); let mut run_len: uint = count_run_ascending(arr); if run_len < min_run { let force = if remaining <= min_run {remaining} else {min_run}; - let slice = vec::mut_view(arr, 0, force); + let slice = vec::mut_slice(arr, 0, force); binarysort(slice, run_len); run_len = force; } @@ -241,7 +241,7 @@ fn binarysort(array: &mut [T], start: uint) { let mut n = start-left; copy_vec(array, left+1, array, left, n); - array[left] = move pivot; + array[left] = pivot; start += 1; } } @@ -431,12 +431,12 @@ impl MergeState { arr[n+1].len = arr[n+2].len; } - let slice = vec::mut_view(array, b1, b1+l1); + let slice = vec::mut_slice(array, b1, b1+l1); let k = gallop_right(&const array[b2], slice, 0); b1 += k; l1 -= k; if l1 != 0 { - let slice = vec::mut_view(array, b2, b2+l2); + let slice = vec::mut_slice(array, b2, b2+l2); let l2 = gallop_left( &const array[b1+l1-1],slice,l2-1); if l2 > 0 { @@ -455,7 +455,8 @@ impl MergeState { base2: uint, len2: uint) { assert len1 != 0 && len2 != 0 && base1+len1 == base2; - let mut tmp = vec::slice(array, base1, base1+len1); + let tmp = vec::cast_to_mut( + vec::slice(array, base1, base1+len1).to_vec()); let mut c1 = 0; let mut c2 = base2; @@ -509,7 +510,7 @@ impl MergeState { loop { assert len1 > 1 && len2 != 0; - let tmp_view = vec::const_view(tmp, c1, c1+len1); + let tmp_view = vec::const_slice(tmp, c1, c1+len1); count1 = gallop_right(&const array[c2], tmp_view, 0); if count1 != 0 { copy_vec(array, dest, tmp, c1, count1); @@ -520,7 +521,7 @@ impl MergeState { dest += 1; c2 += 1; len2 -= 1; if len2 == 0 { break_outer = true; break; } - let tmp_view = vec::const_view(array, c2, c2+len2); + let tmp_view = vec::const_slice(array, c2, c2+len2); count2 = gallop_left(&const tmp[c1], tmp_view, 0); if count2 != 0 { copy_vec(array, dest, array, c2, count2); @@ -558,7 +559,8 @@ impl MergeState { base2: uint, len2: uint) { assert len1 != 1 && len2 != 0 && base1 + len1 == base2; - let mut tmp = vec::slice(array, base2, base2+len2); + let tmp = vec::cast_to_mut( + vec::slice(array, base2, base2+len2).to_vec()); let mut c1 = base1 + len1 - 1; let mut c2 = len2 - 1; @@ -614,7 +616,7 @@ impl MergeState { loop { assert len2 > 1 && len1 != 0; - let tmp_view = vec::mut_view(array, base1, base1+len1); + let tmp_view = vec::mut_slice(array, base1, base1+len1); count1 = len1 - gallop_right( &const tmp[c2], tmp_view, len1-1); @@ -630,7 +632,7 @@ impl MergeState { let count2; { - let tmp_view = vec::mut_view(tmp, 0, len2); + let tmp_view = vec::mut_slice(tmp, 0, len2); count2 = len2 - gallop_left(&const array[c1], tmp_view, len2-1); @@ -710,7 +712,7 @@ fn copy_vec(dest: &mut [T], s1: uint, from: &[const T], s2: uint, len: uint) { assert s1+len <= dest.len() && s2+len <= from.len(); - let slice = vec::slice(from, s2, s2+len); + let slice = vec::slice(from, s2, s2+len).to_vec(); for slice.eachi |i, v| { dest[s1+i] = *v; } @@ -816,7 +818,7 @@ mod test_qsort { do quick_sort(names) |x, y| { int::le(*x, *y) }; - let immut_names = move names; + let immut_names = names; let pairs = vec::zip_slice(expected, immut_names); for vec::each(pairs) |p| { @@ -1022,14 +1024,14 @@ mod big_tests { let res = do vec::from_fn(num) |i| { arr[i % size] }; - move res + res } fn makeRange(n: uint) -> ~[uint] { let one = do vec::from_fn(n) |i| { i }; let mut two = copy one; vec::reverse(two); - vec::append(move two, one) + vec::append(two, one) } fn tabulate_unique(lo: uint, hi: uint) { @@ -1048,7 +1050,7 @@ mod big_tests { let arr = do vec::from_fn(n) |_i| { rng.gen_float() }; - let mut arr = move arr; + let mut arr = arr; tim_sort(arr); // *sort isSorted(arr); @@ -1087,9 +1089,9 @@ mod big_tests { isSorted(arr); let mut arr = if n > 4 { - let part = vec::view(arr, 0, 4); + let part = vec::slice(arr, 0, 4); multiplyVec(part, n) - } else { move arr }; + } else { arr }; tim_sort(arr); // ~sort isSorted(arr); @@ -1120,7 +1122,7 @@ mod big_tests { let arr = do vec::from_fn(n) |_i| { @rng.gen_float() }; - let mut arr = move arr; + let mut arr = arr; tim_sort(arr); // *sort isSorted(arr); @@ -1159,9 +1161,9 @@ mod big_tests { isSorted(arr); let mut arr = if n > 4 { - let part = vec::view(arr, 0, 4); + let part = vec::slice(arr, 0, 4); multiplyVec(part, n) - } else { move arr }; + } else { arr }; tim_sort(arr); // ~sort isSorted(arr); diff --git a/src/libstd/std.rc b/src/libstd/std.rc index 3c2baae6d57c1..b0756104fe532 100644 --- a/src/libstd/std.rc +++ b/src/libstd/std.rc @@ -99,6 +99,7 @@ pub mod rl; pub mod workcache; pub mod bigint; pub mod stats; +pub mod semver; #[cfg(unicode)] mod unicode; diff --git a/src/libstd/sync.rs b/src/libstd/sync.rs index af773f5bf4e50..fd0b0d6be3a2d 100644 --- a/src/libstd/sync.rs +++ b/src/libstd/sync.rs @@ -40,7 +40,7 @@ struct Waitqueue { head: pipes::Port, fn new_waitqueue() -> Waitqueue { let (block_head, block_tail) = pipes::stream(); - Waitqueue { head: move block_head, tail: move block_tail } + Waitqueue { head: block_head, tail: block_tail } } // Signals one live task from the queue. @@ -86,7 +86,7 @@ enum Sem = Exclusive>; #[doc(hidden)] fn new_sem(count: int, q: Q) -> Sem { Sem(exclusive(SemInner { - mut count: count, waiters: new_waitqueue(), blocked: move q })) + mut count: count, waiters: new_waitqueue(), blocked: q })) } #[doc(hidden)] fn new_sem_and_signal(count: int, num_condvars: uint) @@ -109,9 +109,9 @@ impl &Sem { // Create waiter nobe. let (WaitEnd, SignalEnd) = pipes::oneshot(); // Tell outer scope we need to block. - waiter_nobe = Some(move WaitEnd); + waiter_nobe = Some(WaitEnd); // Enqueue ourself. - state.waiters.tail.send(move SignalEnd); + state.waiters.tail.send(SignalEnd); } } } @@ -119,7 +119,7 @@ impl &Sem { /* for 1000.times { task::yield(); } */ // Need to wait outside the exclusive. if waiter_nobe.is_some() { - let _ = pipes::recv_one(option::unwrap(move waiter_nobe)); + let _ = pipes::recv_one(option::unwrap(waiter_nobe)); } } fn release() { @@ -215,8 +215,8 @@ impl &Condvar { fn wait_on(condvar_id: uint) { // Create waiter nobe. let (WaitEnd, SignalEnd) = pipes::oneshot(); - let mut WaitEnd = Some(move WaitEnd); - let mut SignalEnd = Some(move SignalEnd); + let mut WaitEnd = Some(WaitEnd); + let mut SignalEnd = Some(SignalEnd); let mut reacquire = None; let mut out_of_bounds = None; unsafe { @@ -231,7 +231,7 @@ impl &Condvar { } // Enqueue ourself to be woken up by a signaller. let SignalEnd = option::swap_unwrap(&mut SignalEnd); - state.blocked[condvar_id].tail.send(move SignalEnd); + state.blocked[condvar_id].tail.send(SignalEnd); } else { out_of_bounds = Some(vec::len(state.blocked)); } @@ -737,7 +737,7 @@ mod tests { pub fn test_sem_as_mutex() { let s = ~semaphore(1); let s2 = ~s.clone(); - do task::spawn |move s2| { + do task::spawn || { do s2.access { for 5.times { task::yield(); } } @@ -752,7 +752,7 @@ mod tests { let (p,c) = pipes::stream(); let s = ~semaphore(0); let s2 = ~s.clone(); - do task::spawn |move s2, move c| { + do task::spawn || { s2.acquire(); c.send(()); } @@ -764,7 +764,7 @@ mod tests { let (p,c) = pipes::stream(); let s = ~semaphore(0); let s2 = ~s.clone(); - do task::spawn |move s2, move p| { + do task::spawn || { for 5.times { task::yield(); } s2.release(); let _ = p.recv(); @@ -780,7 +780,7 @@ mod tests { let s2 = ~s.clone(); let (p1,c1) = pipes::stream(); let (p2,c2) = pipes::stream(); - do task::spawn |move s2, move c1, move p2| { + do task::spawn || { do s2.access { let _ = p2.recv(); c1.send(()); @@ -799,10 +799,10 @@ mod tests { let s = ~semaphore(1); let s2 = ~s.clone(); let (p,c) = pipes::stream(); - let child_data = ~mut Some((move s2, move c)); + let child_data = ~mut Some((s2, c)); do s.access { let (s2,c) = option::swap_unwrap(child_data); - do task::spawn |move c, move s2| { + do task::spawn || { c.send(()); do s2.access { } c.send(()); @@ -825,7 +825,7 @@ mod tests { let m2 = ~m.clone(); let mut sharedstate = ~0; let ptr = ptr::addr_of(&(*sharedstate)); - do task::spawn |move m2, move c| { + do task::spawn || { let sharedstate: &mut int = unsafe { cast::reinterpret_cast(&ptr) }; access_shared(sharedstate, m2, 10); @@ -854,7 +854,7 @@ mod tests { // Child wakes up parent do m.lock_cond |cond| { let m2 = ~m.clone(); - do task::spawn |move m2| { + do task::spawn || { do m2.lock_cond |cond| { let woken = cond.signal(); assert woken; @@ -865,7 +865,7 @@ mod tests { // Parent wakes up child let (port,chan) = pipes::stream(); let m3 = ~m.clone(); - do task::spawn |move chan, move m3| { + do task::spawn || { do m3.lock_cond |cond| { chan.send(()); cond.wait(); @@ -887,8 +887,8 @@ mod tests { for num_waiters.times { let mi = ~m.clone(); let (port, chan) = pipes::stream(); - ports.push(move port); - do task::spawn |move chan, move mi| { + ports.push(port); + do task::spawn || { do mi.lock_cond |cond| { chan.send(()); cond.wait(); @@ -918,7 +918,7 @@ mod tests { pub fn test_mutex_cond_no_waiter() { let m = ~Mutex(); let m2 = ~m.clone(); - do task::try |move m| { + do task::try || { do m.lock_cond |_x| { } }; do m2.lock_cond |cond| { @@ -931,7 +931,7 @@ mod tests { let m = ~Mutex(); let m2 = ~m.clone(); - let result: result::Result<(),()> = do task::try |move m2| { + let result: result::Result<(),()> = do task::try || { do m2.lock { fail!(); } @@ -947,9 +947,9 @@ mod tests { let m = ~Mutex(); let m2 = ~m.clone(); - let result: result::Result<(),()> = do task::try |move m2| { + let result: result::Result<(),()> = do task::try || { let (p,c) = pipes::stream(); - do task::spawn |move p| { // linked + do task::spawn || { // linked let _ = p.recv(); // wait for sibling to get in the mutex task::yield(); fail!(); @@ -972,19 +972,19 @@ mod tests { let m2 = ~m.clone(); let (p,c) = pipes::stream(); - let result: result::Result<(),()> = do task::try |move c, move m2| { + let result: result::Result<(),()> = do task::try || { let mut sibling_convos = ~[]; for 2.times { let (p,c) = pipes::stream(); - let c = ~mut Some(move c); - sibling_convos.push(move p); + let c = ~mut Some(c); + sibling_convos.push(p); let mi = ~m2.clone(); // spawn sibling task - do task::spawn |move mi, move c| { // linked + do task::spawn || { // linked do mi.lock_cond |cond| { let c = option::swap_unwrap(c); c.send(()); // tell sibling to go ahead - let _z = SendOnFailure(move c); + let _z = SendOnFailure(c); cond.wait(); // block forever } } @@ -993,7 +993,7 @@ mod tests { let _ = p.recv(); // wait for sibling to get in the mutex } do m2.lock { } - c.send(move sibling_convos); // let parent wait on all children + c.send(sibling_convos); // let parent wait on all children fail!(); }; assert result.is_err(); @@ -1015,7 +1015,7 @@ mod tests { fn SendOnFailure(c: pipes::Chan<()>) -> SendOnFailure { SendOnFailure { - c: move c + c: c } } } @@ -1025,7 +1025,7 @@ mod tests { let m = ~Mutex(); do m.lock_cond |cond| { let m2 = ~m.clone(); - do task::spawn |move m2| { + do task::spawn || { do m2.lock_cond |cond| { cond.signal_on(0); } @@ -1039,7 +1039,7 @@ mod tests { let m = ~mutex_with_condvars(2); let m2 = ~m.clone(); let (p,c) = pipes::stream(); - do task::spawn |move m2, move c| { + do task::spawn || { do m2.lock_cond |cond| { c.send(()); cond.wait_on(1); @@ -1088,7 +1088,7 @@ mod tests { }, DowngradeRead => do x.write_downgrade |mode| { - let mode = x.downgrade(move mode); + let mode = x.downgrade(mode); (&mode).read(blk); }, } @@ -1103,7 +1103,7 @@ mod tests { let x2 = ~x.clone(); let mut sharedstate = ~0; let ptr = ptr::addr_of(&(*sharedstate)); - do task::spawn |move c, move x2| { + do task::spawn || { let sharedstate: &mut int = unsafe { cast::reinterpret_cast(&ptr) }; access_shared(sharedstate, x2, mode1, 10); @@ -1148,7 +1148,7 @@ mod tests { let x2 = ~x.clone(); let (p1,c1) = pipes::stream(); let (p2,c2) = pipes::stream(); - do task::spawn |move c1, move x2, move p2| { + do task::spawn || { if !make_mode2_go_first { let _ = p2.recv(); // parent sends to us once it locks, or ... } @@ -1185,10 +1185,10 @@ mod tests { // Tests that downgrade can unlock the lock in both modes let x = ~RWlock(); do lock_rwlock_in_mode(x, Downgrade) { } - test_rwlock_handshake(move x, Read, Read, false); + test_rwlock_handshake(x, Read, Read, false); let y = ~RWlock(); do lock_rwlock_in_mode(y, DowngradeRead) { } - test_rwlock_exclusion(move y, Write, Write); + test_rwlock_exclusion(y, Write, Write); } #[test] pub fn test_rwlock_read_recursive() { @@ -1203,7 +1203,7 @@ mod tests { // Child wakes up parent do x.write_cond |cond| { let x2 = ~x.clone(); - do task::spawn |move x2| { + do task::spawn || { do x2.write_cond |cond| { let woken = cond.signal(); assert woken; @@ -1214,7 +1214,7 @@ mod tests { // Parent wakes up child let (port,chan) = pipes::stream(); let x3 = ~x.clone(); - do task::spawn |move x3, move chan| { + do task::spawn || { do x3.write_cond |cond| { chan.send(()); cond.wait(); @@ -1250,8 +1250,8 @@ mod tests { for num_waiters.times { let xi = ~x.clone(); let (port, chan) = pipes::stream(); - ports.push(move port); - do task::spawn |move chan, move xi| { + ports.push(port); + do task::spawn || { do lock_cond(xi, dg1) |cond| { chan.send(()); cond.wait(); @@ -1286,7 +1286,7 @@ mod tests { let x = ~RWlock(); let x2 = ~x.clone(); - let result: result::Result<(),()> = do task::try |move x2| { + let result: result::Result<(),()> = do task::try || { do lock_rwlock_in_mode(x2, mode1) { fail!(); } @@ -1332,7 +1332,7 @@ mod tests { let x = ~RWlock(); let y = ~RWlock(); do x.write_downgrade |xwrite| { - let mut xopt = Some(move xwrite); + let mut xopt = Some(xwrite); do y.write_downgrade |_ywrite| { y.downgrade(option::swap_unwrap(&mut xopt)); error!("oops, y.downgrade(x) should have failed!"); diff --git a/src/libstd/task_pool.rs b/src/libstd/task_pool.rs index 5ed2195d2d2ad..6f479fbb9f7f5 100644 --- a/src/libstd/task_pool.rs +++ b/src/libstd/task_pool.rs @@ -50,11 +50,11 @@ pub impl TaskPool { let (port, chan) = pipes::stream::>(); let init_fn = init_fn_factory(); - let task_body: ~fn() = |move port, move init_fn| { + let task_body: ~fn() = || { let local_data = init_fn(i); loop { match port.recv() { - Execute(move f) => f(&local_data), + Execute(f) => f(&local_data), Quit => break } } @@ -64,23 +64,23 @@ pub impl TaskPool { match opt_sched_mode { None => { // Run on this scheduler. - task::spawn(move task_body); + task::spawn(task_body); } Some(sched_mode) => { - task::task().sched_mode(sched_mode).spawn(move task_body); + task::task().sched_mode(sched_mode).spawn(task_body); } } - move chan + chan }; - return TaskPool { channels: move channels, next_index: 0 }; + return TaskPool { channels: channels, next_index: 0 }; } /// Executes the function `f` on a task in the pool. The function /// receives a reference to the local data returned by the `init_fn`. fn execute(&self, f: ~fn(&T)) { - self.channels[self.next_index].send(Execute(move f)); + self.channels[self.next_index].send(Execute(f)); self.next_index += 1; if self.next_index == self.channels.len() { self.next_index = 0; } } @@ -90,9 +90,9 @@ pub impl TaskPool { fn test_task_pool() { let f: ~fn() -> ~fn(uint) -> uint = || { let g: ~fn(uint) -> uint = |i| i; - move g + g }; - let pool = TaskPool::new(4, Some(SingleThreaded), move f); + let pool = TaskPool::new(4, Some(SingleThreaded), f); for 8.times { pool.execute(|i| io::println(fmt!("Hello from thread %u!", *i))); } diff --git a/src/libstd/test.rs b/src/libstd/test.rs index 530761e48a201..cd03de9118390 100644 --- a/src/libstd/test.rs +++ b/src/libstd/test.rs @@ -120,8 +120,8 @@ pub struct TestDescAndFn { pub fn test_main(args: &[~str], tests: ~[TestDescAndFn]) { let opts = match parse_opts(args) { - either::Left(move o) => o, - either::Right(move m) => fail!(m) + either::Left(o) => o, + either::Right(m) => fail!(m) }; if !run_tests_console(&opts, tests) { fail!(~"Some tests failed"); } } @@ -143,7 +143,7 @@ pub fn test_main_static(args: &[~str], tests: &[TestDescAndFn]) { TestDescAndFn { testfn: StaticBenchFn(f), desc: copy t.desc }, _ => { - die! (~"non-static tests passed to test::test_main_static"); + fail!(~"non-static tests passed to test::test_main_static"); } } }; @@ -173,8 +173,8 @@ pub fn parse_opts(args: &[~str]) -> OptRes { getopts::optopt(~"logfile")]; let matches = match getopts::getopts(args_, opts) { - Ok(move m) => m, - Err(move f) => return either::Right(getopts::fail_str(f)) + Ok(m) => m, + Err(f) => return either::Right(getopts::fail_str(f)) }; let filter = @@ -260,7 +260,7 @@ pub fn run_tests_console(opts: &TestOpts, st.failed += 1; write_failed(st.out, st.use_color); st.out.write_line(~""); - st.failures.push(move test); + st.failures.push(test); } TrIgnored => { st.ignored += 1; @@ -410,7 +410,7 @@ fn should_sort_failures_before_printing_them() { mut failed: 0u, mut ignored: 0u, mut benchmarked: 0u, - mut failures: ~[move test_b, move test_a] + mut failures: ~[test_b, test_a] }; print_failures(st); @@ -486,7 +486,7 @@ fn run_tests(opts: &TestOpts, callback(TeWait(copy b.desc)); run_test(!opts.run_benchmarks, b, ch.clone()); let (test, result) = p.recv(); - callback(TeResult(move test, result)); + callback(TeResult(test, result)); } } @@ -514,7 +514,7 @@ pub fn filter_tests( // Remove tests that don't match the test filter filtered = if opts.filter.is_none() { - move filtered + filtered } else { let filter_str = match opts.filter { @@ -534,7 +534,7 @@ pub fn filter_tests( // Maybe pull out the ignored test and unignore them filtered = if !opts.run_ignored { - move filtered + filtered } else { fn filter(test: TestDescAndFn) -> Option { if test.desc.ignore { @@ -556,7 +556,7 @@ pub fn filter_tests( } sort::quick_sort(filtered, lteq); - move filtered + filtered } struct TestFuture { @@ -582,9 +582,9 @@ pub fn run_test(force_ignore: bool, do task::spawn { let mut result_future = None; // task::future_result(builder); task::task().unlinked().future_result(|+r| { - result_future = Some(move r); + result_future = Some(r); }).spawn(testfn_cell.take()); - let task_result = option::unwrap(move result_future).recv(); + let task_result = option::unwrap(result_future).recv(); let test_result = calc_result(&desc, task_result == task::Success); monitor_ch.send((desc, test_result)); @@ -965,9 +965,9 @@ mod tests { }, testfn: DynTestFn(copy testfn), }; - tests.push(move test); + tests.push(test); } - move tests + tests }; let filtered = filter_tests(&opts, tests); @@ -980,7 +980,7 @@ mod tests { ~"test::parse_ignored_flag", ~"test::sort_tests"]; - let pairs = vec::zip(expected, move filtered); + let pairs = vec::zip(expected, filtered); for vec::each(pairs) |p| { match *p { diff --git a/src/libstd/time.rs b/src/libstd/time.rs index 77e7e3c3054d8..0b8b6c8d34d68 100644 --- a/src/libstd/time.rs +++ b/src/libstd/time.rs @@ -170,7 +170,7 @@ pub fn at_utc(clock: Timespec) -> Tm { let mut Timespec { sec, nsec } = clock; let mut tm = empty_tm(); rustrt::rust_gmtime(sec, nsec, tm); - move tm + tm } } @@ -185,7 +185,7 @@ pub fn at(clock: Timespec) -> Tm { let mut Timespec { sec, nsec } = clock; let mut tm = empty_tm(); rustrt::rust_localtime(sec, nsec, tm); - move tm + tm } } @@ -205,7 +205,7 @@ pub pure fn strptime(s: &str, format: &str) -> Result { pub pure fn strftime(format: &str, tm: &Tm) -> ~str { // unsafe only because do_strftime is annoying to make pure // (it does IO with a str_reader) - move unsafe { do_strftime(format, tm) } + unsafe { do_strftime(format, tm) } } impl Tm { @@ -240,7 +240,7 @@ impl Tm { /// Formats the time according to the format string. pure fn strftime(&self, format: &str) -> ~str { - move strftime(format, self) + strftime(format, self) } /** @@ -689,7 +689,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result { '%' => { match parse_type(s, pos, rdr.read_char(), &mut tm) { Ok(next) => pos = next, - Err(move e) => { result = Err(move e); break; } + Err(e) => { result = Err(e); break; } } }, c => { @@ -714,7 +714,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result { tm_zone: copy tm.tm_zone, tm_nsec: tm.tm_nsec, }) - } else { move result } + } else { result } } } @@ -882,7 +882,7 @@ priv fn do_strftime(format: &str, tm: &Tm) -> ~str { } } - move buf + buf } #[cfg(test)] diff --git a/src/libstd/uv_global_loop.rs b/src/libstd/uv_global_loop.rs index 3152f0b540524..872d53e93ebbe 100644 --- a/src/libstd/uv_global_loop.rs +++ b/src/libstd/uv_global_loop.rs @@ -98,7 +98,7 @@ fn get_monitor_task_gl() -> IoTask { fn spawn_loop() -> IoTask { let builder = do task().add_wrapper |task_body| { - fn~(move task_body) { + fn~() { // The I/O loop task also needs to be weak so it doesn't keep // the runtime alive unsafe { @@ -116,7 +116,7 @@ fn spawn_loop() -> IoTask { } }; let builder = builder.unlinked(); - spawn_iotask(move builder) + spawn_iotask(builder) } #[cfg(test)] diff --git a/src/libstd/uv_iotask.rs b/src/libstd/uv_iotask.rs index a93bdf86a6428..be4240237adf4 100644 --- a/src/libstd/uv_iotask.rs +++ b/src/libstd/uv_iotask.rs @@ -78,7 +78,7 @@ pub fn spawn_iotask(task: task::TaskBuilder) -> IoTask { */ pub unsafe fn interact(iotask: &IoTask, cb: fn~(*c_void)) { - send_msg(iotask, Interaction(move cb)); + send_msg(iotask, Interaction(cb)); } /** @@ -150,7 +150,7 @@ struct IoTaskLoopData { fn send_msg(iotask: &IoTask, msg: IoTaskMsg) { - iotask.op_chan.send(move msg); + iotask.op_chan.send(msg); unsafe { ll::async_send(iotask.async_handle); } diff --git a/src/libstd/uv_ll.rs b/src/libstd/uv_ll.rs index be6b79059a9f2..96b285b8c0a85 100644 --- a/src/libstd/uv_ll.rs +++ b/src/libstd/uv_ll.rs @@ -1252,8 +1252,7 @@ pub mod test { get_data_for_uv_handle(stream as *libc::c_void) as *request_wrapper; let buf_base = get_base_from_buf(buf); - let buf_len = get_len_from_buf(buf); - let bytes = vec::from_buf(buf_base, buf_len as uint); + let bytes = vec::from_buf(buf_base, nread as uint); let read_chan = (*client_data).read_chan.clone(); let msg_from_server = str::from_bytes(bytes); read_chan.send(msg_from_server); @@ -1445,7 +1444,7 @@ pub mod test { buf_base as uint, buf_len as uint, nread)); - let bytes = vec::from_buf(buf_base, buf_len); + let bytes = vec::from_buf(buf_base, nread as uint); let request_str = str::from_bytes(bytes); let client_data = get_data_for_uv_handle( @@ -1453,7 +1452,7 @@ pub mod test { let server_kill_msg = (*client_data).server_kill_msg; let write_req = (*client_data).server_write_req; - if (str::contains(request_str, server_kill_msg)) { + if str::contains(request_str, server_kill_msg) { log(debug, ~"SERVER: client req contains kill_msg!"); log(debug, ~"SERVER: sending response to client"); read_stop(client_stream_ptr); diff --git a/src/libstd/workcache.rs b/src/libstd/workcache.rs index d652b18cfad47..70c03c69d2db3 100644 --- a/src/libstd/workcache.rs +++ b/src/libstd/workcache.rs @@ -16,7 +16,6 @@ use serialize::{Encoder, Encodable, Decoder, Decodable}; use sort; use core::cmp; -use core::dvec; use core::either::{Either, Left, Right}; use core::io; use core::option; @@ -139,19 +138,18 @@ impl WorkKey { type WorkMap = LinearMap; -pub impl WorkMap: Encodable { +pub impl Encodable for WorkMap { fn encode(&self, s: &S) { - let d = dvec::DVec(); + let mut d = ~[]; for self.each |&(k, v)| { d.push((copy *k, copy *v)) } - let mut v = d.get(); - sort::tim_sort(v); - v.encode(s) + sort::tim_sort(d); + d.encode(s) } } -pub impl WorkMap: Decodable { +pub impl Decodable for WorkMap { static fn decode(&self, d: &D) -> WorkMap { let v : ~[(WorkKey,~str)] = Decodable::decode(d); let mut w = LinearMap::new(); @@ -237,7 +235,7 @@ fn json_encode>(t: &T) -> ~str { fn json_decode>(s: &str) -> T { do io::with_str_reader(s) |rdr| { let j = result::unwrap(json::from_reader(rdr)); - Decodable::decode(&json::Decoder(move j)) + Decodable::decode(&json::Decoder(j)) } } @@ -325,20 +323,20 @@ impl TPrep for @Mut { Decodable>(&self, blk: ~fn(&Exec) -> T) -> Work { - let mut bo = Some(move blk); + let mut bo = Some(blk); do self.borrow_imm |p| { let cached = do p.ctxt.db.borrow_mut |db| { db.prepare(p.fn_name, &p.declared_inputs) }; - match move cached { + match cached { Some((ref disc_in, ref disc_out, ref res)) if self.all_fresh("declared input", &p.declared_inputs) && self.all_fresh("discovered input", disc_in) && self.all_fresh("discovered output", disc_out) => { - Work::new(*self, move Left(json_decode(*res))) + Work::new(*self, Left(json_decode(*res))) } _ => { @@ -346,16 +344,16 @@ impl TPrep for @Mut { let mut blk = None; blk <-> bo; let blk = blk.unwrap(); - let chan = ~mut Some(move chan); - do task::spawn |move blk, move chan| { + let chan = ~mut Some(chan); + do task::spawn || { let exe = Exec{discovered_inputs: LinearMap::new(), discovered_outputs: LinearMap::new()}; let chan = option::swap_unwrap(&mut *chan); let v = blk(&exe); - send_one(move chan, (move exe, move v)); + send_one(chan, (exe, v)); } - Work::new(*self, move Right(move port)) + Work::new(*self, Right(port)) } } } @@ -367,7 +365,7 @@ impl> Work { static fn new(p: @Mut, e: Either>) -> Work { - move Work { prep: p, res: Some(move e) } + Work { prep: p, res: Some(e) } } } @@ -376,18 +374,18 @@ fn unwrap Decodable>(w: Work) -> T { - let mut ww = move w; + let mut ww = w; let mut s = None; ww.res <-> s; - match move s { + match s { None => fail!(), - Some(Left(move v)) => move v, - Some(Right(move port)) => { + Some(Left(v)) => v, + Some(Right(port)) => { - let (exe, v) = match recv(move port) { - oneshot::send(move data) => move data + let (exe, v) = match recv(port) { + oneshot::send(data) => data }; let s = json_encode(&v); @@ -401,7 +399,7 @@ fn unwrap ident: Encodable { +pub impl Encodable for ident { fn encode(&self, s: &S) { let intr = match unsafe { task::local_data::local_data_get(interner_key!()) @@ -45,7 +45,7 @@ pub impl ident: Encodable { } } -pub impl ident: Decodable { +pub impl Decodable for ident { static fn decode(d: &D) -> ident { let intr = match unsafe { task::local_data::local_data_get(interner_key!()) @@ -58,7 +58,7 @@ pub impl ident: Decodable { } } -pub impl ident: to_bytes::IterBytes { +pub impl to_bytes::IterBytes for ident { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { self.repr.iter_bytes(lsb0, f) } @@ -67,6 +67,12 @@ pub impl ident: to_bytes::IterBytes { // Functions may or may not have names. pub type fn_ident = Option; +pub struct Lifetime { + id: node_id, + span: span, + ident: ident +} + #[auto_encode] #[auto_decode] #[deriving_eq] @@ -211,7 +217,7 @@ pub enum binding_mode { bind_infer } -pub impl binding_mode : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for binding_mode { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { match *self { bind_by_copy => 0u8.iter_bytes(lsb0, f), @@ -256,7 +262,7 @@ pub enum pat_ { #[deriving_eq] pub enum mutability { m_mutbl, m_imm, m_const, } -pub impl mutability : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for mutability { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as u8).iter_bytes(lsb0, f) } @@ -269,13 +275,13 @@ pub enum Abi { RustAbi } -pub impl Abi : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for Abi { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as uint).iter_bytes(lsb0, f) } } -pub impl Abi : ToStr { +pub impl ToStr for Abi { pure fn to_str(&self) -> ~str { match *self { RustAbi => ~"\"rust\"" @@ -292,13 +298,13 @@ pub enum Sigil { ManagedSigil } -pub impl Sigil : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for Sigil { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as uint).iter_bytes(lsb0, f) } } -pub impl Sigil : ToStr { +pub impl ToStr for Sigil { pure fn to_str(&self) -> ~str { match *self { BorrowedSigil => ~"&", @@ -377,7 +383,7 @@ pub enum inferable { infer(node_id) } -pub impl inferable : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for inferable { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { match *self { expl(ref t) => @@ -395,7 +401,7 @@ pub impl inferable : to_bytes::IterBytes { #[deriving_eq] pub enum rmode { by_ref, by_val, by_copy } -pub impl rmode : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for rmode { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as u8).iter_bytes(lsb0, f) } @@ -736,13 +742,13 @@ pub enum trait_method { #[deriving_eq] pub enum int_ty { ty_i, ty_char, ty_i8, ty_i16, ty_i32, ty_i64, } -pub impl int_ty : ToStr { +pub impl ToStr for int_ty { pure fn to_str(&self) -> ~str { ::ast_util::int_ty_to_str(*self) } } -pub impl int_ty : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for int_ty { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as u8).iter_bytes(lsb0, f) } @@ -753,13 +759,13 @@ pub impl int_ty : to_bytes::IterBytes { #[deriving_eq] pub enum uint_ty { ty_u, ty_u8, ty_u16, ty_u32, ty_u64, } -pub impl uint_ty : ToStr { +pub impl ToStr for uint_ty { pure fn to_str(&self) -> ~str { ::ast_util::uint_ty_to_str(*self) } } -pub impl uint_ty : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for uint_ty { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as u8).iter_bytes(lsb0, f) } @@ -770,13 +776,13 @@ pub impl uint_ty : to_bytes::IterBytes { #[deriving_eq] pub enum float_ty { ty_f, ty_f32, ty_f64, } -pub impl float_ty : ToStr { +pub impl ToStr for float_ty { pure fn to_str(&self) -> ~str { ::ast_util::float_ty_to_str(*self) } } -pub impl float_ty : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for float_ty { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as u8).iter_bytes(lsb0, f) } @@ -830,7 +836,7 @@ pub enum Onceness { Many } -pub impl Onceness : ToStr { +pub impl ToStr for Onceness { pure fn to_str(&self) -> ~str { match *self { Once => ~"once", @@ -839,7 +845,7 @@ pub impl Onceness : ToStr { } } -pub impl Onceness : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for Onceness { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as uint).iter_bytes(lsb0, f); } @@ -889,7 +895,7 @@ pub enum ty_ { ty_infer, } -pub impl Ty : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for Ty { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { to_bytes::iter_bytes_2(&self.span.lo, &self.span.hi, lsb0, f); } @@ -925,7 +931,7 @@ pub enum purity { extern_fn, // declared with "extern fn" } -pub impl purity : ToStr { +pub impl ToStr for purity { pure fn to_str(&self) -> ~str { match *self { impure_fn => ~"impure", @@ -936,7 +942,7 @@ pub impl purity : ToStr { } } -pub impl purity : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for purity { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as u8).iter_bytes(lsb0, f) } @@ -951,7 +957,7 @@ pub enum ret_style { return_val, // everything else } -pub impl ret_style : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for ret_style { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as u8).iter_bytes(lsb0, f) } @@ -1232,7 +1238,7 @@ pub enum item_ { #[deriving_eq] pub enum struct_mutability { struct_mutable, struct_immutable } -pub impl struct_mutability : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for struct_mutability { pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as u8).iter_bytes(lsb0, f) } diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index 9eeee943f8b24..108a0dfc5e060 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -34,7 +34,7 @@ pub enum path_elt { path_name(ident) } -pub impl path_elt : cmp::Eq { +pub impl cmp::Eq for path_elt { pure fn eq(&self, other: &path_elt) -> bool { match (*self) { path_mod(e0a) => { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 335dd4e3fa247..f7ae205809549 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -198,7 +198,7 @@ pub pure fn is_call_expr(e: @expr) -> bool { } // This makes def_id hashable -pub impl def_id : to_bytes::IterBytes { +pub impl to_bytes::IterBytes for def_id { #[inline(always)] pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { to_bytes::iter_bytes_2(&self.crate, &self.node, lsb0, f); @@ -303,7 +303,7 @@ pub trait inlined_item_utils { fn accept(&self, e: E, v: visit::vt); } -pub impl inlined_item: inlined_item_utils { +pub impl inlined_item_utils for inlined_item { fn ident(&self) -> ident { match *self { ii_item(i) => /* FIXME (#2543) */ copy i.ident, diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index e3d1fb9781b2e..605d944c70db9 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -192,13 +192,15 @@ fn eq(a: @ast::meta_item, b: @ast::meta_item) -> bool { } _ => false }, - ast::meta_list(*) => { - - // ~[Fixme-sorting] - // FIXME (#607): Needs implementing - // This involves probably sorting the list by name and - // meta_item variant - fail!(~"unimplemented meta_item variant") + ast::meta_list(ref na, misa) => match b.node { + ast::meta_list(ref nb, misb) => { + if na != nb { return false; } + for misa.each |&mi| { + if !contains(misb, mi) { return false; } + } + true + } + _ => false } } } @@ -253,8 +255,6 @@ pub fn last_meta_item_list_by_name(items: ~[@ast::meta_item], name: ~str) /* Higher-level applications */ -// FIXME (#607): This needs to sort by meta_item variant in addition to -// the item name (See [Fixme-sorting]) pub fn sort_meta_items(+items: ~[@ast::meta_item]) -> ~[@ast::meta_item] { pure fn lteq(ma: &@ast::meta_item, mb: &@ast::meta_item) -> bool { pure fn key(m: &ast::meta_item) -> ~str { @@ -270,7 +270,17 @@ pub fn sort_meta_items(+items: ~[@ast::meta_item]) -> ~[@ast::meta_item] { // This is sort of stupid here, converting to a vec of mutables and back let mut v: ~[@ast::meta_item] = items; std::sort::quick_sort(v, lteq); - move v + + // There doesn't seem to be a more optimal way to do this + do v.map |&m| { + match m.node { + ast::meta_list(n, mis) => @spanned { + node: ast::meta_list(n, sort_meta_items(mis)), + .. *m + }, + _ => m + } + } } pub fn remove_meta_items_by_name(items: ~[@ast::meta_item], name: ~str) -> diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 10a4e12bef4fc..851b35ca3bd3f 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -46,71 +46,71 @@ pub enum CharPos = uint; // XXX: Lots of boilerplate in these impls, but so far my attempts to fix // have been unsuccessful -pub impl BytePos: Pos { +pub impl Pos for BytePos { static pure fn from_uint(n: uint) -> BytePos { BytePos(n) } pure fn to_uint(&self) -> uint { **self } } -pub impl BytePos: cmp::Eq { +pub impl cmp::Eq for BytePos { pure fn eq(&self, other: &BytePos) -> bool { **self == **other } pure fn ne(&self, other: &BytePos) -> bool { !(*self).eq(other) } } -pub impl BytePos: cmp::Ord { +pub impl cmp::Ord for BytePos { pure fn lt(&self, other: &BytePos) -> bool { **self < **other } pure fn le(&self, other: &BytePos) -> bool { **self <= **other } pure fn ge(&self, other: &BytePos) -> bool { **self >= **other } pure fn gt(&self, other: &BytePos) -> bool { **self > **other } } -pub impl BytePos: Add { +pub impl Add for BytePos { pure fn add(&self, rhs: &BytePos) -> BytePos { BytePos(**self + **rhs) } } -pub impl BytePos: Sub { +pub impl Sub for BytePos { pure fn sub(&self, rhs: &BytePos) -> BytePos { BytePos(**self - **rhs) } } -pub impl BytePos: to_bytes::IterBytes { +pub impl to_bytes::IterBytes for BytePos { pure fn iter_bytes(&self, +lsb0: bool, &&f: to_bytes::Cb) { (**self).iter_bytes(lsb0, f) } } -pub impl CharPos: Pos { +pub impl Pos for CharPos { static pure fn from_uint(n: uint) -> CharPos { CharPos(n) } pure fn to_uint(&self) -> uint { **self } } -pub impl CharPos: cmp::Eq { +pub impl cmp::Eq for CharPos { pure fn eq(&self, other: &CharPos) -> bool { **self == **other } pure fn ne(&self, other: &CharPos) -> bool { !(*self).eq(other) } } -pub impl CharPos: cmp::Ord { +pub impl cmp::Ord for CharPos { pure fn lt(&self, other: &CharPos) -> bool { **self < **other } pure fn le(&self, other: &CharPos) -> bool { **self <= **other } pure fn ge(&self, other: &CharPos) -> bool { **self >= **other } pure fn gt(&self, other: &CharPos) -> bool { **self > **other } } -pub impl CharPos: to_bytes::IterBytes { +pub impl to_bytes::IterBytes for CharPos { pure fn iter_bytes(&self, +lsb0: bool, &&f: to_bytes::Cb) { (**self).iter_bytes(lsb0, f) } } -pub impl CharPos: Add { +pub impl Add for CharPos { pure fn add(&self, rhs: &CharPos) -> CharPos { CharPos(**self + **rhs) } } -pub impl CharPos: Sub { +pub impl Sub for CharPos { pure fn sub(&self, rhs: &CharPos) -> CharPos { CharPos(**self - **rhs) } @@ -133,26 +133,26 @@ pub struct span { #[deriving_eq] pub struct spanned { node: T, span: span } -pub impl span : cmp::Eq { +pub impl cmp::Eq for span { pure fn eq(&self, other: &span) -> bool { return (*self).lo == (*other).lo && (*self).hi == (*other).hi; } pure fn ne(&self, other: &span) -> bool { !(*self).eq(other) } } -pub impl span: Encodable { +pub impl Encodable for span { /* Note #1972 -- spans are encoded but not decoded */ fn encode(&self, _s: &S) { } } -pub impl span: Decodable { +pub impl Decodable for span { static fn decode(_d: &D) -> span { dummy_sp() } } pub pure fn spanned(+lo: BytePos, +hi: BytePos, +t: T) -> spanned { - respan(mk_sp(lo, hi), move t) + respan(mk_sp(lo, hi), t) } pub pure fn respan(sp: span, +t: T) -> spanned { @@ -160,7 +160,7 @@ pub pure fn respan(sp: span, +t: T) -> spanned { } pub pure fn dummy_spanned(+t: T) -> spanned { - respan(dummy_sp(), move t) + respan(dummy_sp(), t) } /* assuming that we're not in macro expansion */ diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 2b24d03f8e9e5..ad0998d503a36 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -231,7 +231,7 @@ fn highlight_lines(cm: @codemap::CodeMap, let mut elided = false; let mut display_lines = /* FIXME (#2543) */ copy lines.lines; if vec::len(display_lines) > max_lines { - display_lines = vec::slice(display_lines, 0u, max_lines); + display_lines = vec::slice(display_lines, 0u, max_lines).to_vec(); elided = true; } // Print the offending lines diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 951e350f8b290..33eaaaae35b3e 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -281,7 +281,7 @@ pub fn mk_ctxt(parse_sess: parse::parse_sess, mod_path: ~[], trace_mac: false }; - move ((move imp) as @ext_ctxt) + ((imp) as @ext_ctxt) } pub fn expr_to_str(cx: ext_ctxt, expr: @ast::expr, err_msg: ~str) -> ~str { diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index a050b2316e873..963ea5bfe3329 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -73,7 +73,7 @@ pub fn mk_raw_path_(sp: span, global: false, idents: idents, rp: None, - types: move types } + types: types } } pub fn mk_raw_path_global(sp: span, idents: ~[ast::ident]) -> @ast::path { @ast::path { span: sp, @@ -156,7 +156,7 @@ pub fn mk_field(sp: span, f: &{ident: ast::ident, ex: @ast::expr}) } pub fn mk_fields(sp: span, fields: ~[{ident: ast::ident, ex: @ast::expr}]) -> ~[ast::field] { - move fields.map(|f| mk_field(sp, f)) + fields.map(|f| mk_field(sp, f)) } pub fn mk_rec_e(cx: ext_ctxt, sp: span, @@ -288,33 +288,33 @@ pub fn mk_pat_ident_with_binding_mode(cx: ext_ctxt, bm: ast::binding_mode) -> @ast::pat { let path = mk_raw_path(span, ~[ ident ]); let pat = ast::pat_ident(bm, path, None); - mk_pat(cx, span, move pat) + mk_pat(cx, span, pat) } pub fn mk_pat_enum(cx: ext_ctxt, span: span, path: @ast::path, +subpats: ~[@ast::pat]) -> @ast::pat { - let pat = ast::pat_enum(path, Some(move subpats)); - mk_pat(cx, span, move pat) + let pat = ast::pat_enum(path, Some(subpats)); + mk_pat(cx, span, pat) } pub fn mk_pat_struct(cx: ext_ctxt, span: span, path: @ast::path, +field_pats: ~[ast::field_pat]) -> @ast::pat { - let pat = ast::pat_struct(path, move field_pats, false); - mk_pat(cx, span, move pat) + let pat = ast::pat_struct(path, field_pats, false); + mk_pat(cx, span, pat) } pub fn mk_bool(cx: ext_ctxt, span: span, value: bool) -> @ast::expr { let lit_expr = ast::expr_lit(@codemap::spanned { node: ast::lit_bool(value), span: span }); - build::mk_expr(cx, span, move lit_expr) + build::mk_expr(cx, span, lit_expr) } pub fn mk_stmt(cx: ext_ctxt, span: span, expr: @ast::expr) -> @ast::stmt { let stmt_ = ast::stmt_semi(expr, cx.next_id()); - @codemap::spanned { node: move stmt_, span: span } + @codemap::spanned { node: stmt_, span: span } } pub fn mk_ty_path(cx: ext_ctxt, span: span, @@ -322,7 +322,7 @@ pub fn mk_ty_path(cx: ext_ctxt, -> @ast::Ty { let ty = build::mk_raw_path(span, idents); let ty = ast::ty_path(ty, cx.next_id()); - let ty = @ast::Ty { id: cx.next_id(), node: move ty, span: span }; + let ty = @ast::Ty { id: cx.next_id(), node: ty, span: span }; ty } pub fn mk_ty_path_global(cx: ext_ctxt, @@ -331,7 +331,7 @@ pub fn mk_ty_path_global(cx: ext_ctxt, -> @ast::Ty { let ty = build::mk_raw_path_global(span, idents); let ty = ast::ty_path(ty, cx.next_id()); - let ty = @ast::Ty { id: cx.next_id(), node: move ty, span: span }; + let ty = @ast::Ty { id: cx.next_id(), node: ty, span: span }; ty } pub fn mk_simple_ty_path(cx: ext_ctxt, diff --git a/src/libsyntax/ext/deriving.rs b/src/libsyntax/ext/deriving.rs index 8e87357f8b5b9..1aa1d8ca9a07e 100644 --- a/src/libsyntax/ext/deriving.rs +++ b/src/libsyntax/ext/deriving.rs @@ -95,19 +95,19 @@ fn expand_deriving(cx: ext_ctxt, span, struct_def, item.ident, - move ty_params)); + ty_params)); } item_enum(ref enum_definition, copy ty_params) => { result.push(expand_deriving_enum_def(cx, span, enum_definition, item.ident, - move ty_params)); + ty_params)); } _ => () } } - dvec::unwrap(move result) + dvec::unwrap(result) } fn create_impl_item(cx: ext_ctxt, span: span, +item: item_) -> @item { @@ -115,7 +115,7 @@ fn create_impl_item(cx: ext_ctxt, span: span, +item: item_) -> @item { ident: clownshoes_extensions, attrs: ~[], id: cx.next_id(), - node: move item, + node: item, vis: public, span: span, } @@ -161,7 +161,7 @@ fn create_eq_method(cx: ext_ctxt, }; // Create the function declaration. - let fn_decl = build::mk_fn_decl(~[ move arg ], output_type); + let fn_decl = build::mk_fn_decl(~[ arg ], output_type); // Create the body block. let body_block = build::mk_simple_block(cx, span, body); @@ -174,8 +174,8 @@ fn create_eq_method(cx: ext_ctxt, tps: ~[], self_ty: self_ty, purity: pure_fn, - decl: move fn_decl, - body: move body_block, + decl: fn_decl, + body: body_block, id: cx.next_id(), span: span, self_id: cx.next_id(), @@ -194,14 +194,14 @@ fn create_self_type_with_params(cx: ext_ctxt, let self_ty_param = build::mk_simple_ty_path(cx, span, ty_param.ident); - self_ty_params.push(move self_ty_param); + self_ty_params.push(self_ty_param); } - let self_ty_params = dvec::unwrap(move self_ty_params); + let self_ty_params = dvec::unwrap(self_ty_params); // Create the type of `self`. let self_type = build::mk_raw_path_(span, ~[ type_ident ], - move self_ty_params); + self_ty_params); let self_type = ty_path(self_type, cx.next_id()); @ast::Ty { id: cx.next_id(), node: self_type, span: span } } @@ -221,9 +221,9 @@ fn create_derived_impl(cx: ext_ctxt, trait_path.map(|x| *x)); let bounds = @~[ TraitTyParamBound(bound) ]; let impl_ty_param = build::mk_ty_param(cx, ty_param.ident, bounds); - impl_ty_params.push(move impl_ty_param); + impl_ty_params.push(impl_ty_param); } - let impl_ty_params = dvec::unwrap(move impl_ty_params); + let impl_ty_params = dvec::unwrap(impl_ty_params); // Create the reference to the trait. let trait_path = ast::path { @@ -233,12 +233,12 @@ fn create_derived_impl(cx: ext_ctxt, rp: None, types: ~[] }; - let trait_path = @move trait_path; + let trait_path = @trait_path; let trait_ref = ast::trait_ref { path: trait_path, ref_id: cx.next_id() }; - let trait_ref = @move trait_ref; + let trait_ref = @trait_ref; // Create the type of `self`. let self_type = create_self_type_with_params(cx, @@ -247,11 +247,11 @@ fn create_derived_impl(cx: ext_ctxt, ty_params); // Create the impl item. - let impl_item = item_impl(move impl_ty_params, + let impl_item = item_impl(impl_ty_params, Some(trait_ref), self_type, methods.map(|x| *x)); - return create_impl_item(cx, span, move impl_item); + return create_impl_item(cx, span, impl_item); } fn create_derived_eq_impl(cx: ext_ctxt, @@ -310,11 +310,11 @@ fn create_iter_bytes_method(cx: ext_ctxt, let output_type = @ast::Ty { id: cx.next_id(), node: ty_nil, span: span }; // Create the function declaration. - let inputs = ~[ move lsb0_arg, move f_arg ]; - let fn_decl = build::mk_fn_decl(move inputs, output_type); + let inputs = ~[ lsb0_arg, f_arg ]; + let fn_decl = build::mk_fn_decl(inputs, output_type); // Create the body block. - let body_block = build::mk_block_(cx, span, move statements); + let body_block = build::mk_block_(cx, span, statements); // Create the method. let self_ty = spanned { node: sty_region(m_imm), span: span }; @@ -325,8 +325,8 @@ fn create_iter_bytes_method(cx: ext_ctxt, tps: ~[], self_ty: self_ty, purity: pure_fn, - decl: move fn_decl, - body: move body_block, + decl: fn_decl, + body: body_block, id: cx.next_id(), span: span, self_id: cx.next_id(), @@ -348,10 +348,10 @@ fn create_subpatterns(cx: ext_ctxt, // Create the subpattern. let subpath = build::mk_raw_path(span, ~[ ident ]); let subpat = pat_ident(bind_by_ref(m_imm), subpath, None); - let subpat = build::mk_pat(cx, span, move subpat); + let subpat = build::mk_pat(cx, span, subpat); subpats.push(subpat); } - return dvec::unwrap(move subpats); + return dvec::unwrap(subpats); } fn create_enum_variant_pattern(cx: ext_ctxt, @@ -373,7 +373,7 @@ fn create_enum_variant_pattern(cx: ext_ctxt, prefix, variant_args.len()); - return build::mk_pat_enum(cx, span, matching_path, move subpats); + return build::mk_pat_enum(cx, span, matching_path, subpats); } struct_variant_kind(struct_def) => { let matching_path = build::mk_raw_path(span, ~[ variant_ident ]); @@ -508,7 +508,7 @@ fn expand_deriving_eq_struct_def(cx: ext_ctxt, return create_derived_eq_impl(cx, span, type_ident, - move ty_params, + ty_params, eq_method, ne_method); } @@ -541,7 +541,7 @@ fn expand_deriving_eq_enum_def(cx: ext_ctxt, return create_derived_eq_impl(cx, span, type_ident, - move ty_params, + ty_params, eq_method, ne_method); } @@ -561,7 +561,7 @@ fn expand_deriving_iter_bytes_struct_def(cx: ext_ctxt, return create_derived_iter_bytes_impl(cx, span, type_ident, - move ty_params, + ty_params, method); } @@ -580,7 +580,7 @@ fn expand_deriving_iter_bytes_enum_def(cx: ext_ctxt, return create_derived_iter_bytes_impl(cx, span, type_ident, - move ty_params, + ty_params, method); } @@ -671,8 +671,8 @@ fn expand_deriving_iter_bytes_struct_method(cx: ext_ctxt, } // Create the method itself. - let statements = dvec::unwrap(move statements); - return create_iter_bytes_method(cx, span, move statements); + let statements = dvec::unwrap(statements); + return create_iter_bytes_method(cx, span, statements); } fn expand_deriving_eq_enum_method(cx: ext_ctxt, @@ -738,9 +738,9 @@ fn expand_deriving_eq_enum_method(cx: ext_ctxt, let matching_arm = ast::arm { pats: ~[ matching_pat ], guard: None, - body: move matching_body_block + body: matching_body_block }; - other_arms.push(move matching_arm); + other_arms.push(matching_arm); // Maybe generate a non-matching case. If there is only one // variant then there will always be a match. @@ -777,11 +777,11 @@ fn expand_deriving_eq_enum_method(cx: ext_ctxt, // Create the self pattern body. let other_expr = build::mk_path(cx, span, ~[ other_ident ]); let other_expr = build::mk_unary(cx, span, deref, other_expr); - let other_arms = dvec::unwrap(move other_arms); - let other_match_expr = expr_match(other_expr, move other_arms); + let other_arms = dvec::unwrap(other_arms); + let other_match_expr = expr_match(other_expr, other_arms); let other_match_expr = build::mk_expr(cx, span, - move other_match_expr); + other_match_expr); let other_match_body_block = build::mk_simple_block(cx, span, other_match_expr); @@ -792,15 +792,15 @@ fn expand_deriving_eq_enum_method(cx: ext_ctxt, guard: None, body: other_match_body_block, }; - self_arms.push(move self_arm); + self_arms.push(self_arm); } // Create the method body. let self_expr = build::mk_path(cx, span, ~[ self_ident ]); let self_expr = build::mk_unary(cx, span, deref, self_expr); - let self_arms = dvec::unwrap(move self_arms); - let self_match_expr = expr_match(self_expr, move self_arms); - let self_match_expr = build::mk_expr(cx, span, move self_match_expr); + let self_arms = dvec::unwrap(self_arms); + let self_match_expr = expr_match(self_expr, self_arms); + let self_match_expr = build::mk_expr(cx, span, self_match_expr); // Create the method. return create_eq_method(cx, @@ -848,8 +848,8 @@ fn expand_deriving_iter_bytes_enum_method(cx: ext_ctxt, } // Create the pattern body. - let stmts = dvec::unwrap(move stmts); - let match_body_block = build::mk_block_(cx, span, move stmts); + let stmts = dvec::unwrap(stmts); + let match_body_block = build::mk_block_(cx, span, stmts); // Create the arm. ast::arm { diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 17197f64c5556..85821ae6d8213 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -287,15 +287,6 @@ pub fn core_macros() -> ~str { macro_rules! debug ( ($( $arg:expr ),+) => ( log(::core::debug, fmt!( $($arg),+ )) )) - macro_rules! die( - ($msg: expr) => ( - ::core::sys::begin_unwind($msg, file!().to_owned(), line!()) - ); - () => ( - fail!(~\"explicit failure\") - ) - ) - macro_rules! fail( ($msg: expr) => ( ::core::sys::begin_unwind($msg, file!().to_owned(), line!()) diff --git a/src/libsyntax/ext/pipes/ast_builder.rs b/src/libsyntax/ext/pipes/ast_builder.rs index 58ab05987a600..12e5f1891aa82 100644 --- a/src/libsyntax/ext/pipes/ast_builder.rs +++ b/src/libsyntax/ext/pipes/ast_builder.rs @@ -54,7 +54,7 @@ pub trait append_types { fn add_tys(+tys: ~[@ast::Ty]) -> @ast::path; } -pub impl @ast::path: append_types { +pub impl append_types for @ast::path { fn add_ty(ty: @ast::Ty) -> @ast::path { @ast::path { types: vec::append_one(self.types, ty), .. *self} @@ -112,7 +112,7 @@ pub trait ext_ctxt_ast_builder { fn strip_bounds(bounds: &[ast::ty_param]) -> ~[ast::ty_param]; } -pub impl ext_ctxt: ext_ctxt_ast_builder { +pub impl ext_ctxt_ast_builder for ext_ctxt { fn ty_option(ty: @ast::Ty) -> @ast::Ty { self.ty_path_ast_builder(path_global(~[ self.ident_of(~"core"), diff --git a/src/libsyntax/ext/pipes/check.rs b/src/libsyntax/ext/pipes/check.rs index cde6a581dced0..a8e0b3ba934df 100644 --- a/src/libsyntax/ext/pipes/check.rs +++ b/src/libsyntax/ext/pipes/check.rs @@ -37,7 +37,7 @@ use ext::base::ext_ctxt; use ext::pipes::proto::{state, protocol, next_state}; use ext::pipes::proto; -pub impl ext_ctxt: proto::visitor<(), (), ()> { +pub impl proto::visitor<(), (), ()> for ext_ctxt { fn visit_proto(_proto: protocol, _states: &[()]) { } diff --git a/src/libsyntax/ext/pipes/liveness.rs b/src/libsyntax/ext/pipes/liveness.rs index b0a8f49c7a243..c690c89c025f2 100644 --- a/src/libsyntax/ext/pipes/liveness.rs +++ b/src/libsyntax/ext/pipes/liveness.rs @@ -53,7 +53,7 @@ pub fn analyze(proto: protocol, _cx: ext_ctxt) { for state.reachable |s| { bv.set(s.id, true); } - move bv + bv }; let mut i = 0; diff --git a/src/libsyntax/ext/pipes/parse_proto.rs b/src/libsyntax/ext/pipes/parse_proto.rs index 6a1708b8e2b51..875610474703e 100644 --- a/src/libsyntax/ext/pipes/parse_proto.rs +++ b/src/libsyntax/ext/pipes/parse_proto.rs @@ -22,7 +22,7 @@ pub trait proto_parser { fn parse_message(state: state); } -pub impl parser::Parser: proto_parser { +pub impl proto_parser for parser::Parser { fn parse_proto(id: ~str) -> protocol { let proto = protocol(id, self.span); diff --git a/src/libsyntax/ext/pipes/pipec.rs b/src/libsyntax/ext/pipes/pipec.rs index da0ac4e08ab06..68d18a2937c43 100644 --- a/src/libsyntax/ext/pipes/pipec.rs +++ b/src/libsyntax/ext/pipes/pipec.rs @@ -45,7 +45,7 @@ pub trait gen_init { fn gen_init_bounded(ext_cx: ext_ctxt) -> @ast::expr; } -pub impl message: gen_send { +pub impl gen_send for message { fn gen_send(cx: ext_ctxt, try: bool) -> @ast::item { debug!("pipec: gen_send"); match self { @@ -73,10 +73,10 @@ pub impl message: gen_send { if this.proto.is_bounded() { let (sp, rp) = match (this.dir, next.dir) { - (send, send) => (~"move c", ~"move s"), + (send, send) => (~"c", ~"s"), (send, recv) => (~"s", ~"c"), (recv, send) => (~"s", ~"c"), - (recv, recv) => (~"move c", ~"move s") + (recv, recv) => (~"c", ~"s") }; body += ~"let b = pipe.reuse_buffer();\n"; @@ -89,10 +89,10 @@ pub impl message: gen_send { } else { let pat = match (this.dir, next.dir) { - (send, send) => "(move c, move s)", + (send, send) => "(c, s)", (send, recv) => "(s, c)", (recv, send) => "(s, c)", - (recv, recv) => "(move c, move s)" + (recv, recv) => "(c, s)" }; body += fmt!("let %s = ::pipes::entangle();\n", pat); @@ -100,17 +100,17 @@ pub impl message: gen_send { body += fmt!("let message = %s(%s);\n", self.name(), str::connect(vec::append_one( - arg_names.map(|x| ~"move " + cx.str_of(*x)), - ~"move s"), ~", ")); + arg_names.map(|x| cx.str_of(*x)), + ~"s"), ~", ")); if !try { - body += fmt!("::pipes::send(move pipe, move message);\n"); + body += fmt!("::pipes::send(pipe, message);\n"); // return the new channel - body += ~"move c }"; + body += ~"c }"; } else { - body += fmt!("if ::pipes::send(move pipe, move message) {\n \ - ::pipes::rt::make_some(move c) \ + body += fmt!("if ::pipes::send(pipe, message) {\n \ + ::pipes::rt::make_some(c) \ } else { ::pipes::rt::make_none() } }"); } @@ -153,7 +153,7 @@ pub impl message: gen_send { ~"" } else { - ~"(" + str::connect(arg_names.map(|x| ~"move " + *x), + ~"(" + str::connect(arg_names.map(|x| *x), ~", ") + ~")" }; @@ -164,10 +164,10 @@ pub impl message: gen_send { message_args); if !try { - body += fmt!("::pipes::send(move pipe, move message);\n"); + body += fmt!("::pipes::send(pipe, message);\n"); body += ~" }"; } else { - body += fmt!("if ::pipes::send(move pipe, move message) \ + body += fmt!("if ::pipes::send(pipe, message) \ { \ ::pipes::rt::make_some(()) \ } else { \ @@ -201,7 +201,7 @@ pub impl message: gen_send { } } -pub impl state: to_type_decls { +pub impl to_type_decls for state { fn to_type_decls(cx: ext_ctxt) -> ~[@ast::item] { debug!("pipec: to_type_decls"); // This compiles into two different type declarations. Say the @@ -305,8 +305,7 @@ pub impl state: to_type_decls { } } -pub impl protocol: gen_init { - +pub impl gen_init for protocol { fn gen_init(cx: ext_ctxt) -> @ast::item { let ext_cx = cx; @@ -319,7 +318,7 @@ pub impl protocol: gen_init { recv => { quote_expr!({ let (s, c) = ::pipes::entangle(); - (move c, move s) + (c, s) }) } } @@ -331,7 +330,7 @@ pub impl protocol: gen_init { recv => { quote_expr!({ let (s, c) = $body; - (move c, move s) + (c, s) }) } } @@ -375,7 +374,7 @@ pub impl protocol: gen_init { quote_expr!({ let buffer = $buffer; - do ::pipes::entangle_buffer(move buffer) |buffer, data| { + do ::pipes::entangle_buffer(buffer) |buffer, data| { $entangle_body } }) diff --git a/src/libsyntax/ext/pipes/proto.rs b/src/libsyntax/ext/pipes/proto.rs index 6a1d93576941d..027375b6326bf 100644 --- a/src/libsyntax/ext/pipes/proto.rs +++ b/src/libsyntax/ext/pipes/proto.rs @@ -21,7 +21,7 @@ use core::to_str::ToStr; pub enum direction { send, recv } -pub impl direction : cmp::Eq { +pub impl cmp::Eq for direction { pure fn eq(&self, other: &direction) -> bool { match ((*self), (*other)) { (send, send) => true, @@ -33,7 +33,7 @@ pub impl direction : cmp::Eq { pure fn ne(&self, other: &direction) -> bool { !(*self).eq(other) } } -pub impl direction: ToStr { +pub impl ToStr for direction { pure fn to_str(&self) -> ~str { match *self { send => ~"Send", @@ -156,7 +156,6 @@ pub struct protocol_ { } pub impl protocol_ { - /// Get a state. fn get_state(name: ~str) -> state { self.states.find(|i| i.name == name).get() @@ -207,7 +206,7 @@ pub impl protocol { span: self.span, dir: dir, ty_params: ty_params, - messages: move messages, + messages: messages, proto: self }); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 9e89e703c09bb..df10f15c709cb 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -279,7 +279,7 @@ pub fn parse(sess: parse_sess, } new_pos.idx += 1; - cur_eis.push(move new_pos); + cur_eis.push(new_pos); } // can we go around again? @@ -288,19 +288,19 @@ pub fn parse(sess: parse_sess, match copy ei.sep { Some(ref t) if idx == len => { // we need a separator if tok == (*t) { //pass the separator - let ei_t = move ei; + let ei_t = ei; ei_t.idx += 1; - next_eis.push(move ei_t); + next_eis.push(ei_t); } } _ => { // we don't need a separator - let ei_t = move ei; + let ei_t = ei; ei_t.idx = 0; - cur_eis.push(move ei_t); + cur_eis.push(ei_t); } } } else { - eof_eis.push(move ei); + eof_eis.push(ei); } } else { match copy ei.elts[idx].node { @@ -315,26 +315,26 @@ pub fn parse(sess: parse_sess, new_ei.matches[idx].push(@matched_seq(~[], sp)); } - cur_eis.push(move new_ei); + cur_eis.push(new_ei); } let matches = vec::map(ei.matches, // fresh, same size: |_m| DVec::<@named_match>()); - let ei_t = move ei; + let ei_t = ei; cur_eis.push(~{ elts: (*matchers), sep: (*sep), mut idx: 0u, - mut up: matcher_pos_up(Some(move ei_t)), - matches: move matches, + mut up: matcher_pos_up(Some(ei_t)), + matches: matches, match_lo: match_idx_lo, match_hi: match_idx_hi, sp_lo: sp.lo }); } - match_nonterminal(_,_,_) => { bb_eis.push(move ei) } + match_nonterminal(_,_,_) => { bb_eis.push(ei) } match_tok(ref t) => { - let ei_t = move ei; + let ei_t = ei; if (*t) == tok { ei_t.idx += 1; - next_eis.push(move ei_t); + next_eis.push(ei_t); } } } @@ -388,7 +388,7 @@ pub fn parse(sess: parse_sess, } _ => fail!() } - cur_eis.push(move ei); + cur_eis.push(ei); for rust_parser.tokens_consumed.times() || { rdr.next_token(); diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 8cecbfb12101e..dc5d7916c7eee 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -252,7 +252,7 @@ pub fn noop_fold_item_underscore(i: item_, fld: ast_fold) -> item_ { }; item_trait(fold_ty_params(tps, fld), vec::map(traits, |p| fold_trait_ref(*p, fld)), - move methods) + methods) } item_mac(ref m) => { // FIXME #2888: we might actually want to do something here. @@ -692,7 +692,7 @@ pub fn default_ast_fold() -> ast_fold_fns { new_span: noop_span}; } -pub impl ast_fold_fns: ast_fold { +pub impl ast_fold for ast_fold_fns { /* naturally, a macro to write these would be nice */ fn fold_crate(c: crate) -> crate { let (n, s) = (self.fold_crate)(c.node, c.span, self as ast_fold); diff --git a/src/libsyntax/parse/comments.rs b/src/libsyntax/parse/comments.rs index 2cadf195778a2..d58d894b6a0af 100644 --- a/src/libsyntax/parse/comments.rs +++ b/src/libsyntax/parse/comments.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -15,6 +15,7 @@ use codemap::{BytePos, CharPos, CodeMap, FileMap, Pos}; use diagnostic; use parse::lexer::{is_whitespace, get_str_from, reader}; use parse::lexer::{StringReader, bump, is_eof, nextch, TokenAndSpan}; +use parse::lexer::{is_line_non_doc_comment, is_block_non_doc_comment}; use parse::lexer; use parse::token; use parse; @@ -46,9 +47,9 @@ impl cmp::Eq for cmnt_style { pub type cmnt = {style: cmnt_style, lines: ~[~str], pos: BytePos}; pub fn is_doc_comment(s: ~str) -> bool { - s.starts_with(~"///") || + (s.starts_with(~"///") && !is_line_non_doc_comment(s)) || s.starts_with(~"//!") || - s.starts_with(~"/**") || + (s.starts_with(~"/**") && !is_block_non_doc_comment(s)) || s.starts_with(~"/*!") } @@ -231,47 +232,56 @@ fn read_block_comment(rdr: @mut StringReader, bump(rdr); bump(rdr); + let mut curr_line = ~"/*"; + // doc-comments are not really comments, they are attributes if rdr.curr == '*' || rdr.curr == '!' { while !(rdr.curr == '*' && nextch(rdr) == '/') && !is_eof(rdr) { + str::push_char(&mut curr_line, rdr.curr); bump(rdr); } if !is_eof(rdr) { + curr_line += ~"*/"; bump(rdr); bump(rdr); } - return; - } - - let mut curr_line = ~"/*"; - let mut level: int = 1; - while level > 0 { - debug!("=== block comment level %d", level); - if is_eof(rdr) {(rdr as reader).fatal(~"unterminated block comment");} - if rdr.curr == '\n' { - trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); - curr_line = ~""; - bump(rdr); - } else { - str::push_char(&mut curr_line, rdr.curr); - if rdr.curr == '/' && nextch(rdr) == '*' { - bump(rdr); + if !is_block_non_doc_comment(curr_line) { return; } + assert !curr_line.contains_char('\n'); + lines.push(curr_line); + } else { + let mut level: int = 1; + while level > 0 { + debug!("=== block comment level %d", level); + if is_eof(rdr) { + (rdr as reader).fatal(~"unterminated block comment"); + } + if rdr.curr == '\n' { + trim_whitespace_prefix_and_push_line(&mut lines, curr_line, + col); + curr_line = ~""; bump(rdr); - curr_line += ~"*"; - level += 1; } else { - if rdr.curr == '*' && nextch(rdr) == '/' { + str::push_char(&mut curr_line, rdr.curr); + if rdr.curr == '/' && nextch(rdr) == '*' { bump(rdr); bump(rdr); - curr_line += ~"/"; - level -= 1; - } else { bump(rdr); } + curr_line += ~"*"; + level += 1; + } else { + if rdr.curr == '*' && nextch(rdr) == '/' { + bump(rdr); + bump(rdr); + curr_line += ~"/"; + level -= 1; + } else { bump(rdr); } + } } } + if str::len(curr_line) != 0 { + trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); + } } - if str::len(curr_line) != 0 { - trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); - } + let mut style = if code_to_the_left { trailing } else { isolated }; consume_non_eol_whitespace(rdr); if !is_eof(rdr) && rdr.curr != '\n' && vec::len(lines) == 1u { diff --git a/src/libsyntax/parse/lexer.rs b/src/libsyntax/parse/lexer.rs index f5fbefdd89b4b..92c4f1e828f62 100644 --- a/src/libsyntax/parse/lexer.rs +++ b/src/libsyntax/parse/lexer.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -127,7 +127,7 @@ impl reader for StringReader { fn dup(@mut self) -> reader { dup_string_reader(self) as reader } } -pub impl TtReader: reader { +pub impl reader for TtReader { fn is_eof(@mut self) -> bool { self.cur_tok == token::EOF } fn next_token(@mut self) -> TokenAndSpan { tt_next_token(self) } fn fatal(@mut self, m: ~str) -> ! { @@ -253,6 +253,10 @@ fn consume_whitespace_and_comments(rdr: @mut StringReader) return consume_any_line_comment(rdr); } +pub pure fn is_line_non_doc_comment(s: &str) -> bool { + s.trim_right().all(|ch| ch == '/') +} + // PRECONDITION: rdr.curr is not whitespace // EFFECT: eats any kind of comment. // returns a Some(sugared-doc-attr) if one exists, None otherwise @@ -271,15 +275,18 @@ fn consume_any_line_comment(rdr: @mut StringReader) str::push_char(&mut acc, rdr.curr); bump(rdr); } - return Some(TokenAndSpan{ - tok: token::DOC_COMMENT(rdr.interner.intern(@acc)), - sp: codemap::mk_sp(start_bpos, rdr.pos) - }); + // but comments with only "/"s are not + if !is_line_non_doc_comment(acc) { + return Some(TokenAndSpan{ + tok: token::DOC_COMMENT(rdr.interner.intern(@acc)), + sp: codemap::mk_sp(start_bpos, rdr.pos) + }); + } } else { while rdr.curr != '\n' && !is_eof(rdr) { bump(rdr); } - // Restart whitespace munch. - return consume_whitespace_and_comments(rdr); } + // Restart whitespace munch. + return consume_whitespace_and_comments(rdr); } '*' => { bump(rdr); bump(rdr); return consume_block_comment(rdr); } _ => () @@ -298,6 +305,11 @@ fn consume_any_line_comment(rdr: @mut StringReader) return None; } +pub pure fn is_block_non_doc_comment(s: &str) -> bool { + assert s.len() >= 1u; + str::all_between(s, 1u, s.len() - 1u, |ch| ch == '*') +} + // might return a sugared-doc-attr fn consume_block_comment(rdr: @mut StringReader) -> Option { @@ -315,10 +327,13 @@ fn consume_block_comment(rdr: @mut StringReader) acc += ~"*/"; bump(rdr); bump(rdr); - return Some(TokenAndSpan{ - tok: token::DOC_COMMENT(rdr.interner.intern(@acc)), - sp: codemap::mk_sp(start_bpos, rdr.pos) - }); + // but comments with only "*"s between two "/"s are not + if !is_block_non_doc_comment(acc) { + return Some(TokenAndSpan{ + tok: token::DOC_COMMENT(rdr.interner.intern(@acc)), + sp: codemap::mk_sp(start_bpos, rdr.pos) + }); + } } } else { loop { diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 12038898a9d1c..82c1697bf72b0 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -151,7 +151,7 @@ pub fn parse_from_source_str(f: fn (p: Parser) -> T, p.reader.fatal(~"expected end-of-string"); } p.abort_if_errors(); - move r + r } pub fn next_node_id(sess: parse_sess) -> node_id { @@ -177,16 +177,16 @@ pub fn new_parser_from_file(sess: parse_sess, path: &Path) -> Result { match io::read_whole_file_str(path) { - result::Ok(move src) => { + result::Ok(src) => { - let filemap = sess.cm.new_filemap(path.to_str(), @move src); + let filemap = sess.cm.new_filemap(path.to_str(), @src); let srdr = lexer::new_string_reader(sess.span_diagnostic, filemap, sess.interner); Ok(Parser(sess, cfg, srdr as reader)) } - result::Err(move e) => Err(move e) + result::Err(e) => Err(e) } } @@ -195,8 +195,8 @@ pub fn new_parser_from_file(sess: parse_sess, pub fn new_crate_parser_from_file(sess: parse_sess, cfg: ast::crate_cfg, path: &Path) -> Parser { match new_parser_from_file(sess, cfg, path) { - Ok(move parser) => move parser, - Err(move e) => { + Ok(parser) => parser, + Err(e) => { sess.span_diagnostic.handler().fatal(e) } } @@ -207,8 +207,8 @@ pub fn new_crate_parser_from_file(sess: parse_sess, cfg: ast::crate_cfg, pub fn new_sub_parser_from_file(sess: parse_sess, cfg: ast::crate_cfg, path: &Path, sp: span) -> Parser { match new_parser_from_file(sess, cfg, path) { - Ok(move parser) => move parser, - Err(move e) => { + Ok(parser) => parser, + Err(e) => { sess.span_diagnostic.span_fatal(sp, e) } } @@ -227,12 +227,11 @@ mod test { use super::*; use std::serialize::Encodable; use std; - use core::dvec; use core::str; use util::testing::*; #[test] fn to_json_str (val: Encodable) -> ~str { - let bw = @io::BytesWriter {bytes: dvec::DVec(), pos: 0}; + let bw = @io::BytesWriter(); val.encode(~std::json::Encoder(bw as io::Writer)); str::from_bytes(bw.bytes.data) } diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 1b4493b7ec9af..bf04996838cf8 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -45,10 +45,11 @@ pub enum ObsoleteSyntax { ObsoleteMoveInit, ObsoleteBinaryMove, ObsoleteUnsafeBlock, - ObsoleteUnenforcedBound + ObsoleteUnenforcedBound, + ObsoleteImplSyntax } -pub impl ObsoleteSyntax: to_bytes::IterBytes { +pub impl to_bytes::IterBytes for ObsoleteSyntax { #[inline(always)] pure fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { (*self as uint).iter_bytes(lsb0, f); @@ -115,6 +116,10 @@ pub impl Parser { "unenforced type parameter bound", "use trait bounds on the functions that take the type as \ arguments, not on the types themselves" + ), + ObsoleteImplSyntax => ( + "colon-separated impl syntax", + "write `impl Trait for Type`" ) }; diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 41ccf39e2cee1..799f0d40a4617 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -74,7 +74,7 @@ use parse::obsolete::{ObsoleteLet, ObsoleteFieldTerminator}; use parse::obsolete::{ObsoleteMoveInit, ObsoleteBinaryMove}; use parse::obsolete::{ObsoleteStructCtor, ObsoleteWith}; use parse::obsolete::{ObsoleteSyntax, ObsoleteLowerCaseKindBounds}; -use parse::obsolete::{ObsoleteUnsafeBlock}; +use parse::obsolete::{ObsoleteUnsafeBlock, ObsoleteImplSyntax}; use parse::prec::{as_prec, token_to_binop}; use parse::token::{can_begin_expr, is_ident, is_ident_or_path}; use parse::token::{is_plain_ident, INTERPOLATED, special_idents}; @@ -84,8 +84,6 @@ use print::pprust::expr_to_str; use util::interner::Interner; use core::cmp; -use core::dvec::DVec; -use core::dvec; use core::either::{Either, Left, Right}; use core::either; use core::result::Result; @@ -192,8 +190,8 @@ pub fn Parser(sess: parse_sess let interner = rdr.interner(); Parser { - reader: move rdr, - interner: move interner, + reader: rdr, + interner: interner, sess: sess, cfg: cfg, token: tok0.tok, @@ -309,12 +307,12 @@ pub impl Parser { { /* - extern "ABI" [pure|unsafe] fn (S) -> T - ^~~~^ ^~~~~~~~~~~~^ ^~^ ^ - | | | | - | | | Return type - | | Argument types - | | + extern "ABI" [pure|unsafe] fn <'lt> (S) -> T + ^~~~^ ^~~~~~~~~~~~^ ^~~~^ ^~^ ^ + | | | | | + | | | | Return type + | | | Argument types + | | Lifetimes | | | Purity ABI @@ -335,12 +333,12 @@ pub impl Parser { { /* - (&|~|@) [r/] [pure|unsafe] [once] fn (S) -> T - ^~~~~~^ ^~~^ ^~~~~~~~~~~~^ ^~~~~^ ^~^ ^ - | | | | | | - | | | | | Return type - | | | | Argument types - | | | | + (&|~|@) [r/] [pure|unsafe] [once] fn <'lt> (S) -> T + ^~~~~~^ ^~~^ ^~~~~~~~~~~~^ ^~~~~^ ^~~~^ ^~^ ^ + | | | | | | | + | | | | | | Return type + | | | | | Argument types + | | | | Lifetimes | | | Once-ness (a.k.a., affine) | | Purity | Lifetime bound @@ -396,12 +394,24 @@ pub impl Parser { } fn parse_ty_fn_decl() -> fn_decl { - let inputs = do self.parse_unspanned_seq( - token::LPAREN, token::RPAREN, - seq_sep_trailing_disallowed(token::COMMA)) |p| { + /* - p.parse_arg_general(false) - }; + (fn) <'lt> (S) -> T + ^~~~^ ^~^ ^ + | | | + | | Return type + | Argument types + Lifetimes + + */ + if self.eat(token::LT) { + let _lifetimes = self.parse_lifetimes(); + self.expect(token::GT); + } + let inputs = self.parse_unspanned_seq( + token::LPAREN, token::RPAREN, + seq_sep_trailing_disallowed(token::COMMA), + |p| p.parse_arg_general(false)); let (ret_style, ret_ty) = self.parse_ret_ty(); ast::fn_decl { inputs: inputs, output: ret_ty, cf: ret_style } } @@ -626,8 +636,13 @@ pub impl Parser { sigil: ast::Sigil, ctor: &fn(+v: mt) -> ty_) -> ty_ { - // @foo/fn() or @fn() are parsed directly as fn types: + // @'foo fn() or @foo/fn() or @fn() are parsed directly as fn types: match copy self.token { + token::LIFETIME(rname) => { + self.bump(); + return self.parse_ty_closure(Some(sigil), Some(rname)); + } + token::IDENT(rname, _) => { if self.look_ahead(1u) == token::BINOP(token::SLASH) && self.token_is_closure_keyword(self.look_ahead(2u)) @@ -650,8 +665,13 @@ pub impl Parser { } fn parse_borrowed_pointee() -> ty_ { - // look for `&foo/` and interpret `foo` as the region name: - let rname = match copy self.token { + // look for `&'lt` or `&foo/` and interpret `foo` as the region name: + let rname = match self.token { + token::LIFETIME(sid) => { + self.bump(); + Some(sid) + } + token::IDENT(sid, _) => { if self.look_ahead(1u) == token::BINOP(token::SLASH) { self.bump(); self.bump(); @@ -660,6 +680,7 @@ pub impl Parser { None } } + _ => { None } }; @@ -714,7 +735,7 @@ pub impl Parser { fn parse_capture_item_or(parse_arg_fn: fn(Parser) -> arg_or_capture_item) -> arg_or_capture_item { - if self.eat_keyword(~"move") || self.eat_keyword(~"copy") { + if self.eat_keyword(~"copy") { // XXX outdated syntax now that moves-based-on-type has gone in self.parse_ident(); either::Right(()) @@ -892,22 +913,95 @@ pub impl Parser { } }; - // Parse any type parameters which may appear: + // Parse any lifetime or type parameters which may appear: let tps = { - if self.token == token::LT { - self.parse_seq_lt_gt(Some(token::COMMA), - |p| p.parse_ty(false)) + if !self.eat(token::LT) { + ~[] } else { - codemap::spanned {node: ~[], span: path.span} + // First consume lifetimes. + let _lifetimes = self.parse_lifetimes(); + let result = self.parse_seq_to_gt( + Some(token::COMMA), + |p| p.parse_ty(false)); + result } }; - @ast::path { span: mk_sp(lo, tps.span.hi), + let hi = self.span.lo; + + @ast::path { span: mk_sp(lo, hi), rp: rp, - types: tps.node, + types: tps, .. *path } } + fn parse_opt_lifetime() -> Option { + /*! + * + * Parses 0 or 1 lifetime. + */ + + match self.token { + token::LIFETIME(_) => { + Some(self.parse_lifetime()) + } + _ => { + None + } + } + } + + fn parse_lifetime() -> ast::Lifetime { + /*! + * + * Parses a single lifetime. + */ + + match self.token { + token::LIFETIME(i) => { + self.bump(); + return ast::Lifetime { + id: self.get_id(), + span: self.span, + ident: i + }; + } + _ => { + self.fatal(fmt!("Expected a lifetime name")); + } + } + } + + fn parse_lifetimes() -> ~[ast::Lifetime] { + /*! + * + * Parses zero or more comma separated lifetimes. + * Expects each lifetime to be followed by either + * a comma or `>`. Used when parsing type parameter + * lists, where we expect something like `<'a, 'b, T>`. + */ + + let mut res = ~[]; + loop { + match self.token { + token::LIFETIME(_) => { + res.push(self.parse_lifetime()); + } + _ => { + return res; + } + } + + match self.token { + token::COMMA => { self.bump();} + token::GT => { return res; } + _ => { + self.fatal(~"expected `,` or `>` after lifetime name"); + } + } + } + } + fn parse_mutability() -> mutability { if self.eat_keyword(~"mut") { m_mutbl @@ -1085,9 +1179,6 @@ pub impl Parser { let e = self.parse_expr(); ex = expr_copy(e); hi = e.span.hi; - } else if self.eat_keyword(~"move") { - // XXX move keyword is no longer important, remove after snapshot - return self.parse_expr(); } else if self.token == token::MOD_SEP || is_ident(self.token) && !self.is_keyword(~"true") && !self.is_keyword(~"false") { @@ -1199,7 +1290,7 @@ pub impl Parser { hi = self.span.hi; let nd = expr_method_call(e, i, tys, es, NoSugar); - e = self.mk_expr(lo, hi, move nd); + e = self.mk_expr(lo, hi, nd); } _ => { e = self.mk_expr(lo, hi, expr_field(e, i, tys)); @@ -1323,11 +1414,11 @@ pub impl Parser { } fn parse_all_token_trees() -> ~[token_tree] { - let tts = DVec(); + let mut tts = ~[]; while self.token != token::EOF { tts.push(self.parse_token_tree()); } - tts.get() + tts } fn parse_matchers() -> ~[matcher] { @@ -1429,6 +1520,7 @@ pub impl Parser { } token::AND => { self.bump(); + let _lt = self.parse_opt_lifetime(); let m = self.parse_mutability(); let e = self.parse_prefix_expr(); hi = e.span.hi; @@ -2101,10 +2193,6 @@ pub impl Parser { } else if self.eat_keyword(~"copy") { pat = self.parse_pat_ident(refutable, bind_by_copy); } else { - if self.eat_keyword(~"move") { - /* XXX---remove move keyword */ - } - // XXX---refutable match bindings should work same as let let binding_mode = if refutable {bind_infer} else {bind_by_copy}; @@ -2374,7 +2462,7 @@ pub impl Parser { self.obsolete(copy self.span, ObsoleteUnsafeBlock); } self.expect(token::LBRACE); - let {inner: move inner, next: move next} = + let {inner: inner, next: next} = maybe_parse_inner_attrs_and_next(self, parse_attrs); return (inner, self.parse_block_tail_(lo, default_blk, next)); } @@ -2399,8 +2487,8 @@ pub impl Parser { let mut stmts = ~[]; let mut expr = None; - let {attrs_remaining: move attrs_remaining, - view_items: move view_items, + let {attrs_remaining: attrs_remaining, + view_items: view_items, items: items, _} = self.parse_items_and_view_items(first_item_attrs, IMPORTS_AND_ITEMS_ALLOWED, false); @@ -2572,7 +2660,7 @@ pub impl Parser { } } } - return @move bounds; + return @bounds; } fn parse_ty_param() -> ty_param { @@ -2583,7 +2671,10 @@ pub impl Parser { fn parse_ty_params() -> ~[ty_param] { if self.eat(token::LT) { - self.parse_seq_to_gt(Some(token::COMMA), |p| p.parse_ty_param()) + let _lifetimes = self.parse_lifetimes(); + self.parse_seq_to_gt( + Some(token::COMMA), + |p| p.parse_ty_param()) } else { ~[] } } @@ -2838,16 +2929,11 @@ pub impl Parser { // XXX: clownshoes let ident = special_idents::clownshoes_extensions; - // Parse the type. (If this is `impl trait for type`, however, this - // actually parses the trait.) + // Parse the trait. let mut ty = self.parse_ty(false); // Parse traits, if necessary. - let opt_trait = if self.token == token::COLON { - // Old-style trait. - self.bump(); - Some(self.parse_trait_ref()) - } else if self.eat_keyword(~"for") { + let opt_trait = if self.eat_keyword(~"for") { // New-style trait. Reinterpret the type as a trait. let opt_trait_ref = match ty.node { ty_path(path, node_id) => { @@ -2864,6 +2950,9 @@ pub impl Parser { ty = self.parse_ty(false); opt_trait_ref + } else if self.eat(token::COLON) { + self.obsolete(copy self.span, ObsoleteImplSyntax); + Some(self.parse_trait_ref()) } else { None }; @@ -3085,13 +3174,13 @@ pub impl Parser { fn parse_mod_items(term: token::Token, +first_item_attrs: ~[attribute]) -> _mod { // Shouldn't be any view items since we've already parsed an item attr - let {attrs_remaining: move attrs_remaining, - view_items: move view_items, + let {attrs_remaining: attrs_remaining, + view_items: view_items, items: starting_items, _} = self.parse_items_and_view_items(first_item_attrs, VIEW_ITEMS_AND_ITEMS_ALLOWED, true); - let mut items: ~[@item] = move starting_items; + let mut items: ~[@item] = starting_items; let mut first = true; while self.token != term { @@ -3142,7 +3231,7 @@ pub impl Parser { self.bump(); // This mod is in an external file. Let's go get it! let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span); - (id, m, Some(move attrs)) + (id, m, Some(attrs)) } else { self.push_mod_path(id, outer_attrs); self.expect(token::LBRACE); @@ -3302,9 +3391,9 @@ pub impl Parser { fn parse_foreign_item(+attrs: ~[attribute]) -> @foreign_item { let vis = self.parse_visibility(); if self.is_keyword(~"const") { - self.parse_item_foreign_const(vis, move attrs) + self.parse_item_foreign_const(vis, attrs) } else { - self.parse_item_foreign_fn( move attrs) + self.parse_item_foreign_fn(attrs) } } @@ -3313,15 +3402,15 @@ pub impl Parser { +first_item_attrs: ~[attribute]) -> foreign_mod { // Shouldn't be any view items since we've already parsed an item attr - let {attrs_remaining: move attrs_remaining, - view_items: move view_items, + let {attrs_remaining: attrs_remaining, + view_items: view_items, items: _, - foreign_items: move foreign_items} = + foreign_items: foreign_items} = self.parse_items_and_view_items(first_item_attrs, VIEW_ITEMS_AND_FOREIGN_ITEMS_ALLOWED, true); - let mut items: ~[@foreign_item] = move foreign_items; + let mut items: ~[@foreign_item] = foreign_items; let mut initial_attrs = attrs_remaining; while self.token != token::RBRACE { let attrs = vec::append(initial_attrs, @@ -3331,7 +3420,7 @@ pub impl Parser { } ast::foreign_mod { sort: sort, - abi: move abi, + abi: abi, view_items: view_items, items: items } @@ -3384,14 +3473,14 @@ pub impl Parser { // extern mod { ... } if items_allowed && self.eat(token::LBRACE) { let abi; - match move abi_opt { - Some(move found_abi) => abi = move found_abi, + match abi_opt { + Some(found_abi) => abi = found_abi, None => abi = special_idents::c_abi, } let extra_attrs = self.parse_inner_attrs_and_next(); let m = self.parse_foreign_mod_items(sort, - move abi, + abi, extra_attrs.next); self.expect(token::RBRACE); @@ -3515,7 +3604,7 @@ pub impl Parser { ident = self.parse_ident(); self.expect(token::LBRACE); let nested_enum_def = self.parse_enum_def(ty_params); - kind = enum_variant_kind(move nested_enum_def); + kind = enum_variant_kind(nested_enum_def); needs_comma = false; } else { ident = self.parse_value_ident(); @@ -3954,7 +4043,7 @@ pub impl Parser { VIEW_ITEMS_AND_ITEMS_ALLOWED | IMPORTS_AND_ITEMS_ALLOWED => false }; - let (view_items, items, foreign_items) = (DVec(), DVec(), DVec()); + let mut (view_items, items, foreign_items) = (~[], ~[], ~[]); loop { match self.parse_item_or_view_item(attrs, items_allowed, foreign_items_allowed, @@ -3986,9 +4075,9 @@ pub impl Parser { } {attrs_remaining: attrs, - view_items: dvec::unwrap(move view_items), - items: dvec::unwrap(move items), - foreign_items: dvec::unwrap(move foreign_items)} + view_items: view_items, + items: items, + foreign_items: foreign_items} } // Parses a source module as a crate diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 3279c79e5af0d..bdd26fc00a7dc 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -493,7 +493,7 @@ pub fn strict_keyword_table() -> HashMap<~str, ()> { ~"false", ~"fn", ~"for", ~"if", ~"impl", ~"let", ~"log", ~"loop", - ~"match", ~"mod", ~"move", ~"mut", + ~"match", ~"mod", ~"mut", ~"once", ~"priv", ~"pub", ~"pure", ~"ref", ~"return", diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index aeebcce1f2b27..a30447d968e1d 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -147,11 +147,11 @@ pub fn mk_printer(out: @io::Writer, linewidth: uint) -> @mut Printer { space: linewidth as int, left: 0, right: 0, - token: move token, - size: move size, + token: token, + size: size, left_total: 0, right_total: 0, - scan_stack: move scan_stack, + scan_stack: scan_stack, scan_stack_empty: true, top: 0, bottom: 0, diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 905571d181721..657e6ee59fa41 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -24,7 +24,7 @@ pub fn mk() -> Interner { let m = oldmap::HashMap::(); let hi: hash_interner = {map: m, vect: DVec()}; - move ((move hi) as Interner::) + ((hi) as Interner::) } pub fn mk_prefill(init: &[T]) -> Interner { @@ -42,7 +42,7 @@ pub trait Interner { fn len() -> uint; } -pub impl hash_interner: Interner { +pub impl Interner for hash_interner { fn intern(val: T) -> uint { match self.map.find(&val) { Some(idx) => return idx, diff --git a/src/rt/memory_region.cpp b/src/rt/memory_region.cpp index 6307730b0f4b3..6de9d5a1df4a2 100644 --- a/src/rt/memory_region.cpp +++ b/src/rt/memory_region.cpp @@ -121,8 +121,10 @@ memory_region::realloc(void *mem, size_t orig_size) { } void * -memory_region::malloc(size_t size, const char *tag, bool zero) { +memory_region::malloc(size_t size, const char *tag) { +# if RUSTRT_TRACK_ALLOCATIONS >= 1 size_t old_size = size; +# endif size += HEADER_SIZE; alloc_header *mem = (alloc_header *)::malloc(size); if (mem == NULL) { @@ -143,18 +145,9 @@ memory_region::malloc(size_t size, const char *tag, bool zero) { void *data = get_data(mem); claim_alloc(data); - if(zero) { - memset(data, 0, old_size); - } - return data; } -void * -memory_region::calloc(size_t size, const char *tag) { - return malloc(size, tag, true); -} - memory_region::~memory_region() { if (_synchronized) { _lock.lock(); } if (_live_allocations == 0 && !_detailed_leaks) { diff --git a/src/rt/memory_region.h b/src/rt/memory_region.h index 7a68a0f8af548..999a992eefaea 100644 --- a/src/rt/memory_region.h +++ b/src/rt/memory_region.h @@ -77,8 +77,7 @@ class memory_region { public: memory_region(rust_env *env, bool synchronized); memory_region(memory_region *parent); - void *malloc(size_t size, const char *tag, bool zero = true); - void *calloc(size_t size, const char *tag); + void *malloc(size_t size, const char *tag); void *realloc(void *mem, size_t size); void free(void *mem); ~memory_region(); diff --git a/src/rt/rust_builtin.cpp b/src/rt/rust_builtin.cpp index 3f6545caaa8e4..85caf7b2e5381 100644 --- a/src/rt/rust_builtin.cpp +++ b/src/rt/rust_builtin.cpp @@ -135,7 +135,7 @@ rand_seed() { rust_vec *v = (rust_vec *) task->kernel->malloc(vec_size(size), "rand_seed"); v->fill = v->alloc = size; - isaac_seed(task->kernel, (uint8_t*) &v->data, size); + rng_gen_seed(task->kernel, (uint8_t*) &v->data, size); return v; } @@ -143,27 +143,27 @@ extern "C" CDECL void * rand_new() { rust_task *task = rust_get_current_task(); rust_sched_loop *thread = task->sched_loop; - randctx *rctx = (randctx *) task->malloc(sizeof(randctx), "rand_new"); - if (!rctx) { + rust_rng *rng = (rust_rng *) task->malloc(sizeof(rust_rng), "rand_new"); + if (!rng) { task->fail(); return NULL; } - isaac_init(thread->kernel, rctx, NULL); - return rctx; + rng_init(thread->kernel, rng, NULL); + return rng; } extern "C" CDECL void * rand_new_seeded(rust_vec_box* seed) { rust_task *task = rust_get_current_task(); rust_sched_loop *thread = task->sched_loop; - randctx *rctx = (randctx *) task->malloc(sizeof(randctx), - "rand_new_seeded"); - if (!rctx) { + rust_rng *rng = (rust_rng *) task->malloc(sizeof(rust_rng), + "rand_new_seeded"); + if (!rng) { task->fail(); return NULL; } - isaac_init(thread->kernel, rctx, seed); - return rctx; + rng_init(thread->kernel, rng, seed); + return rng; } extern "C" CDECL void * @@ -171,15 +171,16 @@ rand_new_seeded2(rust_vec_box** seed) { return rand_new_seeded(*seed); } -extern "C" CDECL size_t -rand_next(randctx *rctx) { - return isaac_rand(rctx); +extern "C" CDECL uint32_t +rand_next(rust_rng *rng) { + rust_task *task = rust_get_current_task(); + return rng_gen_u32(task->kernel, rng); } extern "C" CDECL void -rand_free(randctx *rctx) { +rand_free(rust_rng *rng) { rust_task *task = rust_get_current_task(); - task->free(rctx); + task->free(rng); } diff --git a/src/rt/rust_exchange_alloc.cpp b/src/rt/rust_exchange_alloc.cpp index 6c0204ca73611..a92bc4edd411a 100644 --- a/src/rt/rust_exchange_alloc.cpp +++ b/src/rt/rust_exchange_alloc.cpp @@ -18,23 +18,15 @@ uintptr_t exchange_count = 0; void * -rust_exchange_alloc::malloc(size_t size, bool zero) { +rust_exchange_alloc::malloc(size_t size) { void *value = ::malloc(size); assert(value); - if (zero) { - memset(value, 0, size); - } sync::increment(exchange_count); return value; } -void * -rust_exchange_alloc::calloc(size_t size) { - return this->malloc(size); -} - void * rust_exchange_alloc::realloc(void *ptr, size_t size) { void *new_ptr = ::realloc(ptr, size); diff --git a/src/rt/rust_exchange_alloc.h b/src/rt/rust_exchange_alloc.h index 1b52929acf1b7..767caf0132345 100644 --- a/src/rt/rust_exchange_alloc.h +++ b/src/rt/rust_exchange_alloc.h @@ -16,8 +16,7 @@ class rust_exchange_alloc { public: - void *malloc(size_t size, bool zero = true); - void *calloc(size_t size); + void *malloc(size_t size); void *realloc(void *mem, size_t size); void free(void *mem); }; diff --git a/src/rt/rust_globals.h b/src/rt/rust_globals.h index d0116fe27813d..3d3ce7562b5ed 100644 --- a/src/rt/rust_globals.h +++ b/src/rt/rust_globals.h @@ -37,9 +37,6 @@ #include #include -#include "rand.h" -#include "uthash.h" - #if defined(__WIN32__) extern "C" { #include diff --git a/src/rt/rust_kernel.cpp b/src/rt/rust_kernel.cpp index 6b7a82414161c..4d2d6ad344cc9 100644 --- a/src/rt/rust_kernel.cpp +++ b/src/rt/rust_kernel.cpp @@ -79,11 +79,6 @@ rust_kernel::malloc(size_t size, const char *tag) { return exchange_alloc.malloc(size); } -void * -rust_kernel::calloc(size_t size, const char *tag) { - return exchange_alloc.calloc(size); -} - void * rust_kernel::realloc(void *mem, size_t size) { return exchange_alloc.realloc(mem, size); diff --git a/src/rt/rust_kernel.h b/src/rt/rust_kernel.h index 01ebf5ab57b95..ec0515faeafc0 100644 --- a/src/rt/rust_kernel.h +++ b/src/rt/rust_kernel.h @@ -49,7 +49,6 @@ #include "rust_log.h" #include "rust_sched_reaper.h" #include "rust_type.h" -#include "util/hash_map.h" #include "sync/lock_and_signal.h" class rust_scheduler; @@ -133,7 +132,6 @@ class rust_kernel { void fatal(char const *fmt, ...); void *malloc(size_t size, const char *tag); - void *calloc(size_t size, const char *tag); void *realloc(void *mem, size_t size); void free(void *mem); rust_exchange_alloc *region() { return &exchange_alloc; } diff --git a/src/rt/rust_rng.cpp b/src/rt/rust_rng.cpp new file mode 100644 index 0000000000000..3d6bfdf7dbb1f --- /dev/null +++ b/src/rt/rust_rng.cpp @@ -0,0 +1,115 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#include "rust_globals.h" +#include "rust_rng.h" +#include "rust_util.h" + +// Initialization helpers for ISAAC RNG + +void +rng_gen_seed(rust_kernel* kernel, uint8_t* dest, size_t size) { +#ifdef __WIN32__ + HCRYPTPROV hProv; + kernel->win32_require + (_T("CryptAcquireContext"), + CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT|CRYPT_SILENT)); + kernel->win32_require + (_T("CryptGenRandom"), CryptGenRandom(hProv, size, (BYTE*) dest)); + kernel->win32_require + (_T("CryptReleaseContext"), CryptReleaseContext(hProv, 0)); +#else + int fd = open("/dev/urandom", O_RDONLY); + if (fd == -1) + kernel->fatal("error opening /dev/urandom: %s", strerror(errno)); + size_t amount = 0; + do { + ssize_t ret = read(fd, dest+amount, size-amount); + if (ret < 0) + kernel->fatal("error reading /dev/urandom: %s", strerror(errno)); + else if (ret == 0) + kernel->fatal("somehow hit eof reading from /dev/urandom"); + amount += (size_t)ret; + } while (amount < size); + int ret = close(fd); + // FIXME #3697: Why does this fail sometimes? + if (ret != 0) + kernel->log(log_warn, "error closing /dev/urandom: %s", + strerror(errno)); +#endif +} + +static void +isaac_init(rust_kernel *kernel, randctx *rctx, rust_vec_box* user_seed) { + memset(rctx, 0, sizeof(randctx)); + + char *env_seed = kernel->env->rust_seed; + if (user_seed != NULL) { + // ignore bytes after the required length + size_t seed_len = user_seed->body.fill < sizeof(rctx->randrsl) + ? user_seed->body.fill : sizeof(rctx->randrsl); + memcpy(&rctx->randrsl, user_seed->body.data, seed_len); + } else if (env_seed != NULL) { + ub4 seed = (ub4) atoi(env_seed); + for (size_t i = 0; i < RANDSIZ; i ++) { + memcpy(&rctx->randrsl[i], &seed, sizeof(ub4)); + seed = (seed + 0x7ed55d16) + (seed << 12); + } + } else { + rng_gen_seed(kernel, (uint8_t*)&rctx->randrsl, sizeof(rctx->randrsl)); + } + + randinit(rctx, 1); +} + +void +rng_init(rust_kernel* kernel, rust_rng* rng, rust_vec_box* user_seed) { + isaac_init(kernel, &rng->rctx, user_seed); + rng->reseedable = !user_seed && !kernel->env->rust_seed; +} + +static void +rng_maybe_reseed(rust_kernel* kernel, rust_rng* rng) { + // If this RNG has generated more than 32KB of random data and was not + // seeded by the user or RUST_SEED, then we should reseed now. + const size_t RESEED_THRESHOLD = 32 * 1024; + size_t bytes_generated = rng->rctx.randc * sizeof(ub4); + if (bytes_generated < RESEED_THRESHOLD || !rng->reseedable) { + return; + } + + uint32_t new_seed[RANDSIZ]; + rng_gen_seed(kernel, (uint8_t*) new_seed, RANDSIZ * sizeof(uint32_t)); + + // Stir new seed into PRNG's entropy pool. + for (size_t i = 0; i < RANDSIZ; i++) { + rng->rctx.randrsl[i] ^= new_seed[i]; + } + + randinit(&rng->rctx, 1); +} + +uint32_t +rng_gen_u32(rust_kernel* kernel, rust_rng* rng) { + uint32_t x = isaac_rand(&rng->rctx); + rng_maybe_reseed(kernel, rng); + return x; +} + +// +// Local Variables: +// mode: C++ +// fill-column: 78; +// indent-tabs-mode: nil +// c-basic-offset: 4 +// buffer-file-coding-system: utf-8-unix +// End: +// diff --git a/src/rt/rust_rng.h b/src/rt/rust_rng.h new file mode 100644 index 0000000000000..2f1e680623feb --- /dev/null +++ b/src/rt/rust_rng.h @@ -0,0 +1,40 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#ifndef RUST_RNG_H +#define RUST_RNG_H + +#include "rand.h" + +class rust_kernel; +struct rust_vec_box; + +// Initialization helpers for ISAAC RNG + +struct rust_rng { + randctx rctx; + bool reseedable; +}; + +void rng_gen_seed(rust_kernel* kernel, uint8_t* dest, size_t size); +void rng_init(rust_kernel *kernel, rust_rng *rng, rust_vec_box* user_seed); +uint32_t rng_gen_u32(rust_kernel *kernel, rust_rng *rng); + +// +// Local Variables: +// mode: C++ +// fill-column: 78; +// indent-tabs-mode: nil +// c-basic-offset: 4 +// buffer-file-coding-system: utf-8-unix +// End: +// + +#endif diff --git a/src/rt/rust_sched_loop.cpp b/src/rt/rust_sched_loop.cpp index 0d0eaaee9628e..7143bf88d46bd 100644 --- a/src/rt/rust_sched_loop.cpp +++ b/src/rt/rust_sched_loop.cpp @@ -41,7 +41,7 @@ rust_sched_loop::rust_sched_loop(rust_scheduler *sched, int id, bool killed) : name("main") { LOGPTR(this, "new dom", (uintptr_t)this); - isaac_init(kernel, &rctx, NULL); + rng_init(kernel, &rng, NULL); if (!tls_initialized) init_tls(); @@ -150,10 +150,10 @@ rust_sched_loop::release_task(rust_task *task) { rust_task * rust_sched_loop::schedule_task() { lock.must_have_lock(); - if (running_tasks.length() > 0) { - size_t k = isaac_rand(&rctx); - size_t i = k % running_tasks.length(); - return (rust_task *)running_tasks[i]; + size_t tasks = running_tasks.length(); + if (tasks > 0) { + size_t i = (tasks > 1) ? (rng_gen_u32(kernel, &rng) % tasks) : 0; + return running_tasks[i]; } return NULL; } diff --git a/src/rt/rust_sched_loop.h b/src/rt/rust_sched_loop.h index 0105b83e28b45..736c09ee920ca 100644 --- a/src/rt/rust_sched_loop.h +++ b/src/rt/rust_sched_loop.h @@ -13,6 +13,7 @@ #include "rust_globals.h" #include "rust_log.h" +#include "rust_rng.h" #include "rust_stack.h" #include "rust_signal.h" #include "context.h" @@ -61,7 +62,7 @@ struct rust_sched_loop #endif context c_context; - + rust_rng rng; bool should_exit; stk_seg *cached_c_stack; @@ -102,7 +103,6 @@ struct rust_sched_loop size_t min_stack_size; memory_region local_region; - randctx rctx; const char *const name; // Used for debugging // Only a pointer to 'name' is kept, so it must live as long as this diff --git a/src/rt/rust_stack.cpp b/src/rt/rust_stack.cpp index 3bcda8adf4024..64ca256ff4611 100644 --- a/src/rt/rust_stack.cpp +++ b/src/rt/rust_stack.cpp @@ -58,7 +58,7 @@ check_stack_canary(stk_seg *stk) { stk_seg * create_stack(memory_region *region, size_t sz) { size_t total_sz = sizeof(stk_seg) + sz; - stk_seg *stk = (stk_seg *)region->malloc(total_sz, "stack", false); + stk_seg *stk = (stk_seg *)region->malloc(total_sz, "stack"); memset(stk, 0, sizeof(stk_seg)); stk->end = (uintptr_t) &stk->data[sz]; add_stack_canary(stk); @@ -75,7 +75,7 @@ destroy_stack(memory_region *region, stk_seg *stk) { stk_seg * create_exchange_stack(rust_exchange_alloc *exchange, size_t sz) { size_t total_sz = sizeof(stk_seg) + sz; - stk_seg *stk = (stk_seg *)exchange->malloc(total_sz, false); + stk_seg *stk = (stk_seg *)exchange->malloc(total_sz); memset(stk, 0, sizeof(stk_seg)); stk->end = (uintptr_t) &stk->data[sz]; add_stack_canary(stk); diff --git a/src/rt/rust_task.cpp b/src/rt/rust_task.cpp index e51af464e488a..63dc1c9833e21 100644 --- a/src/rt/rust_task.cpp +++ b/src/rt/rust_task.cpp @@ -450,11 +450,6 @@ rust_task::backtrace() { #endif } -void * -rust_task::calloc(size_t size, const char *tag) { - return local_region.calloc(size, tag); -} - size_t rust_task::get_next_stack_size(size_t min, size_t current, size_t requested) { LOG(this, mem, "calculating new stack size for 0x%" PRIxPTR, this); diff --git a/src/rt/rust_util.h b/src/rt/rust_util.h index 4b0d87880ef9e..0385804a77871 100644 --- a/src/rt/rust_util.h +++ b/src/rt/rust_util.h @@ -19,21 +19,6 @@ extern struct type_desc str_body_tydesc; // Inline fn used regularly elsewhere. -static inline size_t -next_power_of_two(size_t s) -{ - size_t tmp = s - 1; - tmp |= tmp >> 1; - tmp |= tmp >> 2; - tmp |= tmp >> 4; - tmp |= tmp >> 8; - tmp |= tmp >> 16; -#ifdef _LP64 - tmp |= tmp >> 32; -#endif - return tmp + 1; -} - // Rounds |size| to the nearest |alignment|. Invariant: |alignment| is a power // of two. template @@ -91,10 +76,6 @@ inline void reserve_vec_exact(rust_task* task, rust_vec_box** vpp, } } -inline void reserve_vec(rust_task* task, rust_vec_box** vpp, size_t size) { - reserve_vec_exact(task, vpp, next_power_of_two(size)); -} - typedef rust_vec_box rust_str; inline rust_str * @@ -136,65 +117,6 @@ inline size_t get_box_size(size_t body_size, size_t body_align) { return total_size; } -// Initialization helpers for ISAAC RNG - -inline void isaac_seed(rust_kernel* kernel, uint8_t* dest, size_t size) -{ -#ifdef __WIN32__ - HCRYPTPROV hProv; - kernel->win32_require - (_T("CryptAcquireContext"), - CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, - CRYPT_VERIFYCONTEXT|CRYPT_SILENT)); - kernel->win32_require - (_T("CryptGenRandom"), CryptGenRandom(hProv, size, (BYTE*) dest)); - kernel->win32_require - (_T("CryptReleaseContext"), CryptReleaseContext(hProv, 0)); -#else - int fd = open("/dev/urandom", O_RDONLY); - if (fd == -1) - kernel->fatal("error opening /dev/urandom: %s", strerror(errno)); - size_t amount = 0; - do { - ssize_t ret = read(fd, dest+amount, size-amount); - if (ret < 0) - kernel->fatal("error reading /dev/urandom: %s", strerror(errno)); - else if (ret == 0) - kernel->fatal("somehow hit eof reading from /dev/urandom"); - amount += (size_t)ret; - } while (amount < size); - int ret = close(fd); - // FIXME #3697: Why does this fail sometimes? - if (ret != 0) - kernel->log(log_warn, "error closing /dev/urandom: %s", - strerror(errno)); -#endif -} - -inline void -isaac_init(rust_kernel *kernel, randctx *rctx, rust_vec_box* user_seed) -{ - memset(rctx, 0, sizeof(randctx)); - - char *env_seed = kernel->env->rust_seed; - if (user_seed != NULL) { - // ignore bytes after the required length - size_t seed_len = user_seed->body.fill < sizeof(rctx->randrsl) - ? user_seed->body.fill : sizeof(rctx->randrsl); - memcpy(&rctx->randrsl, user_seed->body.data, seed_len); - } else if (env_seed != NULL) { - ub4 seed = (ub4) atoi(env_seed); - for (size_t i = 0; i < RANDSIZ; i ++) { - memcpy(&rctx->randrsl[i], &seed, sizeof(ub4)); - seed = (seed + 0x7ed55d16) + (seed << 12); - } - } else { - isaac_seed(kernel, (uint8_t*) &rctx->randrsl, sizeof(rctx->randrsl)); - } - - randinit(rctx, 1); -} - // // Local Variables: // mode: C++ diff --git a/src/rt/uthash/uthash.h b/src/rt/uthash/uthash.h deleted file mode 100644 index 28021b6161191..0000000000000 --- a/src/rt/uthash/uthash.h +++ /dev/null @@ -1,766 +0,0 @@ -/* -Copyright (c) 2003-2009, Troy D. Hanson http://uthash.sourceforge.net -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef UTHASH_H -#define UTHASH_H - -#include /* memcmp,strlen */ -#include /* ptrdiff_t */ -#include /* uint32_t etc */ - -#define UTHASH_VERSION 1.6 - -/* C++ requires extra stringent casting */ -#if defined __cplusplus -#define TYPEOF(x) (typeof(x)) -#else -#define TYPEOF(x) -#endif - - -#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ -#define uthash_bkt_malloc(sz) malloc(sz) /* malloc fcn for UT_hash_bucket's */ -#define uthash_bkt_free(ptr) free(ptr) /* free fcn for UT_hash_bucket's */ -#define uthash_tbl_malloc(sz) malloc(sz) /* malloc fcn for UT_hash_table */ -#define uthash_tbl_free(ptr) free(ptr) /* free fcn for UT_hash_table */ - -#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ -#define uthash_expand_fyi(tbl) /* can be defined to log expands */ - -/* initial number of buckets */ -#define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ -#define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of buckets */ -#define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ - -/* calculate the element whose hash handle address is hhe */ -#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)hhp) - (tbl)->hho)) - -#define HASH_FIND(hh,head,keyptr,keylen,out) \ -do { \ - unsigned _hf_bkt,_hf_hashv; \ - out=TYPEOF(out)head; \ - if (head) { \ - HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ - HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ - keyptr,keylen,out); \ - } \ -} while (0) - -#define HASH_MAKE_TABLE(hh,head) \ -do { \ - (head)->hh.tbl = (UT_hash_table*)uthash_tbl_malloc( \ - sizeof(UT_hash_table)); \ - if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ - memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ - (head)->hh.tbl->tail = &((head)->hh); \ - (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ - (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ - (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ - (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_bkt_malloc( \ - HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ - if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ - memset((head)->hh.tbl->buckets, 0, \ - HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ -} while(0) - -#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ - HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add) - -#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ -do { \ - unsigned _ha_bkt; \ - (add)->hh.next = NULL; \ - (add)->hh.key = (char*)keyptr; \ - (add)->hh.keylen = keylen_in; \ - if (!(head)) { \ - head = (add); \ - (head)->hh.prev = NULL; \ - HASH_MAKE_TABLE(hh,head); \ - } else { \ - (head)->hh.tbl->tail->next = (add); \ - (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ - (head)->hh.tbl->tail = &((add)->hh); \ - } \ - (head)->hh.tbl->num_items++; \ - (add)->hh.tbl = (head)->hh.tbl; \ - HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ - (add)->hh.hashv, _ha_bkt); \ - HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ - HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ - HASH_FSCK(hh,head); \ -} while(0) - -#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ -do { \ - bkt = ((hashv) & ((num_bkts) - 1)); \ -} while(0) - -/* delete "delptr" from the hash table. - * "the usual" patch-up process for the app-order doubly-linked-list. - * The use of _hd_hh_del below deserves special explanation. - * These used to be expressed using (delptr) but that led to a bug - * if someone used the same symbol for the head and deletee, like - * HASH_DELETE(hh,users,users); - * We want that to work, but by changing the head (users) below - * we were forfeiting our ability to further refer to the deletee (users) - * in the patch-up process. Solution: use scratch space in the table to - * copy the deletee pointer, then the latter references are via that - * scratch pointer rather than through the repointed (users) symbol. - */ -#define HASH_DELETE(hh,head,delptr) \ -do { \ - unsigned _hd_bkt; \ - struct UT_hash_handle *_hd_hh_del; \ - if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ - uthash_bkt_free((head)->hh.tbl->buckets ); \ - uthash_tbl_free((head)->hh.tbl); \ - head = NULL; \ - } else { \ - _hd_hh_del = &((delptr)->hh); \ - if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ - (head)->hh.tbl->tail = \ - (UT_hash_handle*)((char*)((delptr)->hh.prev) + \ - (head)->hh.tbl->hho); \ - } \ - if ((delptr)->hh.prev) { \ - ((UT_hash_handle*)((char*)((delptr)->hh.prev) + \ - (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ - } else { \ - head = TYPEOF(head)((delptr)->hh.next); \ - } \ - if (_hd_hh_del->next) { \ - ((UT_hash_handle*)((char*)_hd_hh_del->next + \ - (head)->hh.tbl->hho))->prev = \ - _hd_hh_del->prev; \ - } \ - HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ - HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ - (head)->hh.tbl->num_items--; \ - } \ - HASH_FSCK(hh,head); \ -} while (0) - - -/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ -#define HASH_FIND_STR(head,findstr,out) \ - HASH_FIND(hh,head,findstr,strlen(findstr),out) -#define HASH_ADD_STR(head,strfield,add) \ - HASH_ADD(hh,head,strfield,strlen(add->strfield),add) -#define HASH_FIND_INT(head,findint,out) \ - HASH_FIND(hh,head,findint,sizeof(int),out) -#define HASH_ADD_INT(head,intfield,add) \ - HASH_ADD(hh,head,intfield,sizeof(int),add) -#define HASH_DEL(head,delptr) \ - HASH_DELETE(hh,head,delptr) - -/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. - * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. - */ -#ifdef HASH_DEBUG -#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) -#define HASH_FSCK(hh,head) \ -do { \ - unsigned _bkt_i; \ - unsigned _count, _bkt_count; \ - char *_prev; \ - struct UT_hash_handle *_thh; \ - if (head) { \ - _count = 0; \ - for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ - _bkt_count = 0; \ - _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ - _prev = NULL; \ - while (_thh) { \ - if (_prev != (char*)(_thh->hh_prev)) { \ - HASH_OOPS("invalid hh_prev %p, actual %p\n", \ - _thh->hh_prev, _prev ); \ - } \ - _bkt_count++; \ - _prev = (char*)(_thh); \ - _thh = _thh->hh_next; \ - } \ - _count += _bkt_count; \ - if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ - HASH_OOPS("invalid bucket count %d, actual %d\n", \ - (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ - } \ - } \ - if (_count != (head)->hh.tbl->num_items) { \ - HASH_OOPS("invalid hh item count %d, actual %d\n", \ - (head)->hh.tbl->num_items, _count ); \ - } \ - /* traverse hh in app order; check next/prev integrity, count */ \ - _count = 0; \ - _prev = NULL; \ - _thh = &(head)->hh; \ - while (_thh) { \ - _count++; \ - if (_prev !=(char*)(_thh->prev)) { \ - HASH_OOPS("invalid prev %p, actual %p\n", \ - _thh->prev, _prev ); \ - } \ - _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ - _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ - (head)->hh.tbl->hho) : NULL ); \ - } \ - if (_count != (head)->hh.tbl->num_items) { \ - HASH_OOPS("invalid app item count %d, actual %d\n", \ - (head)->hh.tbl->num_items, _count ); \ - } \ - } \ -} while (0) -#else -#define HASH_FSCK(hh,head) -#endif - -/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to - * the descriptor to which this macro is defined for tuning the hash function. - * The app can #include to get the prototype for write(2). */ -#ifdef HASH_EMIT_KEYS -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ -do { \ - unsigned _klen = fieldlen; \ - write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ - write(HASH_EMIT_KEYS, keyptr, fieldlen); \ -} while (0) -#else -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) -#endif - -/* default to MurmurHash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ -#ifdef HASH_FUNCTION -#define HASH_FCN HASH_FUNCTION -#else -#define HASH_FCN HASH_MUR -#endif - -/* The Bernstein hash function, used in Perl prior to v5.6 */ -#define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _hb_keylen=keylen; \ - char *_hb_key=(char*)key; \ - (hashv) = 0; \ - while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ - bkt = (hashv) & (num_bkts-1); \ -} while (0) - - -/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at - * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ -#define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _sx_i; \ - char *_hs_key=(char*)key; \ - hashv = 0; \ - for(_sx_i=0; _sx_i < keylen; _sx_i++) \ - hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ - bkt = hashv & (num_bkts-1); \ -} while (0) - -#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _fn_i; \ - char *_hf_key=(char*)key; \ - hashv = 2166136261UL; \ - for(_fn_i=0; _fn_i < keylen; _fn_i++) \ - hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ - bkt = hashv & (num_bkts-1); \ -} while(0); - -#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _ho_i; \ - char *_ho_key=(char*)key; \ - hashv = 0; \ - for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ - hashv += _ho_key[_ho_i]; \ - hashv += (hashv << 10); \ - hashv ^= (hashv >> 6); \ - } \ - hashv += (hashv << 3); \ - hashv ^= (hashv >> 11); \ - hashv += (hashv << 15); \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -#define HASH_JEN_MIX(a,b,c) \ -do { \ - a -= b; a -= c; a ^= ( c >> 13 ); \ - b -= c; b -= a; b ^= ( a << 8 ); \ - c -= a; c -= b; c ^= ( b >> 13 ); \ - a -= b; a -= c; a ^= ( c >> 12 ); \ - b -= c; b -= a; b ^= ( a << 16 ); \ - c -= a; c -= b; c ^= ( b >> 5 ); \ - a -= b; a -= c; a ^= ( c >> 3 ); \ - b -= c; b -= a; b ^= ( a << 10 ); \ - c -= a; c -= b; c ^= ( b >> 15 ); \ -} while (0) - -#define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _hj_i,_hj_j,_hj_k; \ - char *_hj_key=(char*)key; \ - hashv = 0xfeedbeef; \ - _hj_i = _hj_j = 0x9e3779b9; \ - _hj_k = keylen; \ - while (_hj_k >= 12) { \ - _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ - + ( (unsigned)_hj_key[2] << 16 ) \ - + ( (unsigned)_hj_key[3] << 24 ) ); \ - _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ - + ( (unsigned)_hj_key[6] << 16 ) \ - + ( (unsigned)_hj_key[7] << 24 ) ); \ - hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ - + ( (unsigned)_hj_key[10] << 16 ) \ - + ( (unsigned)_hj_key[11] << 24 ) ); \ - \ - HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ - \ - _hj_key += 12; \ - _hj_k -= 12; \ - } \ - hashv += keylen; \ - switch ( _hj_k ) { \ - case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ - case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ - case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ - case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ - case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ - case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ - case 5: _hj_j += _hj_key[4]; \ - case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ - case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ - case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ - case 1: _hj_i += _hj_key[0]; \ - } \ - HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -/* The Paul Hsieh hash function */ -#undef get16bits -#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ - || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) -#define get16bits(d) (*((const uint16_t *) (d))) -#endif - -#if !defined (get16bits) -#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\ - +(uint32_t)(((const uint8_t *)(d))[0]) ) -#endif -#define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ -do { \ - char *_sfh_key=(char*)key; \ - hashv = 0xcafebabe; \ - uint32_t _sfh_tmp, _sfh_len = keylen; \ - \ - int _sfh_rem = _sfh_len & 3; \ - _sfh_len >>= 2; \ - \ - /* Main loop */ \ - for (;_sfh_len > 0; _sfh_len--) { \ - hashv += get16bits (_sfh_key); \ - _sfh_tmp = (get16bits (_sfh_key+2) << 11) ^ hashv; \ - hashv = (hashv << 16) ^ _sfh_tmp; \ - _sfh_key += 2*sizeof (uint16_t); \ - hashv += hashv >> 11; \ - } \ - \ - /* Handle end cases */ \ - switch (_sfh_rem) { \ - case 3: hashv += get16bits (_sfh_key); \ - hashv ^= hashv << 16; \ - hashv ^= _sfh_key[sizeof (uint16_t)] << 18; \ - hashv += hashv >> 11; \ - break; \ - case 2: hashv += get16bits (_sfh_key); \ - hashv ^= hashv << 11; \ - hashv += hashv >> 17; \ - break; \ - case 1: hashv += *_sfh_key; \ - hashv ^= hashv << 10; \ - hashv += hashv >> 1; \ - } \ - \ - /* Force "avalanching" of final 127 bits */ \ - hashv ^= hashv << 3; \ - hashv += hashv >> 5; \ - hashv ^= hashv << 4; \ - hashv += hashv >> 17; \ - hashv ^= hashv << 25; \ - hashv += hashv >> 6; \ - bkt = hashv & (num_bkts-1); \ -} while(0); - -/* Austin Appleby's MurmurHash */ -#define HASH_MUR(key,keylen,num_bkts,hashv,bkt) \ -do { \ - const unsigned int _mur_m = 0x5bd1e995; \ - const int _mur_r = 24; \ - hashv = 0xcafebabe ^ keylen; \ - char *_mur_key = (char *)key; \ - uint32_t _mur_tmp, _mur_len = keylen; \ - \ - for (;_mur_len >= 4; _mur_len-=4) { \ - _mur_tmp = *(uint32_t *)_mur_key; \ - _mur_tmp *= _mur_m; \ - _mur_tmp ^= _mur_tmp >> _mur_r; \ - _mur_tmp *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_tmp; \ - _mur_key += 4; \ - } \ - \ - switch(_mur_len) \ - { \ - case 3: hashv ^= _mur_key[2] << 16; \ - case 2: hashv ^= _mur_key[1] << 8; \ - case 1: hashv ^= _mur_key[0]; \ - hashv *= _mur_m; \ - }; \ - \ - hashv ^= hashv >> 13; \ - hashv *= _mur_m; \ - hashv ^= hashv >> 15; \ - \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -/* key comparison function; return 0 if keys equal */ -#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) - -/* iterate over items in a known bucket to find desired item */ -#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ -out = TYPEOF(out)((head.hh_head) ? ELMT_FROM_HH(tbl,head.hh_head) : NULL); \ -while (out) { \ - if (out->hh.keylen == keylen_in) { \ - if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break; \ - } \ - out= TYPEOF(out)((out->hh.hh_next) ? \ - ELMT_FROM_HH(tbl,out->hh.hh_next) : NULL); \ -} - -/* add an item to a bucket */ -#define HASH_ADD_TO_BKT(head,addhh) \ -do { \ - head.count++; \ - (addhh)->hh_next = head.hh_head; \ - (addhh)->hh_prev = NULL; \ - if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ - (head).hh_head=addhh; \ - if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ - && (addhh)->tbl->noexpand != 1) { \ - HASH_EXPAND_BUCKETS((addhh)->tbl); \ - } \ -} while(0) - -/* remove an item from a given bucket */ -#define HASH_DEL_IN_BKT(hh,head,hh_del) \ - (head).count--; \ - if ((head).hh_head == hh_del) { \ - (head).hh_head = hh_del->hh_next; \ - } \ - if (hh_del->hh_prev) { \ - hh_del->hh_prev->hh_next = hh_del->hh_next; \ - } \ - if (hh_del->hh_next) { \ - hh_del->hh_next->hh_prev = hh_del->hh_prev; \ - } - -/* Bucket expansion has the effect of doubling the number of buckets - * and redistributing the items into the new buckets. Ideally the - * items will distribute more or less evenly into the new buckets - * (the extent to which this is true is a measure of the quality of - * the hash function as it applies to the key domain). - * - * With the items distributed into more buckets, the chain length - * (item count) in each bucket is reduced. Thus by expanding buckets - * the hash keeps a bound on the chain length. This bounded chain - * length is the essence of how a hash provides constant time lookup. - * - * The calculation of tbl->ideal_chain_maxlen below deserves some - * explanation. First, keep in mind that we're calculating the ideal - * maximum chain length based on the *new* (doubled) bucket count. - * In fractions this is just n/b (n=number of items,b=new num buckets). - * Since the ideal chain length is an integer, we want to calculate - * ceil(n/b). We don't depend on floating point arithmetic in this - * hash, so to calculate ceil(n/b) with integers we could write - * - * ceil(n/b) = (n/b) + ((n%b)?1:0) - * - * and in fact a previous version of this hash did just that. - * But now we have improved things a bit by recognizing that b is - * always a power of two. We keep its base 2 log handy (call it lb), - * so now we can write this with a bit shift and logical AND: - * - * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) - * - */ -#define HASH_EXPAND_BUCKETS(tbl) \ -do { \ - unsigned _he_bkt; \ - unsigned _he_bkt_i; \ - struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ - UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ - _he_new_buckets = (UT_hash_bucket*)uthash_bkt_malloc( \ - 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ - if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ - memset(_he_new_buckets, 0, \ - 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ - tbl->ideal_chain_maxlen = \ - (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ - ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ - tbl->nonideal_items = 0; \ - for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ - { \ - _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ - while (_he_thh) { \ - _he_hh_nxt = _he_thh->hh_next; \ - HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt); \ - _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ - if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ - tbl->nonideal_items++; \ - _he_newbkt->expand_mult = _he_newbkt->count / \ - tbl->ideal_chain_maxlen; \ - } \ - _he_thh->hh_prev = NULL; \ - _he_thh->hh_next = _he_newbkt->hh_head; \ - if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ - _he_thh; \ - _he_newbkt->hh_head = _he_thh; \ - _he_thh = _he_hh_nxt; \ - } \ - } \ - tbl->num_buckets *= 2; \ - tbl->log2_num_buckets++; \ - uthash_bkt_free( tbl->buckets ); \ - tbl->buckets = _he_new_buckets; \ - tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ - (tbl->ineff_expands+1) : 0; \ - if (tbl->ineff_expands > 1) { \ - tbl->noexpand=1; \ - uthash_noexpand_fyi(tbl); \ - } \ - uthash_expand_fyi(tbl); \ -} while(0) - - -/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ -/* Note that HASH_SORT assumes the hash handle name to be hh. - * HASH_SRT was added to allow the hash handle name to be passed in. */ -#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) -#define HASH_SRT(hh,head,cmpfcn) \ -do { \ - unsigned _hs_i; \ - unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ - struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ - if (head) { \ - _hs_insize = 1; \ - _hs_looping = 1; \ - _hs_list = &((head)->hh); \ - while (_hs_looping) { \ - _hs_p = _hs_list; \ - _hs_list = NULL; \ - _hs_tail = NULL; \ - _hs_nmerges = 0; \ - while (_hs_p) { \ - _hs_nmerges++; \ - _hs_q = _hs_p; \ - _hs_psize = 0; \ - for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ - _hs_psize++; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - if (! (_hs_q) ) break; \ - } \ - _hs_qsize = _hs_insize; \ - while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ - if (_hs_psize == 0) { \ - _hs_e = _hs_q; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_qsize--; \ - } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ - _hs_e = _hs_p; \ - _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ - ((void*)((char*)(_hs_p->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_psize--; \ - } else if (( \ - cmpfcn(TYPEOF(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ - TYPEOF(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ - ) <= 0) { \ - _hs_e = _hs_p; \ - _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ - ((void*)((char*)(_hs_p->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_psize--; \ - } else { \ - _hs_e = _hs_q; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_qsize--; \ - } \ - if ( _hs_tail ) { \ - _hs_tail->next = ((_hs_e) ? \ - ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ - } else { \ - _hs_list = _hs_e; \ - } \ - _hs_e->prev = ((_hs_tail) ? \ - ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ - _hs_tail = _hs_e; \ - } \ - _hs_p = _hs_q; \ - } \ - _hs_tail->next = NULL; \ - if ( _hs_nmerges <= 1 ) { \ - _hs_looping=0; \ - (head)->hh.tbl->tail = _hs_tail; \ - (head) = TYPEOF(head)ELMT_FROM_HH((head)->hh.tbl, _hs_list); \ - } \ - _hs_insize *= 2; \ - } \ - HASH_FSCK(hh,head); \ - } \ -} while (0) - -/* This function selects items from one hash into another hash. - * The end result is that the selected items have dual presence - * in both hashes. There is no copy of the items made; rather - * they are added into the new hash through a secondary hash - * hash handle that must be present in the structure. */ -#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ -do { \ - unsigned _src_bkt, _dst_bkt; \ - void *_last_elt=NULL, *_elt; \ - UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ - ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ - if (src) { \ - for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ - for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ - _src_hh; \ - _src_hh = _src_hh->hh_next) { \ - _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ - if (cond(_elt)) { \ - _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ - _dst_hh->key = _src_hh->key; \ - _dst_hh->keylen = _src_hh->keylen; \ - _dst_hh->hashv = _src_hh->hashv; \ - _dst_hh->prev = _last_elt; \ - _dst_hh->next = NULL; \ - if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ - if (!dst) { \ - dst = TYPEOF(dst)_elt; \ - HASH_MAKE_TABLE(hh_dst,dst); \ - } else { \ - _dst_hh->tbl = (dst)->hh_dst.tbl; \ - } \ - HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ - HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ - (dst)->hh_dst.tbl->num_items++; \ - _last_elt = _elt; \ - _last_elt_hh = _dst_hh; \ - } \ - } \ - } \ - } \ - HASH_FSCK(hh_dst,dst); \ -} while (0) - -#define HASH_CLEAR(hh,head) \ -do { \ - if (head) { \ - uthash_bkt_free((head)->hh.tbl->buckets ); \ - uthash_tbl_free((head)->hh.tbl); \ - (head)=NULL; \ - } \ -} while(0) - -/* obtain a count of items in the hash */ -#define HASH_COUNT(head) HASH_CNT(hh,head) -#define HASH_CNT(hh,head) (head?(head->hh.tbl->num_items):0) - -typedef struct UT_hash_bucket { - struct UT_hash_handle *hh_head; - unsigned count; - - /* expand_mult is normally set to 0. In this situation, the max chain length - * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If - * the bucket's chain exceeds this length, bucket expansion is triggered). - * However, setting expand_mult to a non-zero value delays bucket expansion - * (that would be triggered by additions to this particular bucket) - * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. - * (The multiplier is simply expand_mult+1). The whole idea of this - * multiplier is to reduce bucket expansions, since they are expensive, in - * situations where we know that a particular bucket tends to be overused. - * It is better to let its chain length grow to a longer yet-still-bounded - * value, than to do an O(n) bucket expansion too often. - */ - unsigned expand_mult; - -} UT_hash_bucket; - -typedef struct UT_hash_table { - UT_hash_bucket *buckets; - unsigned num_buckets, log2_num_buckets; - unsigned num_items; - struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ - ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ - - /* in an ideal situation (all buckets used equally), no bucket would have - * more than ceil(#items/#buckets) items. that's the ideal chain length. */ - unsigned ideal_chain_maxlen; - - /* nonideal_items is the number of items in the hash whose chain position - * exceeds the ideal chain maxlen. these items pay the penalty for an uneven - * hash distribution; reaching them in a chain traversal takes >ideal steps */ - unsigned nonideal_items; - - /* ineffective expands occur when a bucket doubling was performed, but - * afterward, more than half the items in the hash had nonideal chain - * positions. If this happens on two consecutive expansions we inhibit any - * further expansion, as it's not helping; this happens when the hash - * function isn't a good fit for the key domain. When expansion is inhibited - * the hash will still work, albeit no longer in constant time. */ - unsigned ineff_expands, noexpand; - - -} UT_hash_table; - - -typedef struct UT_hash_handle { - struct UT_hash_table *tbl; - void *prev; /* prev element in app order */ - void *next; /* next element in app order */ - struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ - struct UT_hash_handle *hh_next; /* next hh in bucket order */ - void *key; /* ptr to enclosing struct's key */ - unsigned keylen; /* enclosing struct's key len */ - unsigned hashv; /* result of hash-fcn(key) */ -} UT_hash_handle; - -#endif /* UTHASH_H */ diff --git a/src/rt/uthash/utlist.h b/src/rt/uthash/utlist.h deleted file mode 100644 index a33615e1ba054..0000000000000 --- a/src/rt/uthash/utlist.h +++ /dev/null @@ -1,280 +0,0 @@ -/* -Copyright (c) 2007-2009, Troy D. Hanson -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef UTLIST_H -#define UTLIST_H - -#define UTLIST_VERSION 1.0 - -/* C++ requires extra stringent casting */ -#if defined __cplusplus -#define LTYPEOF(x) (typeof(x)) -#else -#define LTYPEOF(x) -#endif -/* - * This file contains macros to manipulate singly and doubly-linked lists. - * - * 1. LL_ macros: singly-linked lists. - * 2. DL_ macros: doubly-linked lists. - * 3. CDL_ macros: circular doubly-linked lists. - * - * To use singly-linked lists, your structure must have a "next" pointer. - * To use doubly-linked lists, your structure must "prev" and "next" pointers. - * Either way, the pointer to the head of the list must be initialized to NULL. - * - * ----------------.EXAMPLE ------------------------- - * struct item { - * int id; - * struct item *prev, *next; - * } - * - * struct item *list = NULL: - * - * int main() { - * struct item *item; - * ... allocate and populate item ... - * DL_APPEND(list, item); - * } - * -------------------------------------------------- - * - * For doubly-linked lists, the append and delete macros are O(1) - * For singly-linked lists, append and delete are O(n) but prepend is O(1) - * The sort macro is O(n log(n)) for all types of single/double/circular lists. - */ - -/****************************************************************************** - * The SORT macros * - *****************************************************************************/ -#define LL_SORT(l,cmp) \ - LISTSORT(l,0,0,FIELD_OFFSET(l,next),cmp) -#define DL_SORT(l,cmp) \ - LISTSORT(l,0,FIELD_OFFSET(l,prev),FIELD_OFFSET(l,next),cmp) -#define CDL_SORT(l,cmp) \ - LISTSORT(l,1,FIELD_OFFSET(l,prev),FIELD_OFFSET(l,next),cmp) - -/* The macros can't assume or cast to the caller's list element type. So we use - * a couple tricks when we need to deal with those element's prev/next pointers. - * Basically we use char pointer arithmetic to get those field offsets. */ -#define FIELD_OFFSET(ptr,field) ((char*)&((ptr)->field) - (char*)(ptr)) -#define LNEXT(e,no) (*(char**)(((char*)e) + no)) -#define LPREV(e,po) (*(char**)(((char*)e) + po)) -/****************************************************************************** - * The LISTSORT macro is an adaptation of Simon Tatham's O(n log(n)) mergesort* - * Unwieldy variable names used here to avoid shadowing passed-in variables. * - *****************************************************************************/ -#define LISTSORT(list, is_circular, po, no, cmp) \ -do { \ - void *_ls_p, *_ls_q, *_ls_e, *_ls_tail, *_ls_oldhead; \ - int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ - int _ls_is_double = (po==0) ? 0 : 1; \ - if (list) { \ - _ls_insize = 1; \ - _ls_looping = 1; \ - while (_ls_looping) { \ - _ls_p = list; \ - _ls_oldhead = list; \ - list = NULL; \ - _ls_tail = NULL; \ - _ls_nmerges = 0; \ - while (_ls_p) { \ - _ls_nmerges++; \ - _ls_q = _ls_p; \ - _ls_psize = 0; \ - for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ - _ls_psize++; \ - if (is_circular) { \ - _ls_q = ((LNEXT(_ls_q,no) == _ls_oldhead) ? NULL : LNEXT(_ls_q,no)); \ - } else { \ - _ls_q = LNEXT(_ls_q,no); \ - } \ - if (!_ls_q) break; \ - } \ - _ls_qsize = _ls_insize; \ - while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ - if (_ls_psize == 0) { \ - _ls_e = _ls_q; _ls_q = LNEXT(_ls_q,no); _ls_qsize--; \ - if (is_circular && _ls_q == _ls_oldhead) { _ls_q = NULL; } \ - } else if (_ls_qsize == 0 || !_ls_q) { \ - _ls_e = _ls_p; _ls_p = LNEXT(_ls_p,no); _ls_psize--; \ - if (is_circular && (_ls_p == _ls_oldhead)) { _ls_p = NULL; } \ - } else if (cmp(LTYPEOF(list)_ls_p,LTYPEOF(list)_ls_q) <= 0) { \ - _ls_e = _ls_p; _ls_p = LNEXT(_ls_p,no); _ls_psize--; \ - if (is_circular && (_ls_p == _ls_oldhead)) { _ls_p = NULL; } \ - } else { \ - _ls_e = _ls_q; _ls_q = LNEXT(_ls_q,no); _ls_qsize--; \ - if (is_circular && (_ls_q == _ls_oldhead)) { _ls_q = NULL; } \ - } \ - if (_ls_tail) { \ - LNEXT(_ls_tail,no) = (char*)_ls_e; \ - } else { \ - list = LTYPEOF(list)_ls_e; \ - } \ - if (_ls_is_double) { \ - LPREV(_ls_e,po) = (char*)_ls_tail; \ - } \ - _ls_tail = _ls_e; \ - } \ - _ls_p = _ls_q; \ - } \ - if (is_circular) { \ - LNEXT(_ls_tail,no) = (char*)list; \ - if (_ls_is_double) { \ - LPREV(list,po) = (char*)_ls_tail; \ - } \ - } else { \ - LNEXT(_ls_tail,no) = NULL; \ - } \ - if (_ls_nmerges <= 1) { \ - _ls_looping=0; \ - } \ - _ls_insize *= 2; \ - } \ - } \ -} while (0) - -/****************************************************************************** - * singly linked list macros (non-circular) * - *****************************************************************************/ -#define LL_PREPEND(head,add) \ -do { \ - (add)->next = head; \ - head = add; \ -} while (0) - -#define LL_APPEND(head,add) \ -do { \ - (add)->next=NULL; \ - if (head) { \ - char *_lla_el = (char*)(head); \ - unsigned _lla_no = FIELD_OFFSET(head,next); \ - while (LNEXT(_lla_el,_lla_no)) { _lla_el = LNEXT(_lla_el,_lla_no); } \ - LNEXT(_lla_el,_lla_no)=(char*)(add); \ - } else { \ - (head)=(add); \ - } \ -} while (0) - -#define LL_DELETE(head,del) \ -do { \ - if ((head) == (del)) { \ - (head)=(head)->next; \ - } else { \ - char *_lld_el = (char*)(head); \ - unsigned _lld_no = FIELD_OFFSET(head,next); \ - while (LNEXT(_lld_el,_lld_no) && (LNEXT(_lld_el,_lld_no) != (char*)(del))) { \ - _lld_el = LNEXT(_lld_el,_lld_no); \ - } \ - if (LNEXT(_lld_el,_lld_no)) { \ - LNEXT(_lld_el,_lld_no) = (char*)((del)->next); \ - } \ - } \ -} while (0) - -#define LL_FOREACH(head,el) \ - for(el=head;el;el=el->next) - -/****************************************************************************** - * doubly linked list macros (non-circular) * - *****************************************************************************/ -#define DL_PREPEND(head,add) \ -do { \ - (add)->next = head; \ - if (head) { \ - (add)->prev = (head)->prev; \ - (head)->prev = (add); \ - } else { \ - (add)->prev = (add); \ - } \ - (head) = (add); \ -} while (0) - -#define DL_APPEND(head,add) \ -do { \ - if (head) { \ - (add)->prev = (head)->prev; \ - (head)->prev->next = (add); \ - (head)->prev = (add); \ - (add)->next = NULL; \ - } else { \ - (head)=(add); \ - (head)->prev = (head); \ - (head)->next = NULL; \ - } \ -} while (0); - -#define DL_DELETE(head,del) \ -do { \ - if ((del)->prev == (del)) { \ - (head)=NULL; \ - } else if ((del)==(head)) { \ - (del)->next->prev = (del)->prev; \ - (head) = (del)->next; \ - } else { \ - (del)->prev->next = (del)->next; \ - if ((del)->next) { \ - (del)->next->prev = (del)->prev; \ - } else { \ - (head)->prev = (del)->prev; \ - } \ - } \ -} while (0); - - -#define DL_FOREACH(head,el) \ - for(el=head;el;el=el->next) - -/****************************************************************************** - * circular doubly linked list macros * - *****************************************************************************/ -#define CDL_PREPEND(head,add) \ -do { \ - if (head) { \ - (add)->prev = (head)->prev; \ - (add)->next = (head); \ - (head)->prev = (add); \ - (add)->prev->next = (add); \ - } else { \ - (add)->prev = (add); \ - (add)->next = (add); \ - } \ -(head)=(add); \ -} while (0) - -#define CDL_DELETE(head,del) \ -do { \ - if ( ((head)==(del)) && ((head)->next == (head))) { \ - (head) = 0L; \ - } else { \ - (del)->next->prev = (del)->prev; \ - (del)->prev->next = (del)->next; \ - if ((del) == (head)) (head)=(del)->next; \ - } \ -} while (0); - -#define CDL_FOREACH(head,el) \ - for(el=head;el;el= (el->next==head ? 0L : el->next)) - - -#endif /* UTLIST_H */ - diff --git a/src/rt/util/hash_map.h b/src/rt/util/hash_map.h deleted file mode 100644 index e5bef45c1c3c5..0000000000000 --- a/src/rt/util/hash_map.h +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/** - * A C++ wrapper around uthash. - */ - -#ifndef HASH_MAP -#define HASH_MAP - -#include -#include "../uthash/uthash.h" - -template class hash_map { - struct map_entry { - K key; - V value; - UT_hash_handle hh; - }; - map_entry * _head; -private: - // private and left undefined to disable copying - hash_map(const hash_map& rhs); - hash_map& operator=(const hash_map& rhs); -public: - hash_map(); - ~hash_map(); - - /** - * Associates a value with the specified key in this hash map. - * If a mapping already exists the old value is replaced. - * - * returns: - * true if the mapping was successfully created and false otherwise. - */ - bool put(K key, V value); - - /** - * Updates the value associated with the specified key in this hash map. - * - * returns: - * true if the value was updated, or false if the key was not found. - */ - bool set(K key, V value); - - /** - * Gets the value associated with the specified key in this hash map. - * - * returns: - * true if the value was found and updates the specified *value parameter - * with the associated value, or false otherwise. - */ - bool get(K key, V *value) const; - - /** - * Removes a key-value pair from this hash map. - * - * returns: - * true if a key-value pair exists and updates the specified - * *key and *value parameters, or false otherwise. - */ - bool pop(K *key, V *value); - - /** - * Checks if the specified key exists in this hash map. - * - * returns: - * true if the specified key exists in this hash map, or false otherwise. - */ - bool contains(K key) const; - - /** - * Removes the value associated with the specified key from this hash map. - * - * returns: - * true if the specified key exists and updates the specified *old_value - * parameter with the associated value, or false otherwise. - */ - bool remove(K key, V *old_value); - bool remove(K key); - - /** - * Returns the number of key-value pairs in this hash map. - */ - size_t count() const; - - bool is_empty() const { - return count() == 0; - } - - /** - * Clears all the key-value pairs in this hash map. - * - * returns: - * the number of deleted key-value pairs. - */ - size_t clear(); -}; - -template -hash_map::hash_map() { - _head = NULL; -} - -template -hash_map::~hash_map() { - clear(); -} - -template bool -hash_map::put(K key, V value) { - if (contains(key)) { - return set(key, value); - } - map_entry *entry = (map_entry *) malloc(sizeof(map_entry)); - entry->key = key; - entry->value = value; - HASH_ADD(hh, _head, key, sizeof(K), entry); - return true; -} - -template bool -hash_map::get(K key, V *value) const { - map_entry *entry = NULL; - HASH_FIND(hh, _head, &key, sizeof(K), entry); - if (entry == NULL) { - return false; - } - *value = entry->value; - return true; -} - -template bool -hash_map::set(K key, V value) { - map_entry *entry = NULL; - HASH_FIND(hh, _head, &key, sizeof(K), entry); - if (entry == NULL) { - return false; - } - entry->value = value; - return true; -} - -template bool -hash_map::contains(K key) const { - V value; - return get(key, &value); -} - -template bool -hash_map::remove(K key, V *old_value) { - map_entry *entry = NULL; - HASH_FIND(hh, _head, &key, sizeof(K), entry); - if (entry == NULL) { - return false; - } - *old_value = entry->value; - HASH_DEL(_head, entry); - free(entry); - return true; -} - -template bool -hash_map::pop(K *key, V *value) { - if (is_empty()) { - return false; - } - map_entry *entry = _head; - HASH_DEL(_head, entry); - *key = entry->key; - *value = entry->value; - free(entry); - return true; -} - -template bool -hash_map::remove(K key) { - V old_value; - return remove(key, &old_value); -} - -template size_t -hash_map::count() const { - return HASH_CNT(hh, _head); -} - -template size_t -hash_map::clear() { - size_t deleted_entries = 0; - while (_head != NULL) { - map_entry *entry = _head; - HASH_DEL(_head, entry); - free(entry); - deleted_entries ++; - } - assert(count() == 0); - return deleted_entries; -} - -#endif /* HASH_MAP */ diff --git a/src/test/auxiliary/cci_capture_clause.rs b/src/test/auxiliary/cci_capture_clause.rs index fd319aacd05f8..70a2b8f680a5c 100644 --- a/src/test/auxiliary/cci_capture_clause.rs +++ b/src/test/auxiliary/cci_capture_clause.rs @@ -12,7 +12,7 @@ use core::pipes::*; pub fn foo(x: T) -> Port { let (p, c) = stream(); - do task::spawn() |copy x| { + do task::spawn() { c.send(x); } p diff --git a/src/test/auxiliary/cci_class_6.rs b/src/test/auxiliary/cci_class_6.rs index f4b27e04c1304..3ab101bc0b4e8 100644 --- a/src/test/auxiliary/cci_class_6.rs +++ b/src/test/auxiliary/cci_class_6.rs @@ -27,7 +27,7 @@ pub mod kitties { cat { meows: in_x, how_hungry: in_y, - info: move in_info + info: in_info } } } diff --git a/src/test/auxiliary/cci_class_cast.rs b/src/test/auxiliary/cci_class_cast.rs index c0140bff5b13a..5256944b18ecb 100644 --- a/src/test/auxiliary/cci_class_cast.rs +++ b/src/test/auxiliary/cci_class_cast.rs @@ -17,7 +17,7 @@ pub mod kitty { name : ~str, } - pub impl cat : ToStr { + pub impl ToStr for cat { pure fn to_str(&self) -> ~str { copy self.name } } diff --git a/src/test/auxiliary/crate-method-reexport-grrrrrrr2.rs b/src/test/auxiliary/crate-method-reexport-grrrrrrr2.rs index 847b6d5b2bbae..2b3fd47e5bc49 100644 --- a/src/test/auxiliary/crate-method-reexport-grrrrrrr2.rs +++ b/src/test/auxiliary/crate-method-reexport-grrrrrrr2.rs @@ -19,7 +19,7 @@ pub mod name_pool { fn add(s: ~str); } - pub impl name_pool: add { + pub impl add for name_pool { fn add(s: ~str) { } } @@ -34,7 +34,7 @@ pub mod rust { fn cx(); } - pub impl rt: cx { + pub impl cx for rt { fn cx() { } } diff --git a/src/test/auxiliary/issue-3012-1.rs b/src/test/auxiliary/issue-3012-1.rs index 618b9391ba14a..cbc1c4b2fec44 100644 --- a/src/test/auxiliary/issue-3012-1.rs +++ b/src/test/auxiliary/issue-3012-1.rs @@ -16,7 +16,7 @@ pub mod socket { sockfd: libc::c_int, } - pub impl socket_handle : Drop { + pub impl Drop for socket_handle { fn finalize(&self) { /* c::close(self.sockfd); */ } diff --git a/src/test/auxiliary/issue2170lib.rs b/src/test/auxiliary/issue2170lib.rs index bf5a664320429..d664ad62edf1d 100644 --- a/src/test/auxiliary/issue2170lib.rs +++ b/src/test/auxiliary/issue2170lib.rs @@ -15,7 +15,7 @@ pub struct rsrc { x: i32, } -pub impl rsrc : Drop { +pub impl Drop for rsrc { fn finalize(&self) { foo(self.x); } diff --git a/src/test/auxiliary/trait_inheritance_overloading_xc.rs b/src/test/auxiliary/trait_inheritance_overloading_xc.rs index 950f4b6bbe72c..2ed3b3b1f5c98 100644 --- a/src/test/auxiliary/trait_inheritance_overloading_xc.rs +++ b/src/test/auxiliary/trait_inheritance_overloading_xc.rs @@ -17,25 +17,25 @@ pub struct MyInt { val: int } -pub impl MyInt : Add { +pub impl Add for MyInt { pure fn add(&self, other: &MyInt) -> MyInt { mi(self.val + other.val) } } -pub impl MyInt : Sub { +pub impl Sub for MyInt { pure fn sub(&self, other: &MyInt) -> MyInt { mi(self.val - other.val) } } -pub impl MyInt : Mul { +pub impl Mul for MyInt { pure fn mul(&self, other: &MyInt) -> MyInt { mi(self.val * other.val) } } -pub impl MyInt : Eq { +pub impl Eq for MyInt { pure fn eq(&self, other: &MyInt) -> bool { self.val == other.val } pure fn ne(&self, other: &MyInt) -> bool { !self.eq(other) } } -pub impl MyInt : MyNum; +pub impl MyNum for MyInt; pure fn mi(v: int) -> MyInt { MyInt { val: v } } diff --git a/src/test/bench/core-std.rs b/src/test/bench/core-std.rs index fafda39993ee2..bd8757d51b743 100644 --- a/src/test/bench/core-std.rs +++ b/src/test/bench/core-std.rs @@ -24,7 +24,7 @@ macro_rules! bench ( fn main() { let argv = os::args(); - let tests = vec::view(argv, 1, argv.len()); + let tests = vec::slice(argv, 1, argv.len()); bench!(shift_push); bench!(read_line); diff --git a/src/test/bench/core-vec-append.rs b/src/test/bench/core-vec-append.rs index b8766d86b017a..1dfcb31f19638 100644 --- a/src/test/bench/core-vec-append.rs +++ b/src/test/bench/core-vec-append.rs @@ -27,7 +27,7 @@ fn collect_dvec(num: uint) -> ~[uint] { for uint::range(0u, num) |i| { result.push(i); } - return dvec::unwrap(move result); + return dvec::unwrap(result); } fn main() { diff --git a/src/test/bench/graph500-bfs.rs b/src/test/bench/graph500-bfs.rs index e88cb62db7345..f1d5749e8402f 100644 --- a/src/test/bench/graph500-bfs.rs +++ b/src/test/bench/graph500-bfs.rs @@ -23,7 +23,6 @@ use std::time; use std::oldmap; use std::oldmap::Map; use std::oldmap::HashMap; -use std::deque; use std::deque::Deque; use std::par; use core::io::WriterUtil; @@ -124,24 +123,24 @@ fn bfs(graph: graph, key: node_id) -> bfs_result { let mut marks : ~[node_id] = vec::from_elem(vec::len(graph), -1i64); - let Q = deque::create(); + let mut q = Deque::new(); - Q.add_back(key); + q.add_back(key); marks[key] = key; - while Q.size() > 0 { - let t = Q.pop_front(); + while !q.is_empty() { + let t = q.pop_front(); do graph[t].each() |k| { if marks[*k] == -1i64 { marks[*k] = t; - Q.add_back(*k); + q.add_back(*k); } true }; } - move marks + marks } /** @@ -260,7 +259,7 @@ fn pbfs(&&graph: arc::ARC, key: node_id) -> bfs_result { i += 1; let old_len = colors.len(); - let color = arc::ARC(move colors); + let color = arc::ARC(colors); let color_vec = arc::get(&color); // FIXME #3387 requires this temp colors = do par::mapi(*color_vec) { diff --git a/src/test/bench/msgsend-pipes-shared.rs b/src/test/bench/msgsend-pipes-shared.rs index 5b6c5210dbffb..bfbc7ecd20ac6 100644 --- a/src/test/bench/msgsend-pipes-shared.rs +++ b/src/test/bench/msgsend-pipes-shared.rs @@ -27,7 +27,7 @@ use io::WriterUtil; use pipes::{Port, Chan, SharedChan}; macro_rules! move_out ( - { $x:expr } => { unsafe { let y = move *ptr::addr_of(&($x)); move y } } + { $x:expr } => { unsafe { let y = *ptr::addr_of(&($x)); y } } ) enum request { @@ -58,7 +58,7 @@ fn run(args: &[~str]) { let (from_child, to_parent) = pipes::stream(); let (from_parent, to_child) = pipes::stream(); - let to_child = SharedChan(move to_child); + let to_child = SharedChan(to_child); let size = uint::from_str(args[1]).get(); let workers = uint::from_str(args[2]).get(); @@ -68,8 +68,8 @@ fn run(args: &[~str]) { for uint::range(0, workers) |_i| { let to_child = to_child.clone(); do task::task().future_result(|+r| { - worker_results.push(move r); - }).spawn |move to_child| { + worker_results.push(r); + }).spawn || { for uint::range(0, size / workers) |_i| { //error!("worker %?: sending %? bytes", i, num_bytes); to_child.send(bytes(num_bytes)); @@ -77,7 +77,7 @@ fn run(args: &[~str]) { //error!("worker %? exiting", i); }; } - do task::spawn |move from_parent, move to_parent| { + do task::spawn || { server(from_parent, to_parent); } diff --git a/src/test/bench/msgsend-pipes.rs b/src/test/bench/msgsend-pipes.rs index 269d02ae45f33..57d9bb49df25a 100644 --- a/src/test/bench/msgsend-pipes.rs +++ b/src/test/bench/msgsend-pipes.rs @@ -23,7 +23,7 @@ use io::WriterUtil; use pipes::{Port, PortSet, Chan}; macro_rules! move_out ( - { $x:expr } => { unsafe { let y = move *ptr::addr_of(&($x)); move y } } + { $x:expr } => { unsafe { let y = *ptr::addr_of(&($x)); y } } ) enum request { @@ -54,7 +54,7 @@ fn run(args: &[~str]) { let (from_child, to_parent) = pipes::stream(); let (from_parent_, to_child) = pipes::stream(); let from_parent = PortSet(); - from_parent.add(move from_parent_); + from_parent.add(from_parent_); let size = uint::from_str(args[1]).get(); let workers = uint::from_str(args[2]).get(); @@ -63,10 +63,10 @@ fn run(args: &[~str]) { let mut worker_results = ~[]; for uint::range(0, workers) |_i| { let (from_parent_, to_child) = pipes::stream(); - from_parent.add(move from_parent_); + from_parent.add(from_parent_); do task::task().future_result(|+r| { - worker_results.push(move r); - }).spawn |move to_child| { + worker_results.push(r); + }).spawn || { for uint::range(0, size / workers) |_i| { //error!("worker %?: sending %? bytes", i, num_bytes); to_child.send(bytes(num_bytes)); @@ -74,7 +74,7 @@ fn run(args: &[~str]) { //error!("worker %? exiting", i); }; } - do task::spawn |move from_parent, move to_parent| { + do task::spawn || { server(from_parent, to_parent); } diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index 5e1ac20f5eb9f..9b6fee5e23bc1 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -40,7 +40,7 @@ fn recv(p: &pipe) -> uint { fn init() -> (pipe,pipe) { let m = arc::MutexARC(~[]); - ((&m).clone(), move m) + ((&m).clone(), m) } @@ -48,18 +48,18 @@ fn thread_ring(i: uint, count: uint, +num_chan: pipe, +num_port: pipe) { - let mut num_chan = move Some(move num_chan); - let mut num_port = move Some(move num_port); + let mut num_chan = Some(num_chan); + let mut num_port = Some(num_port); // Send/Receive lots of messages. for uint::range(0u, count) |j| { //error!("task %?, iter %?", i, j); let mut num_chan2 = option::swap_unwrap(&mut num_chan); let mut num_port2 = option::swap_unwrap(&mut num_port); send(&num_chan2, i * j); - num_chan = Some(move num_chan2); + num_chan = Some(num_chan2); let _n = recv(&num_port2); //log(error, _n); - num_port = Some(move num_port2); + num_port = Some(num_port2); }; } @@ -77,7 +77,7 @@ fn main() { let msg_per_task = uint::from_str(args[2]).get(); let (num_chan, num_port) = init(); - let mut num_chan = Some(move num_chan); + let mut num_chan = Some(num_chan); let start = time::precise_time_s(); @@ -89,22 +89,22 @@ fn main() { let (new_chan, num_port) = init(); let num_chan2 = ~mut None; *num_chan2 <-> num_chan; - let num_port = ~mut Some(move num_port); - let new_future = future::spawn(|move num_chan2, move num_port| { + let num_port = ~mut Some(num_port); + let new_future = do future::spawn() || { let mut num_chan = None; num_chan <-> *num_chan2; let mut num_port1 = None; num_port1 <-> *num_port; thread_ring(i, msg_per_task, - option::unwrap(move num_chan), - option::unwrap(move num_port1)) - }); - futures.push(move new_future); - num_chan = Some(move new_chan); + option::unwrap(num_chan), + option::unwrap(num_port1)) + }; + futures.push(new_future); + num_chan = Some(new_chan); }; // do our iteration - thread_ring(0, msg_per_task, option::unwrap(move num_chan), move num_port); + thread_ring(0, msg_per_task, option::unwrap(num_chan), num_port); // synchronize for futures.each |f| { f.get() }; diff --git a/src/test/bench/msgsend-ring-pipes.rs b/src/test/bench/msgsend-ring-pipes.rs index e9281a0c41736..71ca0f9576575 100644 --- a/src/test/bench/msgsend-ring-pipes.rs +++ b/src/test/bench/msgsend-ring-pipes.rs @@ -29,15 +29,15 @@ proto! ring ( ) macro_rules! move_out ( - ($x:expr) => { unsafe { let y = move *ptr::addr_of(&$x); move y } } + ($x:expr) => { unsafe { let y = *ptr::addr_of(&$x); y } } ) fn thread_ring(i: uint, count: uint, +num_chan: ring::client::num, +num_port: ring::server::num) { - let mut num_chan = move Some(move num_chan); - let mut num_port = move Some(move num_port); + let mut num_chan = Some(num_chan); + let mut num_port = Some(num_port); // Send/Receive lots of messages. for uint::range(0, count) |j| { //error!("task %?, iter %?", i, j); @@ -45,9 +45,9 @@ fn thread_ring(i: uint, let mut num_port2 = None; num_chan2 <-> num_chan; num_port2 <-> num_port; - num_chan = Some(ring::client::num(option::unwrap(move num_chan2), i * j)); - let port = option::unwrap(move num_port2); - match recv(move port) { + num_chan = Some(ring::client::num(option::unwrap(num_chan2), i * j)); + let port = option::unwrap(num_port2); + match recv(port) { ring::num(_n, p) => { //log(error, _n); num_port = Some(move_out!(p)); @@ -70,7 +70,7 @@ fn main() { let msg_per_task = uint::from_str(args[2]).get(); let (num_chan, num_port) = ring::init(); - let mut num_chan = Some(move num_chan); + let mut num_chan = Some(num_chan); let start = time::precise_time_s(); @@ -82,23 +82,22 @@ fn main() { let (new_chan, num_port) = ring::init(); let num_chan2 = ~mut None; *num_chan2 <-> num_chan; - let num_port = ~mut Some(move num_port); - let new_future = do future::spawn - |move num_chan2, move num_port| { + let num_port = ~mut Some(num_port); + let new_future = do future::spawn || { let mut num_chan = None; num_chan <-> *num_chan2; let mut num_port1 = None; num_port1 <-> *num_port; thread_ring(i, msg_per_task, - option::unwrap(move num_chan), - option::unwrap(move num_port1)) + option::unwrap(num_chan), + option::unwrap(num_port1)) }; - futures.push(move new_future); - num_chan = Some(move new_chan); + futures.push(new_future); + num_chan = Some(new_chan); }; // do our iteration - thread_ring(0, msg_per_task, option::unwrap(move num_chan), move num_port); + thread_ring(0, msg_per_task, option::unwrap(num_chan), num_port); // synchronize for futures.each |f| { f.get() }; diff --git a/src/test/bench/msgsend-ring-rw-arcs.rs b/src/test/bench/msgsend-ring-rw-arcs.rs index ff88eea598dfb..eaae8370d6b8b 100644 --- a/src/test/bench/msgsend-ring-rw-arcs.rs +++ b/src/test/bench/msgsend-ring-rw-arcs.rs @@ -40,7 +40,7 @@ fn recv(p: &pipe) -> uint { fn init() -> (pipe,pipe) { let x = arc::RWARC(~[]); - ((&x).clone(), move x) + ((&x).clone(), x) } @@ -48,18 +48,18 @@ fn thread_ring(i: uint, count: uint, +num_chan: pipe, +num_port: pipe) { - let mut num_chan = move Some(move num_chan); - let mut num_port = move Some(move num_port); + let mut num_chan = Some(num_chan); + let mut num_port = Some(num_port); // Send/Receive lots of messages. for uint::range(0u, count) |j| { //error!("task %?, iter %?", i, j); let mut num_chan2 = option::swap_unwrap(&mut num_chan); let mut num_port2 = option::swap_unwrap(&mut num_port); send(&num_chan2, i * j); - num_chan = Some(move num_chan2); + num_chan = Some(num_chan2); let _n = recv(&num_port2); //log(error, _n); - num_port = Some(move num_port2); + num_port = Some(num_port2); }; } @@ -77,7 +77,7 @@ fn main() { let msg_per_task = uint::from_str(args[2]).get(); let (num_chan, num_port) = init(); - let mut num_chan = Some(move num_chan); + let mut num_chan = Some(num_chan); let start = time::precise_time_s(); @@ -89,23 +89,22 @@ fn main() { let (new_chan, num_port) = init(); let num_chan2 = ~mut None; *num_chan2 <-> num_chan; - let num_port = ~mut Some(move num_port); - let new_future = do future::spawn - |move num_chan2, move num_port| { + let num_port = ~mut Some(num_port); + let new_future = do future::spawn || { let mut num_chan = None; num_chan <-> *num_chan2; let mut num_port1 = None; num_port1 <-> *num_port; thread_ring(i, msg_per_task, - option::unwrap(move num_chan), - option::unwrap(move num_port1)) + option::unwrap(num_chan), + option::unwrap(num_port1)) }; - futures.push(move new_future); - num_chan = Some(move new_chan); + futures.push(new_future); + num_chan = Some(new_chan); }; // do our iteration - thread_ring(0, msg_per_task, option::unwrap(move num_chan), move num_port); + thread_ring(0, msg_per_task, option::unwrap(num_chan), num_port); // synchronize for futures.each |f| { f.get() }; diff --git a/src/test/bench/noise.rs b/src/test/bench/noise.rs index a07dcee35f4d3..39caba9273293 100644 --- a/src/test/bench/noise.rs +++ b/src/test/bench/noise.rs @@ -35,8 +35,8 @@ fn Noise2DContext() -> ~Noise2DContext { r.shuffle_mut(permutations); ~Noise2DContext{ - rgradients: move rgradients, - permutations: move permutations, + rgradients: rgradients, + permutations: permutations, } } diff --git a/src/test/bench/pingpong.rs b/src/test/bench/pingpong.rs index 3d367c546838b..11a127b9722f4 100644 --- a/src/test/bench/pingpong.rs +++ b/src/test/bench/pingpong.rs @@ -45,17 +45,17 @@ proto! pingpong_unbounded ( // This stuff should go in libcore::pipes macro_rules! move_it ( - { $x:expr } => { let t = move *ptr::addr_of(&($x)); move t } + { $x:expr } => { let t = *ptr::addr_of(&($x)); t } ) macro_rules! follow ( { $($message:path($($x: ident),+) -> $next:ident $e:expr)+ } => ( - |m| match move m { - $(Some($message($($x,)* move next)) => { - let $next = move next; - move $e })+ + |m| match m { + $(Some($message($($x,)* next)) => { + let $next = next; + $e })+ _ => { fail!() } } ); @@ -63,10 +63,10 @@ macro_rules! follow ( { $($message:path -> $next:ident $e:expr)+ } => ( - |m| match move m { - $(Some($message(move next)) => { - let $next = move next; - move $e })+ + |m| match m { + $(Some($message(next)) => { + let $next = next; + $e })+ _ => { fail!() } } ) @@ -74,7 +74,7 @@ macro_rules! follow ( fn switch(+endp: pipes::RecvPacketBuffered, f: fn(+v: Option) -> U) -> U { - f(pipes::try_recv(move endp)) + f(pipes::try_recv(endp)) } // Here's the benchmark @@ -84,10 +84,10 @@ fn bounded(count: uint) { let mut ch = do spawn_service(init) |ch| { let mut count = count; - let mut ch = move ch; + let mut ch = ch; while count > 0 { - ch = switch(move ch, follow! ( - ping -> next { server::pong(move next) } + ch = switch(ch, follow! ( + ping -> next { server::pong(next) } )); count -= 1; @@ -96,10 +96,10 @@ fn bounded(count: uint) { let mut count = count; while count > 0 { - let ch_ = client::ping(move ch); + let ch_ = client::ping(ch); - ch = switch(move ch_, follow! ( - pong -> next { move next } + ch = switch(ch_, follow! ( + pong -> next { next } )); count -= 1; @@ -111,10 +111,10 @@ fn unbounded(count: uint) { let mut ch = do spawn_service(init) |ch| { let mut count = count; - let mut ch = move ch; + let mut ch = ch; while count > 0 { - ch = switch(move ch, follow! ( - ping -> next { server::pong(move next) } + ch = switch(ch, follow! ( + ping -> next { server::pong(next) } )); count -= 1; @@ -123,10 +123,10 @@ fn unbounded(count: uint) { let mut count = count; while count > 0 { - let ch_ = client::ping(move ch); + let ch_ = client::ping(ch); - ch = switch(move ch_, follow! ( - pong -> next { move next } + ch = switch(ch_, follow! ( + pong -> next { next } )); count -= 1; diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index 27111ff3b6d45..b42ec246ccb97 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -156,7 +156,7 @@ fn rendezvous(nn: uint, set: ~[color]) { let to_rendezvous_log = to_rendezvous_log.clone(); let (from_rendezvous, to_creature) = stream(); let from_rendezvous = Cell(from_rendezvous); - do task::spawn |move ii, move col| { + do task::spawn || { creature(ii, col, from_rendezvous.take(), to_rendezvous.clone(), to_rendezvous_log.clone()); } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 3afb86210e1b8..78ae31570b335 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -77,7 +77,7 @@ fn find(mm: HashMap<~[u8], uint>, key: ~str) -> uint { // given a map, increment the counter for a key fn update_freq(mm: HashMap<~[u8], uint>, key: &[u8]) { - let key = vec::slice(key, 0, key.len()); + let key = vec::slice(key, 0, key.len()).to_vec(); mm.update(key, 1, |v,v1| { v+v1 }); } @@ -90,11 +90,11 @@ fn windows_with_carry(bb: &[u8], nn: uint, let len = vec::len(bb); while ii < len - (nn - 1u) { - it(vec::view(bb, ii, ii+nn)); + it(vec::slice(bb, ii, ii+nn)); ii += 1u; } - return vec::slice(bb, len - (nn - 1u), len); + return vec::slice(bb, len - (nn - 1u), len).to_vec(); } fn make_sequence_processor(sz: uint, from_parent: pipes::Port<~[u8]>, @@ -128,7 +128,7 @@ fn make_sequence_processor(sz: uint, from_parent: pipes::Port<~[u8]>, _ => { ~"" } }; - to_parent.send(move buffer); + to_parent.send(buffer); } // given a FASTA file on stdin, process sequence THREE @@ -149,23 +149,23 @@ fn main() { // initialize each sequence sorter let sizes = ~[1,2,3,4,6,12,18]; let streams = vec::map(sizes, |_sz| Some(stream())); - let mut streams = move streams; + let mut streams = streams; let mut from_child = ~[]; let to_child = vec::mapi(sizes, |ii, sz| { let sz = *sz; let mut stream = None; stream <-> streams[ii]; - let (from_child_, to_parent_) = option::unwrap(move stream); + let (from_child_, to_parent_) = option::unwrap(stream); - from_child.push(move from_child_); + from_child.push(from_child_); let (from_parent, to_child) = pipes::stream(); - do task::spawn_with(move from_parent) |move to_parent_, from_parent| { + do task::spawn_with(from_parent) |from_parent| { make_sequence_processor(sz, from_parent, to_parent_); }; - move to_child + to_child }); diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index 76a7688777218..5ab9b068d0b0e 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -172,7 +172,7 @@ fn main() { let pchan = pipes::SharedChan(pchan); for uint::range(0_u, size) |j| { let cchan = pchan.clone(); - do task::spawn |move cchan| { cchan.send(chanmb(j, size)) }; + do task::spawn || { cchan.send(chanmb(j, size)) }; }; writer(path, pport, size); } diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index ac695421059c7..2c9da65cc13ac 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -43,15 +43,15 @@ fn fib(n: int) -> int { } else { let p = pipes::PortSet(); let ch = p.chan(); - task::spawn(|move ch| pfib(ch, n - 1) ); + task::spawn(|| pfib(ch, n - 1) ); let ch = p.chan(); - task::spawn(|move ch| pfib(ch, n - 2) ); + task::spawn(|| pfib(ch, n - 2) ); c.send(p.recv() + p.recv()); } } let (p, ch) = pipes::stream(); - let _t = task::spawn(|move ch| pfib(ch, n) ); + let _t = task::spawn(|| pfib(ch, n) ); p.recv() } @@ -86,7 +86,7 @@ fn stress(num_tasks: int) { let mut results = ~[]; for range(0, num_tasks) |i| { do task::task().future_result(|+r| { - results.push(move r); + results.push(r); }).spawn { stress_task(i); } diff --git a/src/test/bench/task-perf-alloc-unwind.rs b/src/test/bench/task-perf-alloc-unwind.rs index 5f0530871fc83..b4b02c3aaa8d4 100644 --- a/src/test/bench/task-perf-alloc-unwind.rs +++ b/src/test/bench/task-perf-alloc-unwind.rs @@ -99,6 +99,6 @@ fn recurse_or_fail(depth: int, st: Option) { } }; - recurse_or_fail(depth, Some(move st)); + recurse_or_fail(depth, Some(st)); } } diff --git a/src/test/bench/task-perf-jargon-metal-smoke.rs b/src/test/bench/task-perf-jargon-metal-smoke.rs index 06f4213ee7b93..f2441755a7b1d 100644 --- a/src/test/bench/task-perf-jargon-metal-smoke.rs +++ b/src/test/bench/task-perf-jargon-metal-smoke.rs @@ -19,14 +19,14 @@ fn child_generation(gens_left: uint, -c: pipes::Chan<()>) { // This used to be O(n^2) in the number of generations that ever existed. // With this code, only as many generations are alive at a time as tasks // alive at a time, - let c = ~mut Some(move c); - do task::spawn_supervised |move c| { + let c = ~mut Some(c); + do task::spawn_supervised || { let c = option::swap_unwrap(c); if gens_left & 1 == 1 { task::yield(); // shake things up a bit } if gens_left > 0 { - child_generation(gens_left - 1, move c); // recurse + child_generation(gens_left - 1, c); // recurse } else { c.send(()) } @@ -44,7 +44,7 @@ fn main() { }; let (p,c) = pipes::stream(); - child_generation(uint::from_str(args[1]).get(), move c); + child_generation(uint::from_str(args[1]).get(), c); if p.try_recv().is_none() { fail!(~"it happened when we slumbered"); } diff --git a/src/test/bench/task-perf-linked-failure.rs b/src/test/bench/task-perf-linked-failure.rs index 4a6195b1ae89c..3b6ececaef90a 100644 --- a/src/test/bench/task-perf-linked-failure.rs +++ b/src/test/bench/task-perf-linked-failure.rs @@ -46,9 +46,9 @@ fn grandchild_group(num_tasks: uint) { fn spawn_supervised_blocking(myname: &str, +f: fn~()) { let mut res = None; - task::task().future_result(|+r| res = Some(move r)).supervised().spawn(move f); + task::task().future_result(|+r| res = Some(r)).supervised().spawn(f); error!("%s group waiting", myname); - let x = option::unwrap(move res).recv(); + let x = option::unwrap(res).recv(); assert x == task::Success; } diff --git a/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-1.rs b/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-1.rs index 298e5d53c9401..e9bc4a5e195d7 100644 --- a/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-1.rs +++ b/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-1.rs @@ -18,8 +18,8 @@ impl Drop for X { fn main() { let x = Some(X { x: () }); - match move x { - Some(ref _y @ move _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern + match x { + Some(ref _y @ _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } } diff --git a/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-2.rs b/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-2.rs index 162a10a370b78..6548adddf1956 100644 --- a/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-2.rs +++ b/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-2.rs @@ -18,8 +18,8 @@ impl Drop for X { fn main() { let x = Some((X { x: () }, X { x: () })); - match move x { - Some((ref _y, move _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern + match x { + Some((ref _y, _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } } diff --git a/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-3.rs b/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-3.rs index 1aed491bbf069..aaa9d9f920a6a 100644 --- a/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-3.rs +++ b/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-3.rs @@ -20,8 +20,8 @@ enum double_option { some2(T,U), none2 } fn main() { let x = some2(X { x: () }, X { x: () }); - match move x { - some2(ref _y, move _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern + match x { + some2(ref _y, _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern none2 => fail!() } } diff --git a/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-4.rs b/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-4.rs index 9c879e297090f..b5686b64c810b 100644 --- a/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-4.rs +++ b/src/test/compile-fail/bind-by-move-neither-can-live-while-the-other-survives-4.rs @@ -18,8 +18,8 @@ impl Drop for X { fn main() { let x = Some((X { x: () }, X { x: () })); - match move x { - Some((move _y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern + match x { + Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } } diff --git a/src/test/compile-fail/bind-by-move-no-guards.rs b/src/test/compile-fail/bind-by-move-no-guards.rs index 82f4d57911b4c..40a444df12d36 100644 --- a/src/test/compile-fail/bind-by-move-no-guards.rs +++ b/src/test/compile-fail/bind-by-move-no-guards.rs @@ -12,9 +12,9 @@ fn main() { let (p,c) = pipes::stream(); let x = Some(p); c.send(false); - match move x { - Some(move z) if z.recv() => { fail!() }, //~ ERROR cannot bind by-move into a pattern guard - Some(move z) => { assert !z.recv(); }, + match x { + Some(z) if z.recv() => { fail!() }, //~ ERROR cannot bind by-move into a pattern guard + Some(z) => { assert !z.recv(); }, None => fail!() } } diff --git a/src/test/compile-fail/bind-by-move-no-lvalues-1.rs b/src/test/compile-fail/bind-by-move-no-lvalues-1.rs index 586285d956691..c8537afa1905e 100644 --- a/src/test/compile-fail/bind-by-move-no-lvalues-1.rs +++ b/src/test/compile-fail/bind-by-move-no-lvalues-1.rs @@ -21,7 +21,7 @@ impl Drop for X { fn main() { let x = Some(X { x: () }); match x { - Some(move _z) => { }, //~ ERROR cannot bind by-move when matching an lvalue + Some(_z) => { }, //~ ERROR cannot bind by-move when matching an lvalue None => fail!() } } diff --git a/src/test/compile-fail/bind-by-move-no-lvalues-2.rs b/src/test/compile-fail/bind-by-move-no-lvalues-2.rs index 9ed48fe33e319..26b1084c09172 100644 --- a/src/test/compile-fail/bind-by-move-no-lvalues-2.rs +++ b/src/test/compile-fail/bind-by-move-no-lvalues-2.rs @@ -23,7 +23,7 @@ struct Y { y: Option } fn main() { let x = Y { y: Some(X { x: () }) }; match x.y { - Some(move _z) => { }, //~ ERROR cannot bind by-move when matching an lvalue + Some(_z) => { }, //~ ERROR cannot bind by-move when matching an lvalue None => fail!() } } diff --git a/src/test/compile-fail/bind-by-move-no-sub-bindings.rs b/src/test/compile-fail/bind-by-move-no-sub-bindings.rs index d60ef84f04024..c86158be5ea7f 100644 --- a/src/test/compile-fail/bind-by-move-no-sub-bindings.rs +++ b/src/test/compile-fail/bind-by-move-no-sub-bindings.rs @@ -18,8 +18,8 @@ impl Drop for X { fn main() { let x = Some(X { x: () }); - match move x { - Some(move _y @ ref _z) => { }, //~ ERROR cannot bind by-move with sub-bindings + match x { + Some(_y @ ref _z) => { }, //~ ERROR cannot bind by-move with sub-bindings None => fail!() } } diff --git a/src/test/compile-fail/borrowck-borrow-from-owned-ptr.rs b/src/test/compile-fail/borrowck-borrow-from-owned-ptr.rs index 47b6b4de64281..005908f86d87d 100644 --- a/src/test/compile-fail/borrowck-borrow-from-owned-ptr.rs +++ b/src/test/compile-fail/borrowck-borrow-from-owned-ptr.rs @@ -18,7 +18,7 @@ struct Bar { int2: int, } -fn make_foo() -> ~Foo { die!() } +fn make_foo() -> ~Foo { fail!() } fn borrow_same_field_twice_mut_mut() { let mut foo = make_foo(); diff --git a/src/test/compile-fail/borrowck-borrow-from-stack-variable.rs b/src/test/compile-fail/borrowck-borrow-from-stack-variable.rs index 30757cc6e7798..035e293bc36b6 100644 --- a/src/test/compile-fail/borrowck-borrow-from-stack-variable.rs +++ b/src/test/compile-fail/borrowck-borrow-from-stack-variable.rs @@ -18,7 +18,7 @@ struct Bar { int2: int, } -fn make_foo() -> Foo { die!() } +fn make_foo() -> Foo { fail!() } fn borrow_same_field_twice_mut_mut() { let mut foo = make_foo(); diff --git a/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs b/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs index 0b9375bc543a1..7b6484fd4aadb 100644 --- a/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs +++ b/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs @@ -20,6 +20,6 @@ impl Add for foo { fn main() { let x = foo(~3); - let _y = x + move x; + let _y = x + x; //~^ ERROR moving out of immutable local variable prohibited due to outstanding loan } diff --git a/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs b/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs index 7154683565960..8f332646bbccd 100644 --- a/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs +++ b/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs @@ -9,7 +9,7 @@ // except according to those terms. fn foo(x: *~int) -> ~int { - let y = move *x; //~ ERROR dereference of unsafe pointer requires unsafe function or block + let y = *x; //~ ERROR dereference of unsafe pointer requires unsafe function or block return y; } diff --git a/src/test/compile-fail/borrowck-vec-pattern-element-loan.rs b/src/test/compile-fail/borrowck-vec-pattern-element-loan.rs index deebff5f43a3c..cec81d8a6ef5b 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-element-loan.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-element-loan.rs @@ -4,7 +4,7 @@ fn a() -> &[int] { [_a, ..tail] => tail, _ => fail!(~"foo") }; - move tail + tail } fn main() { diff --git a/src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs b/src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs index e1ed0f0daa1e8..714a80def9358 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs @@ -4,7 +4,7 @@ fn a() -> &int { [_a, ..tail] => &tail[0], _ => fail!(~"foo") }; - move tail + tail } fn main() { diff --git a/src/test/compile-fail/copy-a-resource.rs b/src/test/compile-fail/copy-a-resource.rs index 95fd9b938f07b..f1b31d66b3f68 100644 --- a/src/test/compile-fail/copy-a-resource.rs +++ b/src/test/compile-fail/copy-a-resource.rs @@ -23,7 +23,7 @@ fn foo(i:int) -> foo { } fn main() { - let x = move foo(10); + let x = foo(10); let _y = copy x; //~^ ERROR copying a value of non-copyable type `foo` log(error, x); diff --git a/src/test/compile-fail/issue-2548.rs b/src/test/compile-fail/issue-2548.rs index abc734697191f..951944e24857f 100644 --- a/src/test/compile-fail/issue-2548.rs +++ b/src/test/compile-fail/issue-2548.rs @@ -34,7 +34,7 @@ fn main() { let mut res = foo(x); let mut v = ~[]; - v = move ~[(move res)] + v; //~ instantiating a type parameter with an incompatible type `foo`, which does not fulfill `Copy` + v = ~[(res)] + v; //~ instantiating a type parameter with an incompatible type `foo`, which does not fulfill `Copy` assert (v.len() == 2); } diff --git a/src/test/compile-fail/issue-3177-mutable-struct.rs b/src/test/compile-fail/issue-3177-mutable-struct.rs index 8a65366d2cb43..a71826c629b6c 100644 --- a/src/test/compile-fail/issue-3177-mutable-struct.rs +++ b/src/test/compile-fail/issue-3177-mutable-struct.rs @@ -17,5 +17,5 @@ struct S { fn main() { let a1 = ~S{ s: true, cant_nest: () }; - let _a2 = ~S{ s: move a1, cant_nest: () }; + let _a2 = ~S{ s: a1, cant_nest: () }; } diff --git a/src/test/compile-fail/issue-3953.rs b/src/test/compile-fail/issue-3953.rs index 2c797691b8d7a..227ea5c1521c0 100644 --- a/src/test/compile-fail/issue-3953.rs +++ b/src/test/compile-fail/issue-3953.rs @@ -19,7 +19,7 @@ trait Hahaha: Eq Eq Eq Eq Eq Eq Eq Eq Eq Eq Eq Eq Eq Eq Eq Eq //~ ERROR Duplicat enum Lol = int; -pub impl Lol: Hahaha { } +pub impl Hahaha for Lol { } impl Eq for Lol { pure fn eq(&self, other: &Lol) -> bool { **self != **other } diff --git a/src/test/compile-fail/issue-3969.rs b/src/test/compile-fail/issue-3969.rs index 675544ea59f93..a003563928738 100644 --- a/src/test/compile-fail/issue-3969.rs +++ b/src/test/compile-fail/issue-3969.rs @@ -16,7 +16,7 @@ trait BikeMethods { fn woops(&const self) -> ~str; } -pub impl Bike : BikeMethods { +pub impl BikeMethods for Bike { static fn woops(&const self) -> ~str { ~"foo" } //~^ ERROR method `woops` is declared as static in its impl, but not in its trait } diff --git a/src/test/compile-fail/kindck-nonsendable-1.rs b/src/test/compile-fail/kindck-nonsendable-1.rs index a513e367fe5bc..397b0f682d62c 100644 --- a/src/test/compile-fail/kindck-nonsendable-1.rs +++ b/src/test/compile-fail/kindck-nonsendable-1.rs @@ -13,6 +13,6 @@ fn foo(_x: @uint) {} fn main() { let x = @3u; let _ = fn~() { foo(x); }; //~ ERROR value has non-owned type `@uint` - let _ = fn~(copy x) { foo(x); }; //~ ERROR value has non-owned type `@uint` - let _ = fn~(move x) { foo(x); }; //~ ERROR value has non-owned type `@uint` + let _ = fn~() { foo(x); }; //~ ERROR value has non-owned type `@uint` + let _ = fn~() { foo(x); }; //~ ERROR value has non-owned type `@uint` } diff --git a/src/test/compile-fail/liveness-unused.rs b/src/test/compile-fail/liveness-unused.rs index b5157c669a73a..970abf4fd94b0 100644 --- a/src/test/compile-fail/liveness-unused.rs +++ b/src/test/compile-fail/liveness-unused.rs @@ -68,5 +68,5 @@ impl Drop for r { fn main() { let x = r { x: () }; - fn@(move x) { copy x; }; //~ ERROR copying a value of non-copyable type + fn@() { copy x; }; //~ ERROR copying a value of non-copyable type } diff --git a/src/test/compile-fail/missing-derivable-attr.rs b/src/test/compile-fail/missing-derivable-attr.rs index 3d63b622fcc96..057e6dbc06864 100644 --- a/src/test/compile-fail/missing-derivable-attr.rs +++ b/src/test/compile-fail/missing-derivable-attr.rs @@ -20,7 +20,7 @@ impl MyEq for int { pure fn eq(&self, other: &int) -> bool { *self == *other } } -impl A : MyEq; //~ ERROR missing method +impl MyEq for A; //~ ERROR missing method fn main() { } diff --git a/src/test/compile-fail/mutable-huh-ptr-assign.rs b/src/test/compile-fail/mutable-huh-ptr-assign.rs index d0e7c2339bc1f..ed356f4001dd6 100644 --- a/src/test/compile-fail/mutable-huh-ptr-assign.rs +++ b/src/test/compile-fail/mutable-huh-ptr-assign.rs @@ -16,8 +16,8 @@ fn main() { } unsafe { - let a = 0; - let v = ptr::mut_addr_of(&a); + let mut a = 0; + let v = &mut a; f(v); } } diff --git a/src/test/compile-fail/mutable-huh-variance-ptr.rs b/src/test/compile-fail/mutable-huh-variance-ptr.rs index e2299597c2f58..dba6f9ae3fa0f 100644 --- a/src/test/compile-fail/mutable-huh-variance-ptr.rs +++ b/src/test/compile-fail/mutable-huh-variance-ptr.rs @@ -13,8 +13,8 @@ extern mod std; fn main() { - let a = ~[0]; - let v: *mut ~[int] = ptr::mut_addr_of(&a); + let mut a = ~[0]; + let v: *mut ~[int] = &mut a; fn f(&&v: *mut ~[const int]) { unsafe { diff --git a/src/test/compile-fail/noncopyable-class.rs b/src/test/compile-fail/noncopyable-class.rs index 115120ff37263..42bad88633cff 100644 --- a/src/test/compile-fail/noncopyable-class.rs +++ b/src/test/compile-fail/noncopyable-class.rs @@ -37,7 +37,7 @@ fn foo(i:int) -> foo { } fn main() { - let x = move foo(10); + let x = foo(10); let _y = copy x; //~ ERROR copying a value of non-copyable type log(error, x); } diff --git a/src/test/compile-fail/regions-addr-of-arg.rs b/src/test/compile-fail/regions-addr-of-arg.rs index 54d7c0b4d18b7..7f2140d96e16c 100644 --- a/src/test/compile-fail/regions-addr-of-arg.rs +++ b/src/test/compile-fail/regions-addr-of-arg.rs @@ -9,11 +9,11 @@ // except according to those terms. fn foo(a: int) { - let _p: &static/int = &a; //~ ERROR illegal borrow + let _p: &'static int = &a; //~ ERROR illegal borrow } fn bar(a: int) { - let _q: &blk/int = &a; + let _q: &'blk int = &a; } fn main() { diff --git a/src/test/compile-fail/regions-addr-of-upvar-self.rs b/src/test/compile-fail/regions-addr-of-upvar-self.rs index 5bb82d1ee662d..cf026785420d7 100644 --- a/src/test/compile-fail/regions-addr-of-upvar-self.rs +++ b/src/test/compile-fail/regions-addr-of-upvar-self.rs @@ -15,7 +15,7 @@ struct dog { impl dog { fn chase_cat() { for uint::range(0u, 10u) |_i| { - let p: &static/mut uint = &mut self.food; //~ ERROR illegal borrow + let p: &'static mut uint = &mut self.food; //~ ERROR illegal borrow *p = 3u; } } diff --git a/src/test/compile-fail/regions-bounds.rs b/src/test/compile-fail/regions-bounds.rs index ba125f0b3231c..47ddbf38e3de1 100644 --- a/src/test/compile-fail/regions-bounds.rs +++ b/src/test/compile-fail/regions-bounds.rs @@ -13,8 +13,10 @@ // checked. enum an_enum = ∫ -trait a_trait { fn foo() -> &self/int; } -struct a_class { x:&self/int } +trait a_trait { + fn foo() -> &'self int; +} +struct a_class { x:&'self int } fn a_fn1(e: an_enum/&a) -> an_enum/&b { return e; //~ ERROR mismatched types: expected `an_enum/&b` but found `an_enum/&a` diff --git a/src/test/compile-fail/regions-in-enums.rs b/src/test/compile-fail/regions-in-enums.rs index baf072c01eea2..b399ef8a747f9 100644 --- a/src/test/compile-fail/regions-in-enums.rs +++ b/src/test/compile-fail/regions-in-enums.rs @@ -8,16 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum yes0 { - x3(&uint) +enum yes0<'lt> { + // This will eventually be legal (and in fact the only way): + X3(&'lt uint) //~ ERROR named regions other than `self` are not allowed as part of a type declaration } enum yes1 { - x4(&self/uint) + X4(&'self uint) } enum yes2 { - x5(&foo/uint) //~ ERROR named regions other than `self` are not allowed as part of a type declaration + X5(&'foo uint) //~ ERROR named regions other than `self` are not allowed as part of a type declaration } fn main() {} diff --git a/src/test/compile-fail/regions-scoping.rs b/src/test/compile-fail/regions-scoping.rs index 380a9a57d01fe..063bc32f7b446 100644 --- a/src/test/compile-fail/regions-scoping.rs +++ b/src/test/compile-fail/regions-scoping.rs @@ -10,13 +10,13 @@ fn with(t: T, f: fn(T)) { f(t) } -fn nested(x: &x/int) { // (1) +fn nested<'x>(x: &'x int) { // (1) do with( - fn&(x: &x/int, // Refers to the region `x` at (1) - y: &y/int, // A fresh region `y` (2) - z: fn(x: &x/int, // Refers to `x` at (1) - y: &y/int, // Refers to `y` at (2) - z: &z/int) -> &z/int) // A fresh region `z` (3) + fn&(x: &'x int, // Refers to the region `x` at (1) + y: &'y int, // A fresh region `y` (2) + z: fn<'z>(x: &'x int, // Refers to `x` at (1) + y: &'y int, // Refers to `y` at (2) + z: &'z int) -> &'z int) // A fresh region `z` (3) -> &x/int { if false { return z(x, y, x); } @@ -29,13 +29,13 @@ fn nested(x: &x/int) { // (1) } ) |foo| { - let a: &x/int = foo(x, x, |_x, _y, z| z ); - let b: &x/int = foo(x, a, |_x, _y, z| z ); - let c: &x/int = foo(a, a, |_x, _y, z| z ); + let a: &'x int = foo(x, x, |_x, _y, z| z ); + let b: &'x int = foo(x, a, |_x, _y, z| z ); + let c: &'x int = foo(a, a, |_x, _y, z| z ); let z = 3i; - let d: &x/int = foo(x, x, |_x, _y, z| z ); - let e: &x/int = foo(x, &z, |_x, _y, z| z ); + let d: &'x int = foo(x, x, |_x, _y, z| z ); + let e: &'x int = foo(x, &z, |_x, _y, z| z ); // This would result in an error, but it is not reported by typeck // anymore but rather borrowck. Therefore, it doesn't end up diff --git a/src/test/compile-fail/unique-pinned-nocopy.rs b/src/test/compile-fail/unique-pinned-nocopy.rs index 1eebc7701328c..12eef71f38bb3 100644 --- a/src/test/compile-fail/unique-pinned-nocopy.rs +++ b/src/test/compile-fail/unique-pinned-nocopy.rs @@ -17,7 +17,7 @@ impl Drop for r { } fn main() { - let i = move ~r { b: true }; + let i = ~r { b: true }; let _j = copy i; //~ ERROR copying a value of non-copyable type log(debug, i); } diff --git a/src/test/compile-fail/unique-unique-kind.rs b/src/test/compile-fail/unique-unique-kind.rs index 25c42ab4adde5..d36b53eb2ee71 100644 --- a/src/test/compile-fail/unique-unique-kind.rs +++ b/src/test/compile-fail/unique-unique-kind.rs @@ -13,5 +13,5 @@ fn f(_i: T) { fn main() { let i = ~@100; - f(move i); //~ ERROR does not fulfill `Owned` + f(i); //~ ERROR does not fulfill `Owned` } diff --git a/src/test/compile-fail/unique-vec-res.rs b/src/test/compile-fail/unique-vec-res.rs index 28a7b37d6e20b..4ff9dd6f9914e 100644 --- a/src/test/compile-fail/unique-vec-res.rs +++ b/src/test/compile-fail/unique-vec-res.rs @@ -24,8 +24,8 @@ fn f(+_i: ~[T], +_j: ~[T]) { fn main() { let i1 = @mut 0; let i2 = @mut 1; - let r1 = move ~[~r { i: i1 }]; - let r2 = move ~[~r { i: i2 }]; + let r1 = ~[~r { i: i1 }]; + let r2 = ~[~r { i: i2 }]; f(copy r1, copy r2); //~^ ERROR copying a value of non-copyable type //~^^ ERROR copying a value of non-copyable type diff --git a/src/test/compile-fail/unsendable-class.rs b/src/test/compile-fail/unsendable-class.rs index e660884e40b9e..8e9ce5f97fc1d 100644 --- a/src/test/compile-fail/unsendable-class.rs +++ b/src/test/compile-fail/unsendable-class.rs @@ -26,5 +26,5 @@ fn foo(i:int, j: @~str) -> foo { fn main() { let cat = ~"kitty"; let (_, ch) = pipes::stream(); //~ ERROR does not fulfill `Owned` - ch.send(foo(42, @(move cat))); //~ ERROR does not fulfill `Owned` + ch.send(foo(42, @(cat))); //~ ERROR does not fulfill `Owned` } diff --git a/src/test/compile-fail/vec-res-add.rs b/src/test/compile-fail/vec-res-add.rs index f21a202dcd82b..b06f91d50f25c 100644 --- a/src/test/compile-fail/vec-res-add.rs +++ b/src/test/compile-fail/vec-res-add.rs @@ -22,8 +22,8 @@ impl Drop for r { fn main() { // This can't make sense as it would copy the classes - let i = move ~[r(0)]; - let j = move ~[r(1)]; + let i = ~[r(0)]; + let j = ~[r(1)]; let k = i + j; log(debug, j); } diff --git a/src/test/pretty/doc-comments.rs b/src/test/pretty/doc-comments.rs index d3e7c7b44dd1b..a866afd240592 100644 --- a/src/test/pretty/doc-comments.rs +++ b/src/test/pretty/doc-comments.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -19,6 +19,14 @@ fn b() { //! some single line inner-docs } +////////////////////////////////// +// some single-line non-doc comment preceded by a separator + +////////////////////////////////// +/// some single-line outer-docs preceded by a separator +/// (and trailing whitespaces) +fn c() { } + /* * some multi-line non-doc comment */ @@ -26,17 +34,28 @@ fn b() { /** * some multi-line outer-docs */ -fn c() { } +fn d() { } -fn d() { +fn e() { /*! * some multi-line inner-docs */ } +/********************************/ +/* + * some multi-line non-doc comment preceded by a separator + */ + +/********************************/ +/** + * some multi-line outer-docs preceded by a separator + */ +fn f() { } + #[doc = "unsugared outer doc-comments work also"] -fn e() { } +fn g() { } -fn f() { +fn h() { #[doc = "as do inner ones"]; } diff --git a/src/test/run-fail/out-of-stack-managed-box.rs b/src/test/run-fail/out-of-stack-managed-box.rs index 85857486cbbb7..9dcdaacb3c1a4 100644 --- a/src/test/run-fail/out-of-stack-managed-box.rs +++ b/src/test/run-fail/out-of-stack-managed-box.rs @@ -15,11 +15,11 @@ // error-pattern:ran out of stack fn main() { - eat(move @0); + eat(@0); } fn eat( +a: @int ) { - eat(move a) + eat(a) } diff --git a/src/test/run-fail/out-of-stack-owned-box.rs b/src/test/run-fail/out-of-stack-owned-box.rs index ef5101d1a9cd5..d4bc70f43ef6e 100644 --- a/src/test/run-fail/out-of-stack-owned-box.rs +++ b/src/test/run-fail/out-of-stack-owned-box.rs @@ -11,11 +11,11 @@ // xfail-test // error-pattern:ran out of stack fn main() { - eat(move ~0); + eat(~0); } fn eat( +a: ~int ) { - eat(move a) + eat(a) } diff --git a/src/test/run-fail/too-much-recursion-unwinding.rs b/src/test/run-fail/too-much-recursion-unwinding.rs index b6a9bce934fa9..fbea8022cfc3c 100644 --- a/src/test/run-fail/too-much-recursion-unwinding.rs +++ b/src/test/run-fail/too-much-recursion-unwinding.rs @@ -39,6 +39,6 @@ fn r(recursed: *mut bool) -> r { fn main() { let mut recursed = false; - let _r = r(ptr::mut_addr_of(&recursed)); + let _r = r(&mut recursed); recurse(); } diff --git a/src/test/run-fail/unwind-box-res.rs b/src/test/run-fail/unwind-box-res.rs index f544438a7cae1..ba8f2fa37cb3b 100644 --- a/src/test/run-fail/unwind-box-res.rs +++ b/src/test/run-fail/unwind-box-res.rs @@ -36,7 +36,7 @@ fn main() { unsafe { let i1 = ~0; let i1p = cast::reinterpret_cast(&i1); - cast::forget(move i1); + cast::forget(i1); let x = @r(i1p); failfn(); log(error, x); diff --git a/src/test/run-fail/unwind-closure.rs b/src/test/run-fail/unwind-closure.rs index 34257b15b7fd8..6d52046b3e2fe 100644 --- a/src/test/run-fail/unwind-closure.rs +++ b/src/test/run-fail/unwind-closure.rs @@ -16,6 +16,6 @@ fn f(a: @int) { fn main() { let b = @0; - let g : fn@() = |move b|f(b); + let g : fn@() = || f(b); g(); } diff --git a/src/test/run-fail/unwind-move.rs b/src/test/run-fail/unwind-move.rs index 539896e831319..b2d30688ec55d 100644 --- a/src/test/run-fail/unwind-move.rs +++ b/src/test/run-fail/unwind-move.rs @@ -15,5 +15,5 @@ fn f(-_a: @int) { fn main() { let a = @0; - f(move a); + f(a); } diff --git a/src/test/run-fail/unwind-resource-fail.rs b/src/test/run-fail/unwind-resource-fail.rs index 8b9d1a6645714..0d57e9279bc72 100644 --- a/src/test/run-fail/unwind-resource-fail.rs +++ b/src/test/run-fail/unwind-resource-fail.rs @@ -19,5 +19,5 @@ fn r(i: int) -> r { r { i: i } } fn main() { @0; - let r = move r(0); + let r = r(0); } diff --git a/src/test/run-fail/unwind-resource-fail2.rs b/src/test/run-fail/unwind-resource-fail2.rs index 9c2c1a24a5e66..0b33326abe719 100644 --- a/src/test/run-fail/unwind-resource-fail2.rs +++ b/src/test/run-fail/unwind-resource-fail2.rs @@ -20,6 +20,6 @@ fn r(i: int) -> r { r { i: i } } fn main() { @0; - let r = move r(0); + let r = r(0); fail!(); } diff --git a/src/test/run-pass/alt-ref-binding-in-guard-3256.rs b/src/test/run-pass/alt-ref-binding-in-guard-3256.rs index a04d8d4618a27..4474aec3d2e50 100644 --- a/src/test/run-pass/alt-ref-binding-in-guard-3256.rs +++ b/src/test/run-pass/alt-ref-binding-in-guard-3256.rs @@ -10,7 +10,7 @@ pub fn main() { let x = Some(private::exclusive(true)); - match move x { + match x { Some(ref z) if z.with(|b| *b) => { do z.with |b| { assert *b; } }, diff --git a/src/test/run-pass/argument-passing.rs b/src/test/run-pass/argument-passing.rs index e58dc29578d5f..ba9266b8a30f2 100644 --- a/src/test/run-pass/argument-passing.rs +++ b/src/test/run-pass/argument-passing.rs @@ -24,7 +24,7 @@ fn f2(a: int, f: fn(int)) -> int { f(1); return a; } pub fn main() { let mut a = X {mut x: 1}, b = 2, c = 3; - assert (f1(a, &mut b, move c) == 6); + assert (f1(a, &mut b, c) == 6); assert (a.x == 0); assert (b == 10); assert (f2(a.x, |x| a.x = 50 ) == 0); diff --git a/src/test/run-pass/auto-encode.rs b/src/test/run-pass/auto-encode.rs index 53c572e75d099..d4171ceb70fd2 100644 --- a/src/test/run-pass/auto-encode.rs +++ b/src/test/run-pass/auto-encode.rs @@ -46,7 +46,7 @@ fn test_ebml { impl Pushable for ~[T] { fn push_val(&mut self, +t: T) { - self.push(move t); + self.push(t); } } diff --git a/src/test/run-pass/bind-by-move.rs b/src/test/run-pass/bind-by-move.rs index bdcc629566462..1e836740f8e81 100644 --- a/src/test/run-pass/bind-by-move.rs +++ b/src/test/run-pass/bind-by-move.rs @@ -17,8 +17,8 @@ fn dispose(+_x: arc::ARC) unsafe { } pub fn main() { let p = arc::arc(true); let x = Some(p); - match move x { - Some(move z) => { dispose(z); }, + match x { + Some(z) => { dispose(z); }, None => fail!() } } diff --git a/src/test/run-pass/borrowck-move-from-unsafe-ptr-ok.rs b/src/test/run-pass/borrowck-move-from-unsafe-ptr-ok.rs index b54791328a0cb..2d83e9746b580 100644 --- a/src/test/run-pass/borrowck-move-from-unsafe-ptr-ok.rs +++ b/src/test/run-pass/borrowck-move-from-unsafe-ptr-ok.rs @@ -12,7 +12,7 @@ fn bar(x: *~int) -> ~int { unsafe { - let y = move *x; + let y = *x; return y; } } diff --git a/src/test/run-pass/cap-clause-move.rs b/src/test/run-pass/cap-clause-move.rs index dd4c7ba6a85cb..e27434400c185 100644 --- a/src/test/run-pass/cap-clause-move.rs +++ b/src/test/run-pass/cap-clause-move.rs @@ -11,21 +11,21 @@ pub fn main() { let x = ~1; let y = ptr::addr_of(&(*x)) as uint; - let lam_move = fn@(move x) -> uint { ptr::addr_of(&(*x)) as uint }; + let lam_move = fn@() -> uint { ptr::addr_of(&(*x)) as uint }; assert lam_move() == y; let x = ~2; let y = ptr::addr_of(&(*x)) as uint; - let lam_move: fn@() -> uint = |move x| ptr::addr_of(&(*x)) as uint; + let lam_move: fn@() -> uint = || ptr::addr_of(&(*x)) as uint; assert lam_move() == y; let x = ~3; let y = ptr::addr_of(&(*x)) as uint; - let snd_move = fn~(move x) -> uint { ptr::addr_of(&(*x)) as uint }; + let snd_move = fn~() -> uint { ptr::addr_of(&(*x)) as uint }; assert snd_move() == y; let x = ~4; let y = ptr::addr_of(&(*x)) as uint; - let lam_move: fn~() -> uint = |move x| ptr::addr_of(&(*x)) as uint; + let lam_move: fn~() -> uint = || ptr::addr_of(&(*x)) as uint; assert lam_move() == y; } diff --git a/src/test/run-pass/capture_nil.rs b/src/test/run-pass/capture_nil.rs index 6c052b95a2bc5..b77e91c8d212c 100644 --- a/src/test/run-pass/capture_nil.rs +++ b/src/test/run-pass/capture_nil.rs @@ -28,7 +28,7 @@ use core::pipes::*; fn foo(&&x: ()) -> Port<()> { let (p, c) = stream::<()>(); - do task::spawn() |copy x| { + do task::spawn() { c.send(x); } p diff --git a/src/test/run-pass/class-poly-methods.rs b/src/test/run-pass/class-poly-methods.rs index b7e638f40e8c0..5ef5e55b7293e 100644 --- a/src/test/run-pass/class-poly-methods.rs +++ b/src/test/run-pass/class-poly-methods.rs @@ -26,7 +26,7 @@ fn cat(in_x : uint, in_y : int, -in_info: ~[U]) -> cat { cat { meows: in_x, how_hungry: in_y, - info: move in_info + info: in_info } } diff --git a/src/test/run-pass/const-enum-newtype-align.rs b/src/test/run-pass/const-enum-newtype-align.rs new file mode 100644 index 0000000000000..9c9013ef86082 --- /dev/null +++ b/src/test/run-pass/const-enum-newtype-align.rs @@ -0,0 +1,17 @@ +// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +enum E = u32; +struct S { a: u8, b: E } +const C: S = S { a: 0xA5, b: E(0xDEADBEEF) }; + +pub fn main() { + assert C.b == 0xDEADBEEF; +} diff --git a/src/test/run-pass/dvec-test.rs b/src/test/run-pass/dvec-test.rs index a0c6b666554a3..cb8b1c5f25f27 100644 --- a/src/test/run-pass/dvec-test.rs +++ b/src/test/run-pass/dvec-test.rs @@ -31,6 +31,6 @@ pub fn main() { assert *e == exp[i]; } - let v = dvec::unwrap(move d); + let v = dvec::unwrap(d); assert v == exp; } diff --git a/src/test/run-pass/fn-bare-spawn.rs b/src/test/run-pass/fn-bare-spawn.rs index 163063ab745d5..c875b805ea3ca 100644 --- a/src/test/run-pass/fn-bare-spawn.rs +++ b/src/test/run-pass/fn-bare-spawn.rs @@ -11,7 +11,7 @@ // This is what the signature to spawn should look like with bare functions fn spawn(val: T, f: extern fn(T)) { - f(move val); + f(val); } fn f(+i: int) { diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index d7a285d58e662..6a12704d4b4b5 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -39,7 +39,7 @@ mod map_reduce { for inputs.each |i| { let ctrl = ctrl.clone(); let i = copy *i; - task::spawn(|move i| map_task(ctrl.clone(), copy i) ); + task::spawn(|| map_task(ctrl.clone(), copy i) ); } } diff --git a/src/test/run-pass/init-res-into-things.rs b/src/test/run-pass/init-res-into-things.rs index 0605fac3677bf..0185b19b48177 100644 --- a/src/test/run-pass/init-res-into-things.rs +++ b/src/test/run-pass/init-res-into-things.rs @@ -32,7 +32,7 @@ fn r(i: @mut int) -> r { fn test_box() { let i = @mut 0; { - let a = move @r(i); + let a = @r(i); } assert *i == 1; } @@ -40,7 +40,7 @@ fn test_box() { fn test_rec() { let i = @mut 0; { - let a = move Box {x: r(i)}; + let a = Box {x: r(i)}; } assert *i == 1; } @@ -52,7 +52,7 @@ fn test_tag() { let i = @mut 0; { - let a = move t0(r(i)); + let a = t0(r(i)); } assert *i == 1; } @@ -60,7 +60,7 @@ fn test_tag() { fn test_tup() { let i = @mut 0; { - let a = move (r(i), 0); + let a = (r(i), 0); } assert *i == 1; } @@ -68,7 +68,7 @@ fn test_tup() { fn test_unique() { let i = @mut 0; { - let a = move ~r(i); + let a = ~r(i); } assert *i == 1; } @@ -76,7 +76,7 @@ fn test_unique() { fn test_box_rec() { let i = @mut 0; { - let a = move @Box { + let a = @Box { x: r(i) }; } diff --git a/src/test/run-pass/intrinsic-move-val.rs b/src/test/run-pass/intrinsic-move-val.rs index b17eb37438a50..9e8e9d8bc15be 100644 --- a/src/test/run-pass/intrinsic-move-val.rs +++ b/src/test/run-pass/intrinsic-move-val.rs @@ -18,7 +18,7 @@ pub fn main() { unsafe { let mut x = @1; let mut y = @2; - rusti::move_val(&mut y, move x); + rusti::move_val(&mut y, x); assert *y == 1; } } diff --git a/src/test/run-pass/issue-1895.rs b/src/test/run-pass/issue-1895.rs index 3d20eb813d8b5..42c6ae38b6afb 100644 --- a/src/test/run-pass/issue-1895.rs +++ b/src/test/run-pass/issue-1895.rs @@ -10,7 +10,7 @@ pub fn main() { let x = 1; - let y = fn@(move x) -> int { + let y = fn@() -> int { x }(); } diff --git a/src/test/run-pass/issue-2185.rs b/src/test/run-pass/issue-2185.rs index ff35b81aad1f6..f3f7f4dacbad4 100644 --- a/src/test/run-pass/issue-2185.rs +++ b/src/test/run-pass/issue-2185.rs @@ -35,11 +35,11 @@ fn filter>(self: IA, prd: fn@(A) -> bool, blk: fn(A)) { } fn foldl>(self: IA, +b0: B, blk: fn(B, A) -> B) -> B { - let mut b = move b0; + let mut b = b0; do self.iter |a| { - b = move blk(b, a); + b = blk(b, a); } - move b + b } fn range(lo: uint, hi: uint, it: fn(uint)) { diff --git a/src/test/run-pass/issue-2383.rs b/src/test/run-pass/issue-2383.rs index e45d9d6055520..a7afa1d6f3494 100644 --- a/src/test/run-pass/issue-2383.rs +++ b/src/test/run-pass/issue-2383.rs @@ -11,10 +11,9 @@ // except according to those terms. extern mod std; -use std::deque; use std::deque::Deque; pub fn main() { - let Q = deque::create(); - Q.add_back(10); + let mut q = Deque::new(); + q.add_back(10); } diff --git a/src/test/run-pass/issue-2718.rs b/src/test/run-pass/issue-2718.rs index 0cae04b60bc74..8472f0158bb62 100644 --- a/src/test/run-pass/issue-2718.rs +++ b/src/test/run-pass/issue-2718.rs @@ -20,6 +20,7 @@ pub mod pipes { mut payload: Option } + #[deriving_eq] pub enum state { empty, full, @@ -27,13 +28,6 @@ pub mod pipes { terminated } - pub impl state : cmp::Eq { - pure fn eq(&self, other: &state) -> bool { - ((*self) as uint) == ((*other) as uint) - } - pure fn ne(&self, other: &state) -> bool { !(*self).eq(other) } - } - pub type packet = { mut state: state, mut blocked_task: Option, @@ -61,18 +55,18 @@ pub mod pipes { // We should consider moving this to ::core::unsafe, although I // suspect graydon would want us to use void pointers instead. pub unsafe fn uniquify(+x: *T) -> ~T { - unsafe { cast::transmute(move x) } + unsafe { cast::transmute(x) } } pub fn swap_state_acq(+dst: &mut state, src: state) -> state { unsafe { - transmute(rusti::atomic_xchg_acq(transmute(move dst), src as int)) + transmute(rusti::atomic_xchg_acq(transmute(dst), src as int)) } } pub fn swap_state_rel(+dst: &mut state, src: state) -> state { unsafe { - transmute(rusti::atomic_xchg_rel(transmute(move dst), src as int)) + transmute(rusti::atomic_xchg_rel(transmute(dst), src as int)) } } @@ -80,20 +74,20 @@ pub mod pipes { let p = p.unwrap(); let p = unsafe { uniquify(p) }; assert (*p).payload.is_none(); - (*p).payload = move Some(move payload); + (*p).payload = Some(payload); let old_state = swap_state_rel(&mut (*p).state, full); match old_state { empty => { // Yay, fastpath. // The receiver will eventually clean this up. - unsafe { forget(move p); } + unsafe { forget(p); } } full => { fail!(~"duplicate send") } blocked => { // The receiver will eventually clean this up. - unsafe { forget(move p); } + unsafe { forget(p); } } terminated => { // The receiver will never receive this. Rely on drop_glue @@ -113,7 +107,7 @@ pub mod pipes { full => { let mut payload = None; payload <-> (*p).payload; - return Some(option::unwrap(move payload)) + return Some(option::unwrap(payload)) } terminated => { assert old_state == terminated; @@ -128,7 +122,7 @@ pub mod pipes { match swap_state_rel(&mut (*p).state, terminated) { empty | blocked => { // The receiver will eventually clean up. - unsafe { forget(move p) } + unsafe { forget(p) } } full => { // This is impossible @@ -145,7 +139,7 @@ pub mod pipes { match swap_state_rel(&mut (*p).state, terminated) { empty => { // the sender will clean up - unsafe { forget(move p) } + unsafe { forget(p) } } blocked => { // this shouldn't happen. @@ -161,12 +155,12 @@ pub mod pipes { mut p: Option<*packet>, } - pub impl send_packet : Drop { + pub impl Drop for send_packet { fn finalize(&self) { if self.p != None { let mut p = None; p <-> self.p; - sender_terminate(option::unwrap(move p)) + sender_terminate(option::unwrap(p)) } } } @@ -175,7 +169,7 @@ pub mod pipes { fn unwrap() -> *packet { let mut p = None; p <-> self.p; - option::unwrap(move p) + option::unwrap(p) } } @@ -189,12 +183,12 @@ pub mod pipes { mut p: Option<*packet>, } - pub impl recv_packet : Drop { + pub impl Drop for recv_packet { fn finalize(&self) { if self.p != None { let mut p = None; p <-> self.p; - receiver_terminate(option::unwrap(move p)) + receiver_terminate(option::unwrap(p)) } } } @@ -203,7 +197,7 @@ pub mod pipes { fn unwrap() -> *packet { let mut p = None; p <-> self.p; - option::unwrap(move p) + option::unwrap(p) } } @@ -231,9 +225,9 @@ pub mod pingpong { let addr : *::pipes::send_packet = match &p { &ping(ref x) => { cast::transmute(ptr::addr_of(x)) } }; - let liberated_value = move *addr; - cast::forget(move p); - move liberated_value + let liberated_value = *addr; + cast::forget(p); + liberated_value } } @@ -242,9 +236,9 @@ pub mod pingpong { let addr : *::pipes::send_packet = match &p { &pong(ref x) => { cast::transmute(ptr::addr_of(x)) } }; - let liberated_value = move *addr; - cast::forget(move p); - move liberated_value + let liberated_value = *addr; + cast::forget(p); + liberated_value } } @@ -262,16 +256,16 @@ pub mod pingpong { pub fn do_ping(-c: ping) -> pong { let (sp, rp) = ::pipes::entangle(); - ::pipes::send(move c, pingpong::ping(move sp)); - move rp + ::pipes::send(c, pingpong::ping(sp)); + rp } pub fn do_pong(-c: pong) -> (ping, ()) { - let packet = ::pipes::recv(move c); + let packet = ::pipes::recv(c); if packet.is_none() { fail!(~"sender closed the connection") } - (pingpong::liberate_pong(option::unwrap(move packet)), ()) + (pingpong::liberate_pong(option::unwrap(packet)), ()) } } @@ -282,32 +276,32 @@ pub mod pingpong { pub type pong = ::pipes::send_packet; pub fn do_ping(-c: ping) -> (pong, ()) { - let packet = ::pipes::recv(move c); + let packet = ::pipes::recv(c); if packet.is_none() { fail!(~"sender closed the connection") } - (pingpong::liberate_ping(option::unwrap(move packet)), ()) + (pingpong::liberate_ping(option::unwrap(packet)), ()) } pub fn do_pong(-c: pong) -> ping { let (sp, rp) = ::pipes::entangle(); - ::pipes::send(move c, pingpong::pong(move sp)); - move rp + ::pipes::send(c, pingpong::pong(sp)); + rp } } } fn client(-chan: pingpong::client::ping) { - let chan = pingpong::client::do_ping(move chan); + let chan = pingpong::client::do_ping(chan); log(error, ~"Sent ping"); - let (_chan, _data) = pingpong::client::do_pong(move chan); + let (_chan, _data) = pingpong::client::do_pong(chan); log(error, ~"Received pong"); } fn server(-chan: pingpong::server::ping) { - let (chan, _data) = pingpong::server::do_ping(move chan); + let (chan, _data) = pingpong::server::do_ping(chan); log(error, ~"Received ping"); - let _chan = pingpong::server::do_pong(move chan); + let _chan = pingpong::server::do_pong(chan); log(error, ~"Sent pong"); } @@ -319,12 +313,12 @@ pub fn main() { let client_ = ~mut Some(client_); let server_ = ~mut Some(server_); - task::spawn {|move client_| + task::spawn {|client_| let mut client__ = none; *client_ <-> client__; client(option::unwrap(client__)); }; - task::spawn {|move server_| + task::spawn {|server_| let mut server_ˊ = none; *server_ <-> server_ˊ; server(option::unwrap(server_ˊ)); diff --git a/src/test/run-pass/issue-2834.rs b/src/test/run-pass/issue-2834.rs index b78cefe1c95e4..84e0f20e61b11 100644 --- a/src/test/run-pass/issue-2834.rs +++ b/src/test/run-pass/issue-2834.rs @@ -19,7 +19,7 @@ proto! streamp ( fn rendezvous() { let (c, s) = streamp::init(); - let streams: ~[streamp::client::open] = ~[move c]; + let streams: ~[streamp::client::open] = ~[c]; error!("%?", streams[0]); } diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index eadfa82619acd..9a726bedbc340 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -60,7 +60,7 @@ fn square_from_char(c: char) -> square { } fn read_board_grid(+in: rdr) -> ~[~[square]] { - let in = (move in) as io::Reader; + let in = (in) as io::Reader; let mut grid = ~[]; for in.each_line |line| { let mut row = ~[]; diff --git a/src/test/run-pass/issue-2930.rs b/src/test/run-pass/issue-2930.rs index 4b6985f057ead..6d22a2ea5edcf 100644 --- a/src/test/run-pass/issue-2930.rs +++ b/src/test/run-pass/issue-2930.rs @@ -17,5 +17,5 @@ proto! stream ( pub fn main() { let (bc, _bp) = stream::init(); - stream::client::send(move bc, ~"abc"); + stream::client::send(bc, ~"abc"); } diff --git a/src/test/run-pass/issue-3168.rs b/src/test/run-pass/issue-3168.rs index 02b147e65fce1..d40bf6e32cf87 100644 --- a/src/test/run-pass/issue-3168.rs +++ b/src/test/run-pass/issue-3168.rs @@ -12,15 +12,15 @@ pub fn main() { let (p,c) = pipes::stream(); - do task::try |move c| { + do task::try || { let (p2,c2) = pipes::stream(); - do task::spawn |move p2| { + do task::spawn || { p2.recv(); error!("sibling fails"); fail!(); } let (p3,c3) = pipes::stream(); - c.send(move c3); + c.send(c3); c2.send(()); error!("child blocks"); p3.recv(); diff --git a/src/test/run-pass/issue-3176.rs b/src/test/run-pass/issue-3176.rs index b5f2a1d22a6e5..fac73d07b6642 100644 --- a/src/test/run-pass/issue-3176.rs +++ b/src/test/run-pass/issue-3176.rs @@ -14,19 +14,19 @@ use pipes::{Select2, Selectable}; pub fn main() { let (p,c) = pipes::stream(); - do task::try |move c| { + do task::try || { let (p2,c2) = pipes::stream(); - do task::spawn |move p2| { + do task::spawn || { p2.recv(); error!("sibling fails"); fail!(); } let (p3,c3) = pipes::stream(); - c.send(move c3); + c.send(c3); c2.send(()); error!("child blocks"); let (p, c) = pipes::stream(); - (move p, move p3).select(); + (p, p3).select(); c.send(()); }; error!("parent tries"); diff --git a/src/test/run-pass/issue-3220.rs b/src/test/run-pass/issue-3220.rs index 71c83e02617ff..ef65531e5546f 100644 --- a/src/test/run-pass/issue-3220.rs +++ b/src/test/run-pass/issue-3220.rs @@ -23,5 +23,5 @@ impl thing { fn f(self) {} } pub fn main() { let z = thing(); - (move z).f(); + (z).f(); } diff --git a/src/test/run-pass/issue-3447.rs b/src/test/run-pass/issue-3447.rs index 18b47e2925dd2..0bcc5983eb719 100644 --- a/src/test/run-pass/issue-3447.rs +++ b/src/test/run-pass/issue-3447.rs @@ -20,7 +20,7 @@ impl list{ next: option::None }; - self.next = Some(@(move newList)); + self.next = Some(@(newList)); } } diff --git a/src/test/run-pass/issue-3563-3.rs b/src/test/run-pass/issue-3563-3.rs index 88f31189a0c8f..c4f4aa46a8a42 100644 --- a/src/test/run-pass/issue-3563-3.rs +++ b/src/test/run-pass/issue-3563-3.rs @@ -23,8 +23,7 @@ extern mod std; use io::WriterUtil; // Represents a position on a canvas. -struct Point -{ +struct Point { x: int, y: int, } @@ -108,8 +107,7 @@ impl AsciiArt // Allows AsciiArt to be converted to a string using the libcore ToStr trait. // Note that the %s fmt! specifier will not call this automatically. -impl AsciiArt : ToStr -{ +impl ToStr for AsciiArt { pure fn to_str(&self) -> ~str { // Convert each line into a string. @@ -139,8 +137,7 @@ trait Canvas // Here we provide an implementation of the Canvas methods for AsciiArt. // Other implementations could also be provided (e.g. for PDF or Apple's Quartz) // and code can use them polymorphically via the Canvas trait. -impl AsciiArt : Canvas -{ +impl Canvas for AsciiArt { fn add_point(&mut self, shape: Point) { self.add_pt(shape.x, shape.y); diff --git a/src/test/run-pass/issue-3609.rs b/src/test/run-pass/issue-3609.rs index 0eacb34b1ef88..6eb540c473726 100644 --- a/src/test/run-pass/issue-3609.rs +++ b/src/test/run-pass/issue-3609.rs @@ -12,7 +12,6 @@ enum Msg fn foo(name: ~str, samples_chan: Chan) { do task::spawn - |copy name| { let callback: SamplesFn = |buffer| diff --git a/src/test/run-pass/issue-3878.rs b/src/test/run-pass/issue-3878.rs index dd41d696b3a93..a5791e3834351 100644 --- a/src/test/run-pass/issue-3878.rs +++ b/src/test/run-pass/issue-3878.rs @@ -11,5 +11,5 @@ pub fn main() { let y = ~1; - move y; + y; } diff --git a/src/test/run-pass/issue-3888-2.rs b/src/test/run-pass/issue-3888-2.rs index 19f05c61ba4ca..06e652cc7cd55 100644 --- a/src/test/run-pass/issue-3888-2.rs +++ b/src/test/run-pass/issue-3888-2.rs @@ -10,8 +10,8 @@ fn vec_peek(v: &r/[T]) -> &r/[T] { // This doesn't work, and should. -// v.view(1, 5) - vec::view(v, 1, 5) +// v.slice(1, 5) + vec::slice(v, 1, 5) } pub fn main() {} diff --git a/src/test/run-pass/issue-3979.rs b/src/test/run-pass/issue-3979.rs index 3ea2ef83296a9..5d48d1e72de1c 100644 --- a/src/test/run-pass/issue-3979.rs +++ b/src/test/run-pass/issue-3979.rs @@ -31,7 +31,7 @@ impl Positioned for Point { } } -impl Point: Movable; +impl Movable for Point; pub fn main() { let p = Point{ x: 1, y: 2}; diff --git a/src/test/run-pass/issue-4016.rs b/src/test/run-pass/issue-4016.rs index 515b342faf3df..307d7974762f7 100644 --- a/src/test/run-pass/issue-4016.rs +++ b/src/test/run-pass/issue-4016.rs @@ -20,7 +20,7 @@ trait JD : Deserializable { } fn exec() { let doc = result::unwrap(json::from_str("")); - let _v: T = deserialize(&json::Deserializer(move doc)); + let _v: T = deserialize(&json::Deserializer(doc)); fail!() } diff --git a/src/test/run-pass/last-use-in-block.rs b/src/test/run-pass/last-use-in-block.rs index 9c04ccdcba0aa..e8083dd3f6b21 100644 --- a/src/test/run-pass/last-use-in-block.rs +++ b/src/test/run-pass/last-use-in-block.rs @@ -13,14 +13,14 @@ fn lp(s: ~str, f: fn(~str) -> T) -> T { while false { let r = f(s); - return (move r); + return (r); } fail!(); } fn apply(s: ~str, f: fn(~str) -> T) -> T { fn g(s: ~str, f: fn(~str) -> T) -> T {f(s)} - g(s, |v| { let r = f(v); move r }) + g(s, |v| { let r = f(v); r }) } pub fn main() {} diff --git a/src/test/run-pass/last-use-in-cap-clause.rs b/src/test/run-pass/last-use-in-cap-clause.rs index e8cb47b373846..2fd2cc9d22b81 100644 --- a/src/test/run-pass/last-use-in-cap-clause.rs +++ b/src/test/run-pass/last-use-in-cap-clause.rs @@ -15,7 +15,7 @@ struct A { a: ~int } fn foo() -> fn@() -> int { let k = ~22; let _u = A {a: copy k}; - return fn@(move k) -> int { 22 }; + return fn@() -> int { 22 }; } pub fn main() { diff --git a/src/test/run-pass/liveness-move-in-loop.rs b/src/test/run-pass/liveness-move-in-loop.rs index f8166e2443d80..8c4b7d57bc201 100644 --- a/src/test/run-pass/liveness-move-in-loop.rs +++ b/src/test/run-pass/liveness-move-in-loop.rs @@ -15,7 +15,7 @@ fn the_loop() { loop { let x = 5; if x > 3 { - list += ~[take(move x)]; + list += ~[take(x)]; } else { break; } diff --git a/src/test/run-pass/log-linearized.rs b/src/test/run-pass/log-linearized.rs index db0b24fca1d2d..152dcb3d4a7a7 100644 --- a/src/test/run-pass/log-linearized.rs +++ b/src/test/run-pass/log-linearized.rs @@ -21,7 +21,7 @@ struct V { v: ~[option] } fn mk() -> @Smallintmap { let mut v: ~[option] = ~[]; - return @Smallintmap {mut v: move v}; + return @Smallintmap {mut v: v}; } fn f() { diff --git a/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs b/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs index 57f7a3f24db21..b5af07207bccd 100644 --- a/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs +++ b/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs @@ -25,7 +25,7 @@ struct F { a: A } impl Serializable for F { fn serialize(s: S) { - self.a.serialize(move s); + self.a.serialize(s); } } diff --git a/src/test/run-pass/move-1-unique.rs b/src/test/run-pass/move-1-unique.rs index 380c969fa1c7d..45ba5eb974811 100644 --- a/src/test/run-pass/move-1-unique.rs +++ b/src/test/run-pass/move-1-unique.rs @@ -13,7 +13,7 @@ struct Triple { x: int, y: int, z: int } fn test(x: bool, foo: ~Triple) -> int { let bar = foo; let mut y: ~Triple; - if x { y = move bar; } else { y = ~Triple{x: 4, y: 5, z: 6}; } + if x { y = bar; } else { y = ~Triple{x: 4, y: 5, z: 6}; } return y.y; } diff --git a/src/test/run-pass/move-1.rs b/src/test/run-pass/move-1.rs index ea6dc94bb8ef4..35cbe6e080cc8 100644 --- a/src/test/run-pass/move-1.rs +++ b/src/test/run-pass/move-1.rs @@ -13,7 +13,7 @@ struct Triple { x: int, y: int, z: int } fn test(x: bool, foo: @Triple) -> int { let bar = foo; let mut y: @Triple; - if x { y = move bar; } else { y = @Triple{x: 4, y: 5, z: 6}; } + if x { y = bar; } else { y = @Triple{x: 4, y: 5, z: 6}; } return y.y; } diff --git a/src/test/run-pass/move-2-unique.rs b/src/test/run-pass/move-2-unique.rs index 133837089b8a3..bc3b5405f1867 100644 --- a/src/test/run-pass/move-2-unique.rs +++ b/src/test/run-pass/move-2-unique.rs @@ -11,4 +11,4 @@ struct X { x: int, y: int, z: int } -pub fn main() { let x = ~X{x: 1, y: 2, z: 3}; let y = move x; assert (y.y == 2); } +pub fn main() { let x = ~X{x: 1, y: 2, z: 3}; let y = x; assert (y.y == 2); } diff --git a/src/test/run-pass/move-2.rs b/src/test/run-pass/move-2.rs index f2b534765cf51..23ec3a178c15a 100644 --- a/src/test/run-pass/move-2.rs +++ b/src/test/run-pass/move-2.rs @@ -11,4 +11,4 @@ struct X { x: int, y: int, z: int } -pub fn main() { let x = @X {x: 1, y: 2, z: 3}; let y = move x; assert (y.y == 2); } +pub fn main() { let x = @X {x: 1, y: 2, z: 3}; let y = x; assert (y.y == 2); } diff --git a/src/test/run-pass/move-3-unique.rs b/src/test/run-pass/move-3-unique.rs index 40d8f9a9bcef7..82b8d2c960921 100644 --- a/src/test/run-pass/move-3-unique.rs +++ b/src/test/run-pass/move-3-unique.rs @@ -15,7 +15,7 @@ struct Triple { x: int, y: int, z: int } fn test(x: bool, foo: ~Triple) -> int { let bar = foo; let mut y: ~Triple; - if x { y = move bar; } else { y = ~Triple {x: 4, y: 5, z: 6}; } + if x { y = bar; } else { y = ~Triple {x: 4, y: 5, z: 6}; } return y.y; } diff --git a/src/test/run-pass/move-3.rs b/src/test/run-pass/move-3.rs index 0e57d0f612689..161dc55f8a34b 100644 --- a/src/test/run-pass/move-3.rs +++ b/src/test/run-pass/move-3.rs @@ -15,7 +15,7 @@ struct Triple { x: int, y: int, z: int } fn test(x: bool, foo: @Triple) -> int { let bar = foo; let mut y: @Triple; - if x { y = move bar; } else { y = @Triple{x: 4, y: 5, z: 6}; } + if x { y = bar; } else { y = @Triple{x: 4, y: 5, z: 6}; } return y.y; } diff --git a/src/test/run-pass/move-4-unique.rs b/src/test/run-pass/move-4-unique.rs index 7b7b816aeb2ab..8845bdfffe146 100644 --- a/src/test/run-pass/move-4-unique.rs +++ b/src/test/run-pass/move-4-unique.rs @@ -14,9 +14,9 @@ struct Triple {a: int, b: int, c: int} fn test(foo: ~Triple) -> ~Triple { let foo = foo; - let bar = move foo; - let baz = move bar; - let quux = move baz; + let bar = foo; + let baz = bar; + let quux = baz; return quux; } diff --git a/src/test/run-pass/move-4.rs b/src/test/run-pass/move-4.rs index cdb48b43b35ba..1a5432620d308 100644 --- a/src/test/run-pass/move-4.rs +++ b/src/test/run-pass/move-4.rs @@ -15,9 +15,9 @@ struct Triple { a: int, b: int, c: int } fn test(foo: @Triple) -> @Triple { let foo = foo; - let bar = move foo; - let baz = move bar; - let quux = move baz; + let bar = foo; + let baz = bar; + let quux = baz; return quux; } diff --git a/src/test/run-pass/move-arg-2-unique.rs b/src/test/run-pass/move-arg-2-unique.rs index e6a3670804bae..21969418c3451 100644 --- a/src/test/run-pass/move-arg-2-unique.rs +++ b/src/test/run-pass/move-arg-2-unique.rs @@ -13,7 +13,7 @@ fn test(-foo: ~~[int]) { assert (foo[0] == 10); } pub fn main() { let x = ~~[10]; // Test forgetting a local by move-in - test(move x); + test(x); // Test forgetting a temporary by move-in. test(~~[10]); diff --git a/src/test/run-pass/move-arg-2.rs b/src/test/run-pass/move-arg-2.rs index 09dc47ab50e00..8c843d2da682f 100644 --- a/src/test/run-pass/move-arg-2.rs +++ b/src/test/run-pass/move-arg-2.rs @@ -13,7 +13,7 @@ fn test(-foo: @~[int]) { assert (foo[0] == 10); } pub fn main() { let x = @~[10]; // Test forgetting a local by move-in - test(move x); + test(x); // Test forgetting a temporary by move-in. test(@~[10]); diff --git a/src/test/run-pass/move-arg.rs b/src/test/run-pass/move-arg.rs index 8e65981ebdf1c..570fa6ee39166 100644 --- a/src/test/run-pass/move-arg.rs +++ b/src/test/run-pass/move-arg.rs @@ -10,4 +10,4 @@ fn test(-foo: int) { assert (foo == 10); } -pub fn main() { let x = 10; test(move x); } +pub fn main() { let x = 10; test(x); } diff --git a/src/test/run-pass/move-nullary-fn.rs b/src/test/run-pass/move-nullary-fn.rs index 0aac8857c598d..0114eeefbfb2d 100644 --- a/src/test/run-pass/move-nullary-fn.rs +++ b/src/test/run-pass/move-nullary-fn.rs @@ -12,7 +12,7 @@ fn f2(-thing: fn@()) { } fn f(-thing: fn@()) { - f2(move thing); + f2(thing); } pub fn main() { diff --git a/src/test/run-pass/move-scalar.rs b/src/test/run-pass/move-scalar.rs index 533543ad138cc..a7ddc4e4cdbe2 100644 --- a/src/test/run-pass/move-scalar.rs +++ b/src/test/run-pass/move-scalar.rs @@ -12,6 +12,6 @@ pub fn main() { let y: int = 42; let mut x: int; - x = move y; + x = y; assert (x == 42); } diff --git a/src/test/run-pass/move-self.rs b/src/test/run-pass/move-self.rs index 170dd520ed6f4..37ce1bce9e659 100644 --- a/src/test/run-pass/move-self.rs +++ b/src/test/run-pass/move-self.rs @@ -4,7 +4,7 @@ struct S { impl S { fn foo(self) { - (move self).bar(); + self.bar(); } fn bar(self) { diff --git a/src/test/run-pass/non-legacy-modes.rs b/src/test/run-pass/non-legacy-modes.rs index 6db971121b758..2a1f94a1d8cdf 100644 --- a/src/test/run-pass/non-legacy-modes.rs +++ b/src/test/run-pass/non-legacy-modes.rs @@ -13,7 +13,7 @@ struct X { } fn apply(x: T, f: fn(T)) { - f(move x); + f(x); } fn check_int(x: int) { diff --git a/src/test/run-pass/option-unwrap.rs b/src/test/run-pass/option-unwrap.rs index 9f787c915e59d..7616ff5007eee 100644 --- a/src/test/run-pass/option-unwrap.rs +++ b/src/test/run-pass/option-unwrap.rs @@ -21,8 +21,8 @@ impl Drop for dtor { } fn unwrap(+o: Option) -> T { - match move o { - Some(move v) => move v, + match o { + Some(v) => v, None => fail!() } } @@ -32,7 +32,7 @@ pub fn main() { { let b = Some(dtor { x:x }); - let c = unwrap(move b); + let c = unwrap(b); } assert *x == 0; diff --git a/src/test/run-pass/pipe-bank-proto.rs b/src/test/run-pass/pipe-bank-proto.rs index d79160a41c44a..bc218e71ede9b 100644 --- a/src/test/run-pass/pipe-bank-proto.rs +++ b/src/test/run-pass/pipe-bank-proto.rs @@ -44,21 +44,21 @@ proto! bank ( ) macro_rules! move_it ( - { $x:expr } => { unsafe { let y = move *ptr::addr_of(&($x)); move y } } + { $x:expr } => { unsafe { let y = *ptr::addr_of(&($x)); y } } ) fn switch(+endp: pipes::RecvPacket, f: fn(+v: Option) -> U) -> U { - f(pipes::try_recv(move endp)) + f(pipes::try_recv(endp)) } -fn move_it(-x: T) -> T { move x } +fn move_it(-x: T) -> T { x } macro_rules! follow ( { $($message:path$(($($x: ident),+))||* -> $next:ident $e:expr)+ } => ( - |m| match move m { + |m| match m { $(Some($message($($($x,)+)* next)) => { let $next = move_it!(next); $e })+ @@ -70,15 +70,15 @@ macro_rules! follow ( fn client_follow(+bank: bank::client::login) { use bank::*; - let bank = client::login(move bank, ~"theincredibleholk", ~"1234"); - let bank = switch(move bank, follow! ( - ok -> connected { move connected } + let bank = client::login(bank, ~"theincredibleholk", ~"1234"); + let bank = switch(bank, follow! ( + ok -> connected { connected } invalid -> _next { fail!(~"bank closed the connected") } )); - let bank = client::deposit(move bank, 100.00); - let bank = client::withdrawal(move bank, 50.00); - switch(move bank, follow! ( + let bank = client::deposit(bank, 100.00); + let bank = client::withdrawal(bank, 50.00); + switch(bank, follow! ( money(m) -> _next { io::println(~"Yay! I got money!"); } @@ -91,8 +91,8 @@ fn client_follow(+bank: bank::client::login) { fn bank_client(+bank: bank::client::login) { use bank::*; - let bank = client::login(move bank, ~"theincredibleholk", ~"1234"); - let bank = match try_recv(move bank) { + let bank = client::login(bank, ~"theincredibleholk", ~"1234"); + let bank = match try_recv(bank) { Some(ok(connected)) => { move_it!(connected) } @@ -100,9 +100,9 @@ fn bank_client(+bank: bank::client::login) { None => { fail!(~"bank closed the connection") } }; - let bank = client::deposit(move bank, 100.00); - let bank = client::withdrawal(move bank, 50.00); - match try_recv(move bank) { + let bank = client::deposit(bank, 100.00); + let bank = client::withdrawal(bank, 50.00); + match try_recv(bank) { Some(money(*)) => { io::println(~"Yay! I got money!"); } diff --git a/src/test/run-pass/pipe-detect-term.rs b/src/test/run-pass/pipe-detect-term.rs index 6831170734d14..2d76542398841 100644 --- a/src/test/run-pass/pipe-detect-term.rs +++ b/src/test/run-pass/pipe-detect-term.rs @@ -32,7 +32,7 @@ pub fn main() { let iotask = &uv::global_loop::get(); pipes::spawn_service(oneshot::init, |p| { - match try_recv(move p) { + match try_recv(p) { Some(*) => { fail!() } None => { } } @@ -47,11 +47,11 @@ pub fn main() { fn failtest() { let (c, p) = oneshot::init(); - do task::spawn_with(move c) |_c| { + do task::spawn_with(c) |_c| { fail!(); } - error!("%?", recv(move p)); + error!("%?", recv(p)); // make sure we get killed if we missed it in the receive. loop { task::yield() } } diff --git a/src/test/run-pass/pipe-peek.rs b/src/test/run-pass/pipe-peek.rs index 7dc1feb24179b..baa5ba5bf00a8 100644 --- a/src/test/run-pass/pipe-peek.rs +++ b/src/test/run-pass/pipe-peek.rs @@ -27,7 +27,7 @@ pub fn main() { assert !pipes::peek(&p); - oneshot::client::signal(move c); + oneshot::client::signal(c); assert pipes::peek(&p); } diff --git a/src/test/run-pass/pipe-pingpong-bounded.rs b/src/test/run-pass/pipe-pingpong-bounded.rs index a3b03daf02fbf..b13b262e8645e 100644 --- a/src/test/run-pass/pipe-pingpong-bounded.rs +++ b/src/test/run-pass/pipe-pingpong-bounded.rs @@ -36,7 +36,7 @@ mod pingpong { pong: mk_packet::() } }; - do pipes::entangle_buffer(move buffer) |buffer, data| { + do pipes::entangle_buffer(buffer) |buffer, data| { data.ping.set_buffer(buffer); data.pong.set_buffer(buffer); ptr::addr_of(&(data.ping)) @@ -53,9 +53,9 @@ mod pingpong { let b = pipe.reuse_buffer(); let s = SendPacketBuffered(ptr::addr_of(&(b.buffer.data.pong))); let c = RecvPacketBuffered(ptr::addr_of(&(b.buffer.data.pong))); - let message = ::pingpong::ping(move s); - ::pipes::send(move pipe, move message); - move c + let message = ::pingpong::ping(s); + ::pipes::send(pipe, message); + c } } pub type ping = pipes::SendPacketBuffered<::pingpong::ping, @@ -74,9 +74,9 @@ mod pingpong { let b = pipe.reuse_buffer(); let s = SendPacketBuffered(ptr::addr_of(&(b.buffer.data.ping))); let c = RecvPacketBuffered(ptr::addr_of(&(b.buffer.data.ping))); - let message = ::pingpong::pong(move s); - ::pipes::send(move pipe, move message); - move c + let message = ::pingpong::pong(s); + ::pipes::send(pipe, message); + c } } pub type pong = pipes::SendPacketBuffered<::pingpong::pong, @@ -91,34 +91,34 @@ mod test { pub fn client(-chan: ::pingpong::client::ping) { use pingpong::client; - let chan = client::ping(move chan); return; + let chan = client::ping(chan); return; log(error, "Sent ping"); - let pong(_chan) = recv(move chan); + let pong(_chan) = recv(chan); log(error, "Received pong"); } pub fn server(-chan: ::pingpong::server::ping) { use pingpong::server; - let ping(chan) = recv(move chan); return; + let ping(chan) = recv(chan); return; log(error, "Received ping"); - let _chan = server::pong(move chan); + let _chan = server::pong(chan); log(error, "Sent pong"); } } pub fn main() { let (client_, server_) = ::pingpong::init(); - let client_ = ~mut Some(move client_); - let server_ = ~mut Some(move server_); - do task::spawn |move client_| { + let client_ = ~mut Some(client_); + let server_ = ~mut Some(server_); + do task::spawn || { let mut client__ = None; *client_ <-> client__; - test::client(option::unwrap(move client__)); + test::client(option::unwrap(client__)); }; - do task::spawn |move server_| { + do task::spawn || { let mut server_ˊ = None; *server_ <-> server_ˊ; - test::server(option::unwrap(move server_ˊ)); + test::server(option::unwrap(server_ˊ)); }; } diff --git a/src/test/run-pass/pipe-pingpong-proto.rs b/src/test/run-pass/pipe-pingpong-proto.rs index 97afbba42c5b5..0d71a2c37d162 100644 --- a/src/test/run-pass/pipe-pingpong-proto.rs +++ b/src/test/run-pass/pipe-pingpong-proto.rs @@ -33,35 +33,35 @@ mod test { pub fn client(-chan: ::pingpong::client::ping) { use pingpong::client; - let chan = client::ping(move chan); + let chan = client::ping(chan); log(error, ~"Sent ping"); - let pong(_chan) = recv(move chan); + let pong(_chan) = recv(chan); log(error, ~"Received pong"); } pub fn server(-chan: ::pingpong::server::ping) { use pingpong::server; - let ping(chan) = recv(move chan); + let ping(chan) = recv(chan); log(error, ~"Received ping"); - let _chan = server::pong(move chan); + let _chan = server::pong(chan); log(error, ~"Sent pong"); } } pub fn main() { let (client_, server_) = pingpong::init(); - let client_ = ~mut Some(move client_); - let server_ = ~mut Some(move server_); + let client_ = ~mut Some(client_); + let server_ = ~mut Some(server_); - do task::spawn |move client_| { + do task::spawn || { let mut client__ = None; *client_ <-> client__; - test::client(option::unwrap(move client__)); + test::client(option::unwrap(client__)); }; - do task::spawn |move server_| { + do task::spawn || { let mut server_ˊ = None; *server_ <-> server_ˊ; - test::server(option::unwrap(move server_ˊ)); + test::server(option::unwrap(server_ˊ)); }; } diff --git a/src/test/run-pass/pipe-presentation-examples.rs b/src/test/run-pass/pipe-presentation-examples.rs index 401c32b67f9d4..7ac6337d1caa1 100644 --- a/src/test/run-pass/pipe-presentation-examples.rs +++ b/src/test/run-pass/pipe-presentation-examples.rs @@ -34,10 +34,10 @@ macro_rules! select_if ( ], )* } => { if $index == $count { - match move pipes::try_recv(move $port) { - $(Some($message($($(move $x,)+)* move next)) => { - let $next = move next; - move $e + match pipes::try_recv($port) { + $(Some($message($($($x,)+)* next)) => { + let $next = next; + $e })+ _ => fail!() } @@ -81,7 +81,7 @@ pub struct Buffer { } -pub impl Buffer : Drop { +pub impl Drop for Buffer { fn finalize(&self) {} } @@ -105,33 +105,33 @@ fn render(_buffer: &Buffer) { } fn draw_frame(+channel: double_buffer::client::acquire) { - let channel = request(move channel); + let channel = request(channel); select! ( channel => { give_buffer(buffer) -> channel { render(&buffer); - release(move channel, move buffer) + release(channel, buffer) } } ); } fn draw_two_frames(+channel: double_buffer::client::acquire) { - let channel = request(move channel); + let channel = request(channel); let channel = select! ( channel => { give_buffer(buffer) -> channel { render(&buffer); - release(move channel, move buffer) + release(channel, buffer) } } ); - let channel = request(move channel); + let channel = request(channel); select! ( channel => { give_buffer(buffer) -> channel { render(&buffer); - release(move channel, move buffer) + release(channel, buffer) } } ); @@ -152,7 +152,7 @@ fn draw_two_frames_bad1(+channel: double_buffer::client::acquire) { channel => { give_buffer(buffer) -> channel { render(&buffer); - release(channel, move buffer) + release(channel, buffer) } } ); @@ -165,9 +165,9 @@ fn draw_two_frames_bad2(+channel: double_buffer::client::acquire) { channel => { give_buffer(buffer) -> channel { render(&buffer); - release(channel, move buffer); + release(channel, buffer); render(&buffer); - release(channel, move buffer); + release(channel, buffer); } } ); diff --git a/src/test/run-pass/pipe-select.rs b/src/test/run-pass/pipe-select.rs index 62765d71398fc..0bf739139cfe1 100644 --- a/src/test/run-pass/pipe-select.rs +++ b/src/test/run-pass/pipe-select.rs @@ -41,24 +41,24 @@ pub fn main() { let c = pipes::spawn_service(stream::init, |p| { error!("waiting for pipes"); - let stream::send(x, p) = recv(move p); + let stream::send(x, p) = recv(p); error!("got pipes"); let (left, right) : (oneshot::server::waiting, oneshot::server::waiting) - = move x; + = x; error!("selecting"); - let (i, _, _) = select(~[move left, move right]); + let (i, _, _) = select(~[left, right]); error!("selected"); assert i == 0; error!("waiting for pipes"); - let stream::send(x, _) = recv(move p); + let stream::send(x, _) = recv(p); error!("got pipes"); let (left, right) : (oneshot::server::waiting, oneshot::server::waiting) - = move x; + = x; error!("selecting"); - let (i, m, _) = select(~[move left, move right]); + let (i, m, _) = select(~[left, right]); error!("selected %?", i); if m.is_some() { assert i == 1; @@ -68,20 +68,20 @@ pub fn main() { let (c1, p1) = oneshot::init(); let (_c2, p2) = oneshot::init(); - let c = send(move c, (move p1, move p2)); + let c = send(c, (p1, p2)); sleep(iotask, 100); - signal(move c1); + signal(c1); let (_c1, p1) = oneshot::init(); let (c2, p2) = oneshot::init(); - send(move c, (move p1, move p2)); + send(c, (p1, p2)); sleep(iotask, 100); - signal(move c2); + signal(c2); test_select2(); } @@ -90,26 +90,26 @@ fn test_select2() { let (ac, ap) = stream::init(); let (bc, bp) = stream::init(); - stream::client::send(move ac, 42); + stream::client::send(ac, 42); - match pipes::select2(move ap, move bp) { + match pipes::select2(ap, bp) { either::Left(*) => { } either::Right(*) => { fail!() } } - stream::client::send(move bc, ~"abc"); + stream::client::send(bc, ~"abc"); error!("done with first select2"); let (ac, ap) = stream::init(); let (bc, bp) = stream::init(); - stream::client::send(move bc, ~"abc"); + stream::client::send(bc, ~"abc"); - match pipes::select2(move ap, move bp) { + match pipes::select2(ap, bp) { either::Left(*) => { fail!() } either::Right(*) => { } } - stream::client::send(move ac, 42); + stream::client::send(ac, 42); } diff --git a/src/test/run-pass/pipe-sleep.rs b/src/test/run-pass/pipe-sleep.rs index ac4829a9c19ad..521c400489e95 100644 --- a/src/test/run-pass/pipe-sleep.rs +++ b/src/test/run-pass/pipe-sleep.rs @@ -26,10 +26,10 @@ proto! oneshot ( pub fn main() { use oneshot::client::*; - let c = pipes::spawn_service(oneshot::init, |p| { recv(move p); }); + let c = pipes::spawn_service(oneshot::init, |p| { recv(p); }); let iotask = &uv::global_loop::get(); sleep(iotask, 500); - signal(move c); + signal(c); } diff --git a/src/test/run-pass/regions-copy-closure.rs b/src/test/run-pass/regions-copy-closure.rs index bfb4ac5f60c99..ff3e115eda9b0 100644 --- a/src/test/run-pass/regions-copy-closure.rs +++ b/src/test/run-pass/regions-copy-closure.rs @@ -13,7 +13,7 @@ struct closure_box { } fn box_it(+x: &r/fn()) -> closure_box/&r { - closure_box {cl: move x} + closure_box {cl: x} } pub fn main() { diff --git a/src/test/run-pass/regions-self-impls.rs b/src/test/run-pass/regions-self-impls.rs index 7b07a8cf1af4d..22eec65b02a07 100644 --- a/src/test/run-pass/regions-self-impls.rs +++ b/src/test/run-pass/regions-self-impls.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Clam { chowder: &int } +struct Clam<'self> { + chowder: &'self int +} -trait get_chowder { - fn get_chowder() -> &self/int; +trait get_chowder<'self> { + fn get_chowder() -> &'self int; } -impl get_chowder for Clam { - fn get_chowder() -> &self/int { return self.chowder; } +impl<'self> get_chowder<'self> for Clam<'self> { + fn get_chowder() -> &'self int { return self.chowder; } } pub fn main() { diff --git a/src/test/run-pass/regions-static-closure.rs b/src/test/run-pass/regions-static-closure.rs index 8b7fbfd3758c0..00f5e695475a2 100644 --- a/src/test/run-pass/regions-static-closure.rs +++ b/src/test/run-pass/regions-static-closure.rs @@ -13,7 +13,7 @@ struct closure_box { } fn box_it(+x: &r/fn()) -> closure_box/&r { - closure_box {cl: move x} + closure_box {cl: x} } fn call_static_closure(cl: closure_box/&static) { @@ -22,5 +22,5 @@ fn call_static_closure(cl: closure_box/&static) { pub fn main() { let cl_box = box_it(|| debug!("Hello, world!")); - call_static_closure(move cl_box); + call_static_closure(cl_box); } diff --git a/src/test/run-pass/resource-assign-is-not-copy.rs b/src/test/run-pass/resource-assign-is-not-copy.rs index ee28c96defcad..af3c92db8f6a1 100644 --- a/src/test/run-pass/resource-assign-is-not-copy.rs +++ b/src/test/run-pass/resource-assign-is-not-copy.rs @@ -29,8 +29,8 @@ pub fn main() { // Even though these look like copies, they are guaranteed not to be { let a = r(i); - let b = (move a, 10); - let (c, _d) = move b; + let b = (a, 10); + let (c, _d) = b; log(debug, c); } assert *i == 1; diff --git a/src/test/run-pass/resource-cycle.rs b/src/test/run-pass/resource-cycle.rs index fb9a1e8117a5b..d47d56b6021b3 100644 --- a/src/test/run-pass/resource-cycle.rs +++ b/src/test/run-pass/resource-cycle.rs @@ -45,10 +45,10 @@ pub fn main() { unsafe { let i1 = ~0; let i1p = cast::reinterpret_cast(&i1); - cast::forget(move i1); + cast::forget(i1); let i2 = ~0; let i2p = cast::reinterpret_cast(&i2); - cast::forget(move i2); + cast::forget(i2); let x1 = @t(Node{ mut next: None, @@ -56,7 +56,7 @@ pub fn main() { let rs = r(i1p); debug!("r = %x", cast::reinterpret_cast::<*r, uint>(&ptr::addr_of(&rs))); - move rs } + rs } }); debug!("x1 = %x, x1.r = %x", @@ -69,7 +69,7 @@ pub fn main() { let rs = r(i2p); debug!("r2 = %x", cast::reinterpret_cast::<*r, uint>(&ptr::addr_of(&rs))); - move rs + rs } }); diff --git a/src/test/run-pass/resource-cycle2.rs b/src/test/run-pass/resource-cycle2.rs index eea5c43bb9955..1b39093c7d05c 100644 --- a/src/test/run-pass/resource-cycle2.rs +++ b/src/test/run-pass/resource-cycle2.rs @@ -45,10 +45,10 @@ pub fn main() { unsafe { let i1 = ~0xA; let i1p = cast::reinterpret_cast(&i1); - cast::forget(move i1); + cast::forget(i1); let i2 = ~0xA; let i2p = cast::reinterpret_cast(&i2); - cast::forget(move i2); + cast::forget(i2); let u1 = U {a: 0xB, b: 0xC, c: i1p}; let u2 = U {a: 0xB, b: 0xC, c: i2p}; diff --git a/src/test/run-pass/resource-cycle3.rs b/src/test/run-pass/resource-cycle3.rs index 544d82e799544..036ca2496698c 100644 --- a/src/test/run-pass/resource-cycle3.rs +++ b/src/test/run-pass/resource-cycle3.rs @@ -54,10 +54,10 @@ pub fn main() { unsafe { let i1 = ~0xA; let i1p = cast::reinterpret_cast(&i1); - cast::forget(move i1); + cast::forget(i1); let i2 = ~0xA; let i2p = cast::reinterpret_cast(&i2); - cast::forget(move i2); + cast::forget(i2); let u1 = U {a: 0xB, b: 0xC, c: i1p}; let u2 = U {a: 0xB, b: 0xC, c: i2p}; diff --git a/src/test/run-pass/resource-destruct.rs b/src/test/run-pass/resource-destruct.rs index 7b5456e21898c..3dc4ca7bd61dc 100644 --- a/src/test/run-pass/resource-destruct.rs +++ b/src/test/run-pass/resource-destruct.rs @@ -30,7 +30,7 @@ fn shrinky_pointer(i: @@mut int) -> shrinky_pointer { pub fn main() { let my_total = @@mut 10; - { let pt = move shrinky_pointer(my_total); assert (pt.look_at() == 10); } + { let pt = shrinky_pointer(my_total); assert (pt.look_at() == 10); } log(error, fmt!("my_total = %d", **my_total)); assert (**my_total == 9); } diff --git a/src/test/run-pass/resource-generic.rs b/src/test/run-pass/resource-generic.rs index 17ce27fa60ad1..eb25f20607f41 100644 --- a/src/test/run-pass/resource-generic.rs +++ b/src/test/run-pass/resource-generic.rs @@ -33,6 +33,6 @@ pub fn main() { let box = @mut 10; fn dec_box(&&i: @mut int) { *i -= 1; } - { let _i = move finish(Arg{val: box, fin: dec_box}); } + { let _i = finish(Arg{val: box, fin: dec_box}); } assert (*box == 9); } diff --git a/src/test/run-pass/rt-sched-1.rs b/src/test/run-pass/rt-sched-1.rs index badd9632cc8a3..cefed420546ea 100644 --- a/src/test/run-pass/rt-sched-1.rs +++ b/src/test/run-pass/rt-sched-1.rs @@ -46,7 +46,7 @@ pub fn main() { }; let fptr = cast::reinterpret_cast(&ptr::addr_of(&f)); rustrt::start_task(new_task_id, fptr); - cast::forget(move f); + cast::forget(f); po.recv(); } } diff --git a/src/test/run-pass/select-macro.rs b/src/test/run-pass/select-macro.rs index 45df9cfa610c9..d576875be10d8 100644 --- a/src/test/run-pass/select-macro.rs +++ b/src/test/run-pass/select-macro.rs @@ -27,18 +27,18 @@ macro_rules! select_if ( $count:expr, $port:path => [ $(type_this $message:path$(($(x $x: ident),+))dont_type_this* - -> $next:ident => { move $e:expr }),+ + -> $next:ident => { $e:expr }),+ ] $(, $ports:path => [ $(type_this $messages:path$(($(x $xs: ident),+))dont_type_this* - -> $nexts:ident => { move $es:expr }),+ + -> $nexts:ident => { $es:expr }),+ ] )* } => { if $index == $count { - match move pipes::try_recv($port) { - $(Some($message($($(move $x,)+)* move next)) => { - let $next = move next; - move $e + match pipes::try_recv($port) { + $(Some($message($($($x,)+)* next)) => { + let $next = next; + $e })+ _ => fail!() } @@ -48,7 +48,7 @@ macro_rules! select_if ( $count + 1 $(, $ports => [ $(type_this $messages$(($(x $xs),+))dont_type_this* - -> $nexts => { move $es }),+ + -> $nexts => { $es }),+ ])* ) } @@ -64,7 +64,7 @@ macro_rules! select ( } => { let index = pipes::selecti([$(($port).header()),+]); select_if!(index, 0 $(, $port => [ - $(type_this $message$(($(x $x),+))dont_type_this* -> $next => { move $e }),+ + $(type_this $message$(($(x $x),+))dont_type_this* -> $next => { $e }),+ ])+) } ) diff --git a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs index d86dc4d56d7dd..fce0889e0a9b8 100644 --- a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs +++ b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs @@ -20,7 +20,7 @@ fn test05() { log(error, *three + n); // will copy x into the closure assert(*three == 3); }; - task::spawn(fn~(move fn_to_send) { + task::spawn(fn~() { test05_start(fn_to_send); }); } diff --git a/src/test/run-pass/static-impl.rs b/src/test/run-pass/static-impl.rs index 870059d1edc52..5e7785c2dbbe8 100644 --- a/src/test/run-pass/static-impl.rs +++ b/src/test/run-pass/static-impl.rs @@ -17,12 +17,12 @@ pub trait plus { mod a { use plus; - pub impl uint: plus { fn plus() -> int { self as int + 20 } } + pub impl plus for uint { fn plus() -> int { self as int + 20 } } } mod b { use plus; - pub impl ~str: plus { fn plus() -> int { 200 } } + pub impl plus for ~str { fn plus() -> int { 200 } } } trait uint_utils { diff --git a/src/test/run-pass/static-method-test.rs b/src/test/run-pass/static-method-test.rs index 3402da6c55c9d..da79bf53fe06c 100644 --- a/src/test/run-pass/static-method-test.rs +++ b/src/test/run-pass/static-method-test.rs @@ -23,13 +23,13 @@ fn andand(x1: T, x2: T) -> T { impl bool_like for bool { static fn select(&&b: bool, +x1: A, +x2: A) -> A { - if b { move x1 } else { move x2 } + if b { x1 } else { x2 } } } impl bool_like for int { static fn select(&&b: int, +x1: A, +x2: A) -> A { - if b != 0 { move x1 } else { move x2 } + if b != 0 { x1 } else { x2 } } } diff --git a/src/test/run-pass/static-methods-in-traits2.rs b/src/test/run-pass/static-methods-in-traits2.rs index 8c61f60eaac2a..b4c28fd52a64c 100644 --- a/src/test/run-pass/static-methods-in-traits2.rs +++ b/src/test/run-pass/static-methods-in-traits2.rs @@ -2,7 +2,7 @@ pub trait Number: NumConv { static pure fn from(n: T) -> Self; } -pub impl float: Number { +pub impl Number for float { static pure fn from(n: T) -> float { n.to_float() } } @@ -10,7 +10,7 @@ pub trait NumConv { pure fn to_float(&self) -> float; } -pub impl float: NumConv { +pub impl NumConv for float { pure fn to_float(&self) -> float { *self } } diff --git a/src/test/run-pass/task-comm-0.rs b/src/test/run-pass/task-comm-0.rs index b66f295e1bad8..aa8a2a9146cbc 100644 --- a/src/test/run-pass/task-comm-0.rs +++ b/src/test/run-pass/task-comm-0.rs @@ -29,7 +29,7 @@ fn test05_start(ch : Chan) { fn test05() { let (po, ch) = pipes::stream(); - task::spawn(|move ch| test05_start(ch) ); + task::spawn(|| test05_start(ch) ); let mut value = po.recv(); log(error, value); value = po.recv(); diff --git a/src/test/run-pass/task-comm-10.rs b/src/test/run-pass/task-comm-10.rs index a5d55fd823bcf..289a728efc39a 100644 --- a/src/test/run-pass/task-comm-10.rs +++ b/src/test/run-pass/task-comm-10.rs @@ -15,7 +15,7 @@ extern mod std; fn start(c: pipes::Chan>) { let (p, ch) = pipes::stream(); - c.send(move ch); + c.send(ch); let mut a; let mut b; @@ -24,12 +24,12 @@ fn start(c: pipes::Chan>) { log(error, a); b = p.recv(); assert b == ~"B"; - log(error, move b); + log(error, b); } pub fn main() { let (p, ch) = pipes::stream(); - let child = task::spawn(|move ch| start(ch) ); + let child = task::spawn(|| start(ch) ); let c = p.recv(); c.send(~"A"); diff --git a/src/test/run-pass/task-comm-11.rs b/src/test/run-pass/task-comm-11.rs index 498b0b7423868..996566abcd89f 100644 --- a/src/test/run-pass/task-comm-11.rs +++ b/src/test/run-pass/task-comm-11.rs @@ -15,11 +15,11 @@ extern mod std; fn start(c: pipes::Chan>) { let (p, ch) = pipes::stream(); - c.send(move ch); + c.send(ch); } pub fn main() { let (p, ch) = pipes::stream(); - let child = task::spawn(|move ch| start(ch) ); + let child = task::spawn(|| start(ch) ); let c = p.recv(); } diff --git a/src/test/run-pass/task-comm-12.rs b/src/test/run-pass/task-comm-12.rs index d32e9454f533b..9f23ab1c9dfa6 100644 --- a/src/test/run-pass/task-comm-12.rs +++ b/src/test/run-pass/task-comm-12.rs @@ -17,7 +17,7 @@ fn start(&&task_number: int) { debug!("Started / Finished task."); } fn test00() { let i: int = 0; let mut result = None; - do task::task().future_result(|+r| { result = Some(move r); }).spawn { + do task::task().future_result(|+r| { result = Some(r); }).spawn { start(i) } @@ -29,7 +29,7 @@ fn test00() { } // Try joining tasks that have already finished. - option::unwrap(move result).recv(); + option::unwrap(result).recv(); debug!("Joined task."); } diff --git a/src/test/run-pass/task-comm-13.rs b/src/test/run-pass/task-comm-13.rs index c52facf230be9..4ee23ec54d6cb 100644 --- a/src/test/run-pass/task-comm-13.rs +++ b/src/test/run-pass/task-comm-13.rs @@ -22,6 +22,6 @@ fn start(c: pipes::Chan, start: int, number_of_messages: int) { pub fn main() { debug!("Check that we don't deadlock."); let (p, ch) = pipes::stream(); - task::try(|move ch| start(ch, 0, 10) ); + task::try(|| start(ch, 0, 10) ); debug!("Joined task"); } diff --git a/src/test/run-pass/task-comm-14.rs b/src/test/run-pass/task-comm-14.rs index dbf8c03493550..f32fbdd04e62e 100644 --- a/src/test/run-pass/task-comm-14.rs +++ b/src/test/run-pass/task-comm-14.rs @@ -19,8 +19,8 @@ pub fn main() { while (i > 0) { log(debug, i); let (p, ch) = pipes::stream(); - po.add(move p); - task::spawn({let i = i; |move ch| child(i, ch)}); + po.add(p); + task::spawn({let i = i; || child(i, ch)}); i = i - 1; } diff --git a/src/test/run-pass/task-comm-15.rs b/src/test/run-pass/task-comm-15.rs index c65e10d36b7e6..957066005acda 100644 --- a/src/test/run-pass/task-comm-15.rs +++ b/src/test/run-pass/task-comm-15.rs @@ -28,6 +28,6 @@ pub fn main() { // the child's point of view the receiver may die. We should // drop messages on the floor in this case, and not crash! let (p, ch) = pipes::stream(); - task::spawn(|move ch| start(ch, 10)); + task::spawn(|| start(ch, 10)); p.recv(); } diff --git a/src/test/run-pass/task-comm-16.rs b/src/test/run-pass/task-comm-16.rs index afc9290b62db7..648a54d190fa4 100644 --- a/src/test/run-pass/task-comm-16.rs +++ b/src/test/run-pass/task-comm-16.rs @@ -100,7 +100,7 @@ fn test_tag() { fn test_chan() { let (po, ch) = pipes::stream(); let (po0, ch0) = pipes::stream(); - ch.send(move ch0); + ch.send(ch0); let ch1 = po.recv(); // Does the transmitted channel still work? diff --git a/src/test/run-pass/task-comm-3.rs b/src/test/run-pass/task-comm-3.rs index 97280d37c6384..372a0ea434b58 100644 --- a/src/test/run-pass/task-comm-3.rs +++ b/src/test/run-pass/task-comm-3.rs @@ -44,10 +44,10 @@ fn test00() { while i < number_of_tasks { let ch = po.chan(); task::task().future_result(|+r| { - results.push(move r); + results.push(r); }).spawn({ let i = i; - |move ch| test00_start(ch, i, number_of_messages) + || test00_start(ch, i, number_of_messages) }); i = i + 1; } diff --git a/src/test/run-pass/task-comm-7.rs b/src/test/run-pass/task-comm-7.rs index 5ebd191944b61..481df2d1d529b 100644 --- a/src/test/run-pass/task-comm-7.rs +++ b/src/test/run-pass/task-comm-7.rs @@ -27,19 +27,19 @@ fn test00() { let number_of_messages: int = 10; let c = p.chan(); - do task::spawn |move c| { + do task::spawn || { test00_start(c, number_of_messages * 0, number_of_messages); } let c = p.chan(); - do task::spawn |move c| { + do task::spawn || { test00_start(c, number_of_messages * 1, number_of_messages); } let c = p.chan(); - do task::spawn |move c| { + do task::spawn || { test00_start(c, number_of_messages * 2, number_of_messages); } let c = p.chan(); - do task::spawn |move c| { + do task::spawn || { test00_start(c, number_of_messages * 3, number_of_messages); } diff --git a/src/test/run-pass/task-comm-9.rs b/src/test/run-pass/task-comm-9.rs index ac259e7f7855b..d3ed48f757523 100644 --- a/src/test/run-pass/task-comm-9.rs +++ b/src/test/run-pass/task-comm-9.rs @@ -28,8 +28,8 @@ fn test00() { let ch = p.chan(); let mut result = None; - do task::task().future_result(|+r| { result = Some(move r); }).spawn - |move ch| { + do task::task().future_result(|+r| { result = Some(r); }).spawn + || { test00_start(ch, number_of_messages); } @@ -40,7 +40,7 @@ fn test00() { i += 1; } - option::unwrap(move result).recv(); + option::unwrap(result).recv(); assert (sum == number_of_messages * (number_of_messages - 1) / 2); } diff --git a/src/test/run-pass/trait-default-method-bound-subst.rs b/src/test/run-pass/trait-default-method-bound-subst.rs index 3f69a2e5d909b..5468970ecf555 100644 --- a/src/test/run-pass/trait-default-method-bound-subst.rs +++ b/src/test/run-pass/trait-default-method-bound-subst.rs @@ -11,13 +11,13 @@ // xfail-test trait A { - fn g(x: T, y: U) -> (T, U) { (move x, move y) } + fn g(x: T, y: U) -> (T, U) { (x, y) } } impl A for int { } fn f>(i: V, j: T, k: U) -> (T, U) { - i.g(move j, move k) + i.g(j, k) } fn main () { diff --git a/src/test/run-pass/trait-default-method-bound-subst2.rs b/src/test/run-pass/trait-default-method-bound-subst2.rs index fcb9f60d762c8..71f4165db9d64 100644 --- a/src/test/run-pass/trait-default-method-bound-subst2.rs +++ b/src/test/run-pass/trait-default-method-bound-subst2.rs @@ -11,13 +11,13 @@ // xfail-test trait A { - fn g(x: T) -> T { move x } + fn g(x: T) -> T { x } } impl A for int { } fn f>(i: V, j: T) -> T { - i.g(move j) + i.g(j) } fn main () { diff --git a/src/test/run-pass/trait-default-method-bound-subst3.rs b/src/test/run-pass/trait-default-method-bound-subst3.rs index c89d4abe3dae7..f27bd7c0a7bf9 100644 --- a/src/test/run-pass/trait-default-method-bound-subst3.rs +++ b/src/test/run-pass/trait-default-method-bound-subst3.rs @@ -11,13 +11,13 @@ #[allow(default_methods)]; trait A { - fn g(x: T, y: T) -> (T, T) { (move x, move y) } + fn g(x: T, y: T) -> (T, T) { (x, y) } } impl A for int { } fn f(i: V, j: T, k: T) -> (T, T) { - i.g(move j, move k) + i.g(j, k) } fn main () { diff --git a/src/test/run-pass/trait-default-method-bound-subst4.rs b/src/test/run-pass/trait-default-method-bound-subst4.rs index 7a6dfa33a1ac4..8ea5341795164 100644 --- a/src/test/run-pass/trait-default-method-bound-subst4.rs +++ b/src/test/run-pass/trait-default-method-bound-subst4.rs @@ -11,13 +11,13 @@ #[allow(default_methods)]; trait A { - fn g(x: uint) -> uint { move x } + fn g(x: uint) -> uint { x } } impl A for int { } fn f>(i: V, j: uint) -> uint { - i.g(move j) + i.g(j) } fn main () { diff --git a/src/test/run-pass/trait-inheritance-num2.rs b/src/test/run-pass/trait-inheritance-num2.rs index fb2969a839824..64b30d71e1dff 100644 --- a/src/test/run-pass/trait-inheritance-num2.rs +++ b/src/test/run-pass/trait-inheritance-num2.rs @@ -21,84 +21,84 @@ use std::cmp::FuzzyEq; pub trait TypeExt {} -pub impl u8: TypeExt {} -pub impl u16: TypeExt {} -pub impl u32: TypeExt {} -pub impl u64: TypeExt {} -pub impl uint: TypeExt {} +pub impl TypeExt for u8 {} +pub impl TypeExt for u16 {} +pub impl TypeExt for u32 {} +pub impl TypeExt for u64 {} +pub impl TypeExt for uint {} -pub impl i8: TypeExt {} -pub impl i16: TypeExt {} -pub impl i32: TypeExt {} -pub impl i64: TypeExt {} -pub impl int: TypeExt {} +pub impl TypeExt for i8 {} +pub impl TypeExt for i16 {} +pub impl TypeExt for i32 {} +pub impl TypeExt for i64 {} +pub impl TypeExt for int {} -pub impl f32: TypeExt {} -pub impl f64: TypeExt {} -pub impl float: TypeExt {} +pub impl TypeExt for f32 {} +pub impl TypeExt for f64 {} +pub impl TypeExt for float {} pub trait NumExt: TypeExt Eq Ord NumCast {} -pub impl u8: NumExt {} -pub impl u16: NumExt {} -pub impl u32: NumExt {} -pub impl u64: NumExt {} -pub impl uint: NumExt {} +pub impl NumExt for u8 {} +pub impl NumExt for u16 {} +pub impl NumExt for u32 {} +pub impl NumExt for u64 {} +pub impl NumExt for uint {} -pub impl i8: NumExt {} -pub impl i16: NumExt {} -pub impl i32: NumExt {} -pub impl i64: NumExt {} -pub impl int: NumExt {} +pub impl NumExt for i8 {} +pub impl NumExt for i16 {} +pub impl NumExt for i32 {} +pub impl NumExt for i64 {} +pub impl NumExt for int {} -pub impl f32: NumExt {} -pub impl f64: NumExt {} -pub impl float: NumExt {} +pub impl NumExt for f32 {} +pub impl NumExt for f64 {} +pub impl NumExt for float {} pub trait UnSignedExt: NumExt {} -pub impl u8: UnSignedExt {} -pub impl u16: UnSignedExt {} -pub impl u32: UnSignedExt {} -pub impl u64: UnSignedExt {} -pub impl uint: UnSignedExt {} +pub impl UnSignedExt for u8 {} +pub impl UnSignedExt for u16 {} +pub impl UnSignedExt for u32 {} +pub impl UnSignedExt for u64 {} +pub impl UnSignedExt for uint {} pub trait SignedExt: NumExt {} -pub impl i8: SignedExt {} -pub impl i16: SignedExt {} -pub impl i32: SignedExt {} -pub impl i64: SignedExt {} -pub impl int: SignedExt {} +pub impl SignedExt for i8 {} +pub impl SignedExt for i16 {} +pub impl SignedExt for i32 {} +pub impl SignedExt for i64 {} +pub impl SignedExt for int {} -pub impl f32: SignedExt {} -pub impl f64: SignedExt {} -pub impl float: SignedExt {} +pub impl SignedExt for f32 {} +pub impl SignedExt for f64 {} +pub impl SignedExt for float {} pub trait IntegerExt: NumExt {} -pub impl u8: IntegerExt {} -pub impl u16: IntegerExt {} -pub impl u32: IntegerExt {} -pub impl u64: IntegerExt {} -pub impl uint: IntegerExt {} +pub impl IntegerExt for u8 {} +pub impl IntegerExt for u16 {} +pub impl IntegerExt for u32 {} +pub impl IntegerExt for u64 {} +pub impl IntegerExt for uint {} -pub impl i8: IntegerExt {} -pub impl i16: IntegerExt {} -pub impl i32: IntegerExt {} -pub impl i64: IntegerExt {} -pub impl int: IntegerExt {} +pub impl IntegerExt for i8 {} +pub impl IntegerExt for i16 {} +pub impl IntegerExt for i32 {} +pub impl IntegerExt for i64 {} +pub impl IntegerExt for int {} pub trait FloatExt: NumExt FuzzyEq {} -pub impl f32: FloatExt {} -pub impl f64: FloatExt {} -pub impl float: FloatExt {} +pub impl FloatExt for f32 {} +pub impl FloatExt for f64 {} +pub impl FloatExt for float {} fn test_float_ext(n: T) { io::println(fmt!("%?", n < n)) } diff --git a/src/test/run-pass/trait-inheritance-num3.rs b/src/test/run-pass/trait-inheritance-num3.rs index 30cc54230223f..f184ab2741a1d 100644 --- a/src/test/run-pass/trait-inheritance-num3.rs +++ b/src/test/run-pass/trait-inheritance-num3.rs @@ -13,7 +13,7 @@ use num::NumCast::from; pub trait NumExt: Eq Ord NumCast {} -pub impl f32: NumExt {} +pub impl NumExt for f32 {} fn num_eq_one(n: T) { io::println(fmt!("%?", n == from(1))) } diff --git a/src/test/run-pass/trait-inheritance-num5.rs b/src/test/run-pass/trait-inheritance-num5.rs index c2b88c59f874f..692d50e541a97 100644 --- a/src/test/run-pass/trait-inheritance-num5.rs +++ b/src/test/run-pass/trait-inheritance-num5.rs @@ -13,8 +13,8 @@ use num::NumCast::from; pub trait NumExt: Eq NumCast {} -pub impl f32: NumExt {} -pub impl int: NumExt {} +pub impl NumExt for f32 {} +pub impl NumExt for int {} fn num_eq_one() -> T { from(1) diff --git a/src/test/run-pass/trait-inheritance-overloading-simple.rs b/src/test/run-pass/trait-inheritance-overloading-simple.rs index c41579e360374..b068d109ccfdb 100644 --- a/src/test/run-pass/trait-inheritance-overloading-simple.rs +++ b/src/test/run-pass/trait-inheritance-overloading-simple.rs @@ -19,7 +19,7 @@ impl Eq for MyInt { pure fn ne(&self, other: &MyInt) -> bool { !self.eq(other) } } -impl MyInt : MyNum; +impl MyNum for MyInt; fn f(x: T, y: T) -> bool { return x == y; diff --git a/src/test/run-pass/trait-inheritance-overloading.rs b/src/test/run-pass/trait-inheritance-overloading.rs index 56cdb5d31188d..f56a950f918ce 100644 --- a/src/test/run-pass/trait-inheritance-overloading.rs +++ b/src/test/run-pass/trait-inheritance-overloading.rs @@ -31,7 +31,7 @@ impl Eq for MyInt { pure fn ne(&self, other: &MyInt) -> bool { !self.eq(other) } } -impl MyInt : MyNum; +impl MyNum for MyInt; fn f(x: T, y: T) -> (T, T, T) { return (x + y, x - y, x * y); diff --git a/src/test/run-pass/trait-inheritance-subst.rs b/src/test/run-pass/trait-inheritance-subst.rs index 03b7e37a7ad13..ea3e75f355185 100644 --- a/src/test/run-pass/trait-inheritance-subst.rs +++ b/src/test/run-pass/trait-inheritance-subst.rs @@ -20,7 +20,7 @@ impl Add for MyInt { pure fn add(other: &MyInt) -> MyInt { mi(self.val + other.val) } } -impl MyInt : MyNum; +impl MyNum for MyInt; fn f(x: T, y: T) -> T { return x.add(&y); diff --git a/src/test/run-pass/trait-inheritance-subst2.rs b/src/test/run-pass/trait-inheritance-subst2.rs index 378c78cfd921f..ab755da709969 100644 --- a/src/test/run-pass/trait-inheritance-subst2.rs +++ b/src/test/run-pass/trait-inheritance-subst2.rs @@ -30,7 +30,7 @@ impl Add for MyInt { fn add(other: &MyInt) -> MyInt { self.chomp(other) } } -impl MyInt : MyNum; +impl MyNum for MyInt; fn f(x: T, y: T) -> T { return x.add(&y).chomp(&y); diff --git a/src/test/run-pass/trait-inheritance2.rs b/src/test/run-pass/trait-inheritance2.rs index 3dee07194dd51..08448a65ac805 100644 --- a/src/test/run-pass/trait-inheritance2.rs +++ b/src/test/run-pass/trait-inheritance2.rs @@ -19,7 +19,7 @@ struct A { x: int } impl Foo for A { fn f() -> int { 10 } } impl Bar for A { fn g() -> int { 20 } } impl Baz for A { fn h() -> int { 30 } } -impl A : Quux; +impl Quux for A; fn f(a: &T) { assert a.f() == 10; diff --git a/src/test/run-pass/trait-static-method-overwriting.rs b/src/test/run-pass/trait-static-method-overwriting.rs index 9538ea497ec9f..d416f3f6c910e 100644 --- a/src/test/run-pass/trait-static-method-overwriting.rs +++ b/src/test/run-pass/trait-static-method-overwriting.rs @@ -19,7 +19,7 @@ mod base { dummy: (), } - pub impl Foo : ::base::HasNew { + pub impl ::base::HasNew for Foo { static pure fn new() -> Foo { unsafe { io::println("Foo"); } Foo { dummy: () } @@ -30,7 +30,7 @@ mod base { dummy: (), } - pub impl Bar : ::base::HasNew { + pub impl ::base::HasNew for Bar { static pure fn new() -> Bar { unsafe { io::println("Bar"); } Bar { dummy: () } diff --git a/src/test/run-pass/trait-to-str.rs b/src/test/run-pass/trait-to-str.rs index 62f4ef89d693d..b3ebc2ba820aa 100644 --- a/src/test/run-pass/trait-to-str.rs +++ b/src/test/run-pass/trait-to-str.rs @@ -40,7 +40,7 @@ pub fn main() { assert indirect(~[10, 20]) == ~"[10, 20]!"; fn indirect2(x: T) -> ~str { - indirect(move x) + indirect(x) } assert indirect2(~[1]) == ~"[1]!"; } diff --git a/src/test/run-pass/unique-decl-move-temp.rs b/src/test/run-pass/unique-decl-move-temp.rs index fd4f428bd9d7a..96e91093d37a2 100644 --- a/src/test/run-pass/unique-decl-move-temp.rs +++ b/src/test/run-pass/unique-decl-move-temp.rs @@ -9,6 +9,6 @@ // except according to those terms. pub fn main() { - let i = move ~100; + let i = ~100; assert *i == 100; } diff --git a/src/test/run-pass/unique-decl-move.rs b/src/test/run-pass/unique-decl-move.rs index 27600c04e22f9..7723eafc035ee 100644 --- a/src/test/run-pass/unique-decl-move.rs +++ b/src/test/run-pass/unique-decl-move.rs @@ -10,6 +10,6 @@ pub fn main() { let i = ~100; - let j = move i; + let j = i; assert *j == 100; } diff --git a/src/test/run-pass/unique-fn-arg-move.rs b/src/test/run-pass/unique-fn-arg-move.rs index 61cee457b0cf0..12e9820361d77 100644 --- a/src/test/run-pass/unique-fn-arg-move.rs +++ b/src/test/run-pass/unique-fn-arg-move.rs @@ -14,5 +14,5 @@ fn f(-i: ~int) { pub fn main() { let i = ~100; - f(move i); + f(i); } diff --git a/src/test/run-pass/unique-move-drop.rs b/src/test/run-pass/unique-move-drop.rs index fd86d5aa6fefa..5988a3e8658dc 100644 --- a/src/test/run-pass/unique-move-drop.rs +++ b/src/test/run-pass/unique-move-drop.rs @@ -11,6 +11,6 @@ pub fn main() { let i = ~100; let j = ~200; - let j = move i; + let j = i; assert *j == 100; } diff --git a/src/test/run-pass/unique-move-temp.rs b/src/test/run-pass/unique-move-temp.rs index eaa8a1cf7bd40..08a496987c0a6 100644 --- a/src/test/run-pass/unique-move-temp.rs +++ b/src/test/run-pass/unique-move-temp.rs @@ -10,6 +10,6 @@ pub fn main() { let mut i; - i = move ~100; + i = ~100; assert *i == 100; } diff --git a/src/test/run-pass/unique-move.rs b/src/test/run-pass/unique-move.rs index be0426edbe2e4..5e778d581d340 100644 --- a/src/test/run-pass/unique-move.rs +++ b/src/test/run-pass/unique-move.rs @@ -11,6 +11,6 @@ pub fn main() { let i = ~100; let mut j; - j = move i; + j = i; assert *j == 100; } diff --git a/src/test/run-pass/unreachable-code-1.rs b/src/test/run-pass/unreachable-code-1.rs index 8e900aa7ff3c4..9c658fdc25276 100644 --- a/src/test/run-pass/unreachable-code-1.rs +++ b/src/test/run-pass/unreachable-code-1.rs @@ -12,7 +12,7 @@ fn id(x: bool) -> bool { x } fn call_id() { - let c = move fail!(); + let c = fail!(); id(c); //~ WARNING unreachable statement } diff --git a/src/test/run-pass/unreachable-code.rs b/src/test/run-pass/unreachable-code.rs index 75b2bf090ba65..fa93dfd0fe135 100644 --- a/src/test/run-pass/unreachable-code.rs +++ b/src/test/run-pass/unreachable-code.rs @@ -12,7 +12,7 @@ fn id(x: bool) -> bool { x } fn call_id() { - let c = move fail!(); + let c = fail!(); id(c); } diff --git a/src/test/run-pass/unused-move-capture.rs b/src/test/run-pass/unused-move-capture.rs index 8f3a6f91d173f..665abe23ee893 100644 --- a/src/test/run-pass/unused-move-capture.rs +++ b/src/test/run-pass/unused-move-capture.rs @@ -10,6 +10,6 @@ pub fn main() { let x = ~1; - let lam_move = fn@(move x) { }; + let lam_move = fn@() { }; lam_move(); } diff --git a/src/test/run-pass/unused-move.rs b/src/test/run-pass/unused-move.rs index 785eb691459d6..69ce791c1a35a 100644 --- a/src/test/run-pass/unused-move.rs +++ b/src/test/run-pass/unused-move.rs @@ -15,5 +15,5 @@ pub fn main() { let y = ~1; - move y; + y; } diff --git a/src/test/run-pass/unwind-resource.rs b/src/test/run-pass/unwind-resource.rs index 62673fc134d19..93f1c7b5b4509 100644 --- a/src/test/run-pass/unwind-resource.rs +++ b/src/test/run-pass/unwind-resource.rs @@ -33,7 +33,7 @@ fn complainer(c: SharedChan) -> complainer { } fn f(c: SharedChan) { - let _c = move complainer(c); + let _c = complainer(c); fail!(); } diff --git a/src/test/run-pass/unwind-resource2.rs b/src/test/run-pass/unwind-resource2.rs index 967ed727aa535..75ce797cfc842 100644 --- a/src/test/run-pass/unwind-resource2.rs +++ b/src/test/run-pass/unwind-resource2.rs @@ -26,7 +26,7 @@ fn complainer(c: @int) -> complainer { } fn f() { - let c = move complainer(@0); + let c = complainer(@0); fail!(); } diff --git a/src/test/run-pass/weird-exprs.rs b/src/test/run-pass/weird-exprs.rs index 28a5a5ca47b55..5b515ae543476 100644 --- a/src/test/run-pass/weird-exprs.rs +++ b/src/test/run-pass/weird-exprs.rs @@ -50,7 +50,7 @@ fn zombiejesus() { fn notsure() { let mut _x; let mut _y = (_x = 0) == (_x = 0); - let mut _z = (_x = move 0) < (_x = 0); + let mut _z = (_x = 0) < (_x = 0); let _a = (_x += 0) == (_x = 0); let _b = (_y <-> _z) == (_y <-> _z); } @@ -73,7 +73,7 @@ fn angrydome() { break; } } -fn evil_lincoln() { let evil = move debug!("lincoln"); } +fn evil_lincoln() { let evil = debug!("lincoln"); } pub fn main() { strange(); diff --git a/src/test/run-pass/while-loop-constraints-2.rs b/src/test/run-pass/while-loop-constraints-2.rs index 3d44cf2669b27..df5f5904793da 100644 --- a/src/test/run-pass/while-loop-constraints-2.rs +++ b/src/test/run-pass/while-loop-constraints-2.rs @@ -15,7 +15,7 @@ pub fn main() { let mut x: int; while z < 50 { z += 1; - while false { x = move y; y = z; } + while false { x = y; y = z; } log(debug, y); } assert (y == 42 && z == 50); diff --git a/src/test/run-pass/yield.rs b/src/test/run-pass/yield.rs index d5c58bbd0fabf..16f43016b8e67 100644 --- a/src/test/run-pass/yield.rs +++ b/src/test/run-pass/yield.rs @@ -11,13 +11,13 @@ pub fn main() { let mut result = None; - task::task().future_result(|+r| { result = Some(move r); }).spawn(child); + task::task().future_result(|+r| { result = Some(r); }).spawn(child); error!("1"); task::yield(); error!("2"); task::yield(); error!("3"); - option::unwrap(move result).recv(); + option::unwrap(result).recv(); } fn child() { diff --git a/src/test/run-pass/yield1.rs b/src/test/run-pass/yield1.rs index 1f6170624346b..ae1271f64e4dc 100644 --- a/src/test/run-pass/yield1.rs +++ b/src/test/run-pass/yield1.rs @@ -11,10 +11,10 @@ pub fn main() { let mut result = None; - task::task().future_result(|+r| { result = Some(move r); }).spawn(child); + task::task().future_result(|+r| { result = Some(r); }).spawn(child); error!("1"); task::yield(); - option::unwrap(move result).recv(); + option::unwrap(result).recv(); } fn child() { error!("2"); }