diff options
447 files changed, 5715 insertions, 3161 deletions
diff --git a/COPYRIGHT b/COPYRIGHT index da8ac7b3add..d4ad98e6e87 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -23,12 +23,12 @@ The following third party packages are included, and carry their own copyright notices and license terms: * Two header files that are part of the Valgrind - package. These files are found at src/rt/vg/valgrind.h and - src/rt/vg/memcheck.h, within this distribution. These files + package. These files are found at src/rt/valgrind/valgrind.h and + src/rt/valgrind/memcheck.h, within this distribution. These files are redistributed under the following terms, as noted in them: - for src/rt/vg/valgrind.h: + for src/rt/valgrind/valgrind.h: This file is part of Valgrind, a dynamic binary instrumentation framework. @@ -74,7 +74,7 @@ their own copyright notices and license terms: USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - for src/rt/vg/memcheck.h: + for src/rt/valgrind/memcheck.h: This file is part of MemCheck, a heavyweight Valgrind tool for detecting memory errors. @@ -120,18 +120,6 @@ their own copyright notices and license terms: USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* The auxiliary file src/etc/pkg/modpath.iss contains a - library routine compiled, by Inno Setup, into the Windows - installer binary. This file is licensed under the LGPL, - version 3, but, in our legal interpretation, this does not - affect the aggregate "collected work" license of the Rust - distribution (MIT/ASL2) nor any other components of it. We - believe that the terms governing distribution of the - binary Windows installer built from modpath.iss are - therefore LGPL, but not the terms governing distribution - of any of the files installed by such an installer (such - as the Rust compiler or runtime libraries themselves). - * The src/rt/miniz.c file, carrying an implementation of RFC1950/RFC1951 DEFLATE, by Rich Geldreich <richgel99@gmail.com>. All uses of this file are diff --git a/configure b/configure index 7b7eac8e735..2127f2c656d 100755 --- a/configure +++ b/configure @@ -374,6 +374,10 @@ case $CFG_OSTYPE in CFG_OSTYPE=unknown-dragonfly ;; + OpenBSD) + CFG_OSTYPE=unknown-openbsd + ;; + Darwin) CFG_OSTYPE=apple-darwin ;; diff --git a/mk/cfg/x86_64-unknown-openbsd.mk b/mk/cfg/x86_64-unknown-openbsd.mk new file mode 100644 index 00000000000..582d75c3eaf --- /dev/null +++ b/mk/cfg/x86_64-unknown-openbsd.mk @@ -0,0 +1,26 @@ +# x86_64-pc-openbsd-elf configuration +CC_x86_64-unknown-openbsd=$(CC) +CXX_x86_64-unknown-openbsd=$(CXX) +CPP_x86_64-unknown-openbsd=$(CPP) +AR_x86_64-unknown-openbsd=$(AR) +CFG_LIB_NAME_x86_64-unknown-openbsd=lib$(1).so +CFG_STATIC_LIB_NAME_x86_64-unknown-openbsd=lib$(1).a +CFG_LIB_GLOB_x86_64-unknown-openbsd=lib$(1)-*.so +CFG_LIB_DSYM_GLOB_x86_64-unknown-openbsd=$(1)-*.dylib.dSYM +CFG_JEMALLOC_CFLAGS_x86_64-unknown-openbsd := -m64 -I/usr/include $(CFLAGS) +CFG_GCCISH_CFLAGS_x86_64-unknown-openbsd := -Wall -Werror -g -fPIC -m64 -I/usr/include $(CFLAGS) +CFG_GCCISH_LINK_FLAGS_x86_64-unknown-openbsd := -shared -fPIC -g -pthread -m64 +CFG_GCCISH_DEF_FLAG_x86_64-unknown-openbsd := -Wl,--export-dynamic,--dynamic-list= +CFG_GCCISH_PRE_LIB_FLAGS_x86_64-unknown-openbsd := -Wl,-whole-archive +CFG_GCCISH_POST_LIB_FLAGS_x86_64-unknown-openbsd := -Wl,-no-whole-archive +CFG_DEF_SUFFIX_x86_64-unknown-openbsd := .bsd.def +CFG_LLC_FLAGS_x86_64-unknown-openbsd := +CFG_INSTALL_NAME_x86_64-unknown-openbsd = +CFG_EXE_SUFFIX_x86_64-unknown-openbsd := +CFG_WINDOWSY_x86_64-unknown-openbsd := +CFG_UNIXY_x86_64-unknown-openbsd := 1 +CFG_PATH_MUNGE_x86_64-unknown-openbsd := +CFG_LDPATH_x86_64-unknown-openbsd := +CFG_RUN_x86_64-unknown-openbsd=$(2) +CFG_RUN_TARG_x86_64-unknown-openbsd=$(call CFG_RUN_x86_64-unknown-openbsd,,$(2)) +CFG_GNU_TRIPLE_x86_64-unknown-openbsd := x86_64-unknown-openbsd diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index b73623223fd..07e92c704d8 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -22,6 +22,7 @@ #![feature(std_misc)] #![feature(test)] #![feature(unicode)] +#![feature(env)] #![deny(warnings)] @@ -31,7 +32,7 @@ extern crate getopts; #[macro_use] extern crate log; -use std::os; +use std::env; use std::old_io; use std::old_io::fs; use std::thunk::Thunk; @@ -48,7 +49,7 @@ pub mod common; pub mod errors; pub fn main() { - let args = os::args(); + let args = env::args().map(|s| s.into_string().unwrap()).collect();; let config = parse_config(args); if config.valgrind_path.is_none() && config.force_valgrind { @@ -224,7 +225,7 @@ pub fn run_tests(config: &Config) { //arm-linux-androideabi debug-info test uses remote debugger //so, we test 1 task at once. // also trying to isolate problems with adb_run_wrapper.sh ilooping - os::setenv("RUST_TEST_TASKS","1"); + env::set_var("RUST_TEST_TASKS","1"); } match config.mode { @@ -232,7 +233,7 @@ pub fn run_tests(config: &Config) { // Some older versions of LLDB seem to have problems with multiple // instances running in parallel, so only run one test task at a // time. - os::setenv("RUST_TEST_TASKS", "1"); + env::set_var("RUST_TEST_TASKS", "1"); } _ => { /* proceed */ } } @@ -245,7 +246,7 @@ pub fn run_tests(config: &Config) { old_io::test::raise_fd_limit(); // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary - os::setenv("__COMPAT_LAYER", "RunAsInvoker"); + env::set_var("__COMPAT_LAYER", "RunAsInvoker"); let res = test::run_tests_console(&opts, tests.into_iter().collect()); match res { Ok(true) => {} @@ -276,7 +277,7 @@ pub fn make_tests(config: &Config) -> Vec<test::TestDescAndFn> { config.src_base.display()); let mut tests = Vec::new(); let dirs = fs::readdir(&config.src_base).unwrap(); - for file in dirs.iter() { + for file in &dirs { let file = file.clone(); debug!("inspecting file {:?}", file.display()); if is_test(config, &file) { @@ -304,13 +305,13 @@ pub fn is_test(config: &Config, testfile: &Path) -> bool { let mut valid = false; - for ext in valid_extensions.iter() { + for ext in &valid_extensions { if name.ends_with(ext.as_slice()) { valid = true; } } - for pre in invalid_prefixes.iter() { + for pre in &invalid_prefixes { if name.starts_with(pre.as_slice()) { valid = false; } diff --git a/src/compiletest/procsrv.rs b/src/compiletest/procsrv.rs index 7f3865308da..4b0eea33d69 100644 --- a/src/compiletest/procsrv.rs +++ b/src/compiletest/procsrv.rs @@ -40,13 +40,13 @@ pub fn run(lib_path: &str, let mut cmd = Command::new(prog); cmd.args(args); add_target_env(&mut cmd, lib_path, aux_path); - for (key, val) in env.into_iter() { + for (key, val) in env { cmd.env(key, val); } match cmd.spawn() { Ok(mut process) => { - for input in input.iter() { + if let Some(input) = input { process.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap(); } let ProcessOutput { status, output, error } = @@ -72,13 +72,13 @@ pub fn run_background(lib_path: &str, let mut cmd = Command::new(prog); cmd.args(args); add_target_env(&mut cmd, lib_path, aux_path); - for (key, val) in env.into_iter() { + for (key, val) in env { cmd.env(key, val); } match cmd.spawn() { Ok(mut process) => { - for input in input.iter() { + if let Some(input) = input { process.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap(); } diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 18cb3d1d5b0..5bb0a4031ea 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -31,7 +31,7 @@ use std::old_io::process::ProcessExit; use std::old_io::process; use std::old_io::timer; use std::old_io; -use std::os; +use std::env; use std::iter::repeat; use std::str; use std::string::String; @@ -547,7 +547,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) { exe_file.as_str().unwrap().replace("\\", "\\\\"))[]); // Add line breakpoints - for line in breakpoint_lines.iter() { + for line in &breakpoint_lines { script_str.push_str(&format!("break '{}':{}\n", testfile.filename_display(), *line)[]); @@ -683,13 +683,13 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) script_str.push_str("type category enable Rust\n"); // Set breakpoints on every line that contains the string "#break" - for line in breakpoint_lines.iter() { + for line in &breakpoint_lines { script_str.push_str(format!("breakpoint set --line {}\n", line).as_slice()); } // Append the other commands - for line in commands.iter() { + for line in &commands { script_str.push_str(line.as_slice()); script_str.push_str("\n"); } @@ -847,7 +847,7 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String]) let mut rest = line.trim(); let mut first = true; let mut failed = false; - for frag in check_fragments[i].iter() { + for frag in &check_fragments[i] { let found = if first { if rest.starts_with(frag.as_slice()) { Some(0) @@ -915,7 +915,7 @@ fn check_error_patterns(props: &TestProps, missing_patterns[0]).as_slice(), proc_res); } else { - for pattern in missing_patterns.iter() { + for pattern in missing_patterns { error(format!("error pattern '{}' not found!", *pattern).as_slice()); } @@ -935,7 +935,7 @@ fn check_no_compiler_crash(proc_res: &ProcRes) { fn check_forbid_output(props: &TestProps, output_to_check: &str, proc_res: &ProcRes) { - for pat in props.forbid_output.iter() { + for pat in &props.forbid_output { if output_to_check.contains(pat.as_slice()) { fatal_proc_rec("forbidden pattern found in compiler output", proc_res); } @@ -1173,7 +1173,7 @@ fn compose_and_run_compiler( // FIXME (#9639): This needs to handle non-utf8 paths let extra_link_args = vec!("-L".to_string(), aux_dir.as_str().unwrap().to_string()); - for rel_ab in props.aux_builds.iter() { + for rel_ab in &props.aux_builds { let abs_ab = config.aux_base.join(rel_ab.as_slice()); let aux_props = header::load_props(&abs_ab); let mut crate_type = if aux_props.no_prefer_dynamic { @@ -1298,9 +1298,9 @@ fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> Path { fn make_exe_name(config: &Config, testfile: &Path) -> Path { let mut f = output_base_name(config, testfile); - if !os::consts::EXE_SUFFIX.is_empty() { + if !env::consts::EXE_SUFFIX.is_empty() { let mut fname = f.filename().unwrap().to_vec(); - fname.extend(os::consts::EXE_SUFFIX.bytes()); + fname.extend(env::consts::EXE_SUFFIX.bytes()); f.set_filename(fname); } f @@ -1503,14 +1503,14 @@ fn _arm_exec_compiled_test(config: &Config, // run test via adb_run_wrapper runargs.push("shell".to_string()); - for (key, val) in env.into_iter() { + for (key, val) in env { runargs.push(format!("{}={}", key, val)); } runargs.push(format!("{}/adb_run_wrapper.sh", config.adb_test_dir)); runargs.push(format!("{}", config.adb_test_dir)); runargs.push(format!("{}", prog_short)); - for tv in args.args.iter() { + for tv in &args.args { runargs.push(tv.to_string()); } procsrv::run("", @@ -1591,7 +1591,7 @@ fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) { let tdir = aux_output_dir_name(config, testfile); let dirs = fs::readdir(&tdir).unwrap(); - for file in dirs.iter() { + for file in &dirs { if file.extension_str() == Some("so") { // FIXME (#9639): This needs to handle non-utf8 paths let copy_result = procsrv::run("", diff --git a/src/compiletest/util.rs b/src/compiletest/util.rs index a116cc33690..078eb7bba20 100644 --- a/src/compiletest/util.rs +++ b/src/compiletest/util.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -11,7 +11,7 @@ use common::Config; #[cfg(target_os = "windows")] -use std::os::getenv; +use std::env; /// Conversion table from triple OS name to Rust SYSNAME static OS_TABLE: &'static [(&'static str, &'static str)] = &[ @@ -23,10 +23,11 @@ static OS_TABLE: &'static [(&'static str, &'static str)] = &[ ("linux", "linux"), ("freebsd", "freebsd"), ("dragonfly", "dragonfly"), + ("openbsd", "openbsd"), ]; pub fn get_os(triple: &str) -> &'static str { - for &(triple_os, os) in OS_TABLE.iter() { + for &(triple_os, os) in OS_TABLE { if triple.contains(triple_os) { return os } @@ -39,11 +40,11 @@ pub fn make_new_path(path: &str) -> String { // Windows just uses PATH as the library search path, so we have to // maintain the current value while adding our own - match getenv(lib_path_env_var()) { - Some(curr) => { + match env::var_string(lib_path_env_var()) { + Ok(curr) => { format!("{}{}{}", path, path_div(), curr) } - None => path.to_string() + Err(..) => path.to_string() } } diff --git a/src/doc/grammar.md b/src/doc/grammar.md index c2cbb3ae3fb..59a1c8f828b 100644 --- a/src/doc/grammar.md +++ b/src/doc/grammar.md @@ -196,8 +196,7 @@ raw_string : '"' raw_string_body '"' | '#' raw_string '#' ; common_escape : '\x5c' | 'n' | 'r' | 't' | '0' | 'x' hex_digit 2 -unicode_escape : 'u' hex_digit 4 - | 'U' hex_digit 8 ; +unicode_escape : 'u' '{' hex_digit+ 6 '}'; hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' diff --git a/src/doc/reference.md b/src/doc/reference.md index 778d98a6ae4..64ddb3ffdd3 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -250,8 +250,7 @@ cases mentioned in [Number literals](#number-literals) below. ##### Unicode escapes | | Name | |---|------| -| `\u7FFF` | 16-bit character code (exactly 4 digits) | -| `\U7EEEFFFF` | 32-bit character code (exactly 8 digits) | +| `\u{7FFF}` | 24-bit Unicode character code (up to 6 digits) | ##### Numbers @@ -286,8 +285,8 @@ raw_string : '"' raw_string_body '"' | '#' raw_string '#' ; common_escape : '\x5c' | 'n' | 'r' | 't' | '0' | 'x' hex_digit 2 -unicode_escape : 'u' hex_digit 4 - | 'U' hex_digit 8 ; + +unicode_escape : 'u' '{' hex_digit+ 6 '}'; hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' @@ -320,12 +319,9 @@ following forms: * An _8-bit codepoint escape_ escape starts with `U+0078` (`x`) and is followed by exactly two _hex digits_. It denotes the Unicode codepoint equal to the provided hex value. -* A _16-bit codepoint escape_ starts with `U+0075` (`u`) and is followed - by exactly four _hex digits_. It denotes the Unicode codepoint equal to - the provided hex value. -* A _32-bit codepoint escape_ starts with `U+0055` (`U`) and is followed - by exactly eight _hex digits_. It denotes the Unicode codepoint equal to - the provided hex value. +* A _24-bit codepoint escape_ starts with `U+0075` (`u`) and is followed + by up to six _hex digits_ surrounded by braces `U+007B` (`{`) and `U+007D` + (`}`). It denotes the Unicode codepoint equal to the provided hex value. * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the unicode values `U+000A` (LF), `U+000D` (CR) or `U+0009` (HT) respectively. @@ -1063,7 +1059,7 @@ mod foo { extern crate core; use foo::core::iter; // good: foo is at crate root -// use core::iter; // bad: native is not at the crate root +// use core::iter; // bad: core is not at the crate root use self::baz::foobaz; // good: self refers to module 'foo' use foo::bar::foobar; // good: foo is at crate root @@ -2197,7 +2193,8 @@ The following configurations must be defined by the implementation: `"unix"` or `"windows"`. The value of this configuration option is defined as a configuration itself, like `unix` or `windows`. * `target_os = "..."`. Operating system of the target, examples include - `"win32"`, `"macos"`, `"linux"`, `"android"`, `"freebsd"` or `"dragonfly"`. + `"win32"`, `"macos"`, `"linux"`, `"android"`, `"freebsd"`, `"dragonfly"` or + `"openbsd"`. * `target_word_size = "..."`. Target word size in bits. This is set to `"32"` for targets with 32-bit pointers, and likewise set to `"64"` for 64-bit pointers. diff --git a/src/doc/trpl/comments.md b/src/doc/trpl/comments.md index 3c211b007cf..66670c7c631 100644 --- a/src/doc/trpl/comments.md +++ b/src/doc/trpl/comments.md @@ -43,5 +43,5 @@ When writing doc comments, adding sections for any arguments, return values, and providing some examples of usage is very, very helpful. Don't worry about the `&str`, we'll get to it soon. -You can use the [`rustdoc`](../rustdoc.html) tool to generate HTML documentation +You can use the [`rustdoc`](documentation.html) tool to generate HTML documentation from these doc comments. diff --git a/src/doc/trpl/strings.md b/src/doc/trpl/strings.md index e05c6e172a4..8ebebc98baf 100644 --- a/src/doc/trpl/strings.md +++ b/src/doc/trpl/strings.md @@ -36,7 +36,7 @@ s.push_str(", world."); println!("{}", s); ``` -`String`s will coerece into `&str` with an `&`: +`String`s will coerce into `&str` with an `&`: ``` fn takes_slice(slice: &str) { diff --git a/src/doc/trpl/testing.md b/src/doc/trpl/testing.md index 1c93fd351b6..9c46c8724d4 100644 --- a/src/doc/trpl/testing.md +++ b/src/doc/trpl/testing.md @@ -552,9 +552,7 @@ extern crate test; # struct X; # impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X; b.iter(|| { - let mut n = 1000_u32; - - test::black_box(&mut n); // pretend to modify `n` + let n = test::black_box(1000); range(0, n).fold(0, |a, b| a ^ b) }) @@ -569,7 +567,7 @@ Performing either of the above changes gives the following benchmarking results ```text running 1 test -test bench_xor_1000_ints ... bench: 1 ns/iter (+/- 0) +test bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3) test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured ``` diff --git a/src/etc/local_stage0.sh b/src/etc/local_stage0.sh index 41dea2eeff4..b506aff94e7 100755 --- a/src/etc/local_stage0.sh +++ b/src/etc/local_stage0.sh @@ -1,5 +1,5 @@ #!/bin/sh -# Copyright 2014 The Rust Project Developers. See the COPYRIGHT +# Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution and at # http://rust-lang.org/COPYRIGHT. # @@ -18,7 +18,7 @@ LIB_PREFIX=lib OS=`uname -s` case $OS in - ("Linux"|"FreeBSD"|"DragonFly") + ("Linux"|"FreeBSD"|"DragonFly"|"OpenBSD") BIN_SUF= LIB_SUF=.so ;; diff --git a/src/etc/make-win-dist.py b/src/etc/make-win-dist.py index 13d05135024..defda27acc9 100644 --- a/src/etc/make-win-dist.py +++ b/src/etc/make-win-dist.py @@ -87,6 +87,7 @@ def make_win_dist(rust_root, gcc_root, target_triple): "libsetupapi.a", "libshell32.a", "libuser32.a", + "libuserenv.a", "libuuid.a", "libwinhttp.a", "libwinmm.a", diff --git a/src/etc/snapshot.py b/src/etc/snapshot.py index 698c3a551e2..264af5f9854 100644 --- a/src/etc/snapshot.py +++ b/src/etc/snapshot.py @@ -1,4 +1,4 @@ -# Copyright 2011-2014 The Rust Project Developers. See the COPYRIGHT +# Copyright 2011-2015 The Rust Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution and at # http://rust-lang.org/COPYRIGHT. # @@ -46,6 +46,7 @@ snapshot_files = { "winnt": ["bin/rustc.exe"], "freebsd": ["bin/rustc"], "dragonfly": ["bin/rustc"], + "openbsd": ["bin/rustc"], } winnt_runtime_deps_32 = ["libgcc_s_dw2-1.dll", "libstdc++-6.dll"] @@ -100,6 +101,8 @@ def get_kernel(triple): return "freebsd" if os_name == "dragonfly": return "dragonfly" + if os_name == "openbsd": + return "openbsd" return "linux" diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 5ada51976ac..0ff6cf7b79a 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -127,7 +127,7 @@ impl Drop for Arena { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); - for chunk in self.chunks.borrow().iter() { + for chunk in &*self.chunks.borrow() { if !chunk.is_copy.get() { destroy_chunk(chunk); } diff --git a/src/libbacktrace/configure b/src/libbacktrace/configure index f4f9d058ec8..14a9fd4f452 100755 --- a/src/libbacktrace/configure +++ b/src/libbacktrace/configure @@ -9332,7 +9332,7 @@ if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. - freebsd* | dragonfly*) + freebsd* | dragonfly* | openbsd*) archive_cmds='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes diff --git a/src/libcollections/bench.rs b/src/libcollections/bench.rs index d03fbf00847..9301bf5e4ab 100644 --- a/src/libcollections/bench.rs +++ b/src/libcollections/bench.rs @@ -73,7 +73,7 @@ pub fn find_rand_n<M, T, I, F>(n: uint, let mut keys = (0..n).map(|_| rng.gen::<uint>() % n) .collect::<Vec<_>>(); - for k in keys.iter() { + for k in &keys { insert(map, *k); } diff --git a/src/libcollections/binary_heap.rs b/src/libcollections/binary_heap.rs index 8aa4c77f6f9..b51ec13335e 100644 --- a/src/libcollections/binary_heap.rs +++ b/src/libcollections/binary_heap.rs @@ -673,7 +673,7 @@ impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord { #[stable(feature = "rust1", since = "1.0.0")] impl<T: Ord> Extend<T> for BinaryHeap<T> { - fn extend<Iter: Iterator<Item=T>>(&mut self, mut iter: Iter) { + fn extend<Iter: Iterator<Item=T>>(&mut self, iter: Iter) { let (lower, _) = iter.size_hint(); self.reserve(lower); @@ -696,7 +696,7 @@ mod tests { let iterout = [9, 5, 3]; let heap = BinaryHeap::from_vec(data); let mut i = 0; - for el in heap.iter() { + for el in &heap { assert_eq!(*el, iterout[i]); i += 1; } @@ -884,7 +884,7 @@ mod tests { let mut q: BinaryHeap<uint> = xs.iter().rev().map(|&x| x).collect(); - for &x in xs.iter() { + for &x in &xs { assert_eq!(q.pop().unwrap(), x); } } diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index ec2a274a45d..3e603f6ebaf 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -431,7 +431,7 @@ impl Bitv { /// ``` #[inline] pub fn set_all(&mut self) { - for w in self.storage.iter_mut() { *w = !0u32; } + for w in &mut self.storage { *w = !0u32; } self.fix_last_block(); } @@ -451,7 +451,7 @@ impl Bitv { /// ``` #[inline] pub fn negate(&mut self) { - for w in self.storage.iter_mut() { *w = !*w; } + for w in &mut self.storage { *w = !*w; } self.fix_last_block(); } @@ -912,7 +912,7 @@ impl Bitv { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn clear(&mut self) { - for w in self.storage.iter_mut() { *w = 0u32; } + for w in &mut self.storage { *w = 0u32; } } } @@ -934,7 +934,7 @@ impl FromIterator<bool> for Bitv { #[stable(feature = "rust1", since = "1.0.0")] impl Extend<bool> for Bitv { #[inline] - fn extend<I: Iterator<Item=bool>>(&mut self, mut iterator: I) { + fn extend<I: Iterator<Item=bool>>(&mut self, iterator: I) { let (min, _) = iterator.size_hint(); self.reserve(min); for element in iterator { @@ -976,7 +976,7 @@ impl Ord for Bitv { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for Bitv { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - for bit in self.iter() { + for bit in self { try!(write!(fmt, "{}", if bit { 1u32 } else { 0u32 })); } Ok(()) @@ -1141,7 +1141,7 @@ impl FromIterator<uint> for BitvSet { #[stable(feature = "rust1", since = "1.0.0")] impl Extend<uint> for BitvSet { #[inline] - fn extend<I: Iterator<Item=uint>>(&mut self, mut iterator: I) { + fn extend<I: Iterator<Item=uint>>(&mut self, iterator: I) { for i in iterator { self.insert(i); } @@ -1353,7 +1353,7 @@ impl BitvSet { } // virtually pad other with 0's for equal lengths - let mut other_words = { + let other_words = { let (_, result) = match_words(self_bitv, other_bitv); result }; @@ -1743,7 +1743,7 @@ impl fmt::Debug for BitvSet { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "BitvSet {{")); let mut first = true; - for n in self.iter() { + for n in self { if !first { try!(write!(fmt, ", ")); } @@ -1756,7 +1756,7 @@ impl fmt::Debug for BitvSet { impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for BitvSet { fn hash(&self, state: &mut S) { - for pos in self.iter() { + for pos in self { pos.hash(state); } } @@ -2600,7 +2600,7 @@ mod bitv_bench { b.iter(|| { let mut sum = 0u; for _ in 0u..10 { - for pres in bitv.iter() { + for pres in &bitv { sum += pres as uint; } } @@ -2613,7 +2613,7 @@ mod bitv_bench { let bitv = Bitv::from_elem(BENCH_BITS, false); b.iter(|| { let mut sum = 0u; - for pres in bitv.iter() { + for pres in &bitv { sum += pres as uint; } sum @@ -2674,8 +2674,8 @@ mod bitv_set_test { fn test_bitv_set_frombitv_init() { let bools = [true, false]; let lengths = [10, 64, 100]; - for &b in bools.iter() { - for &l in lengths.iter() { + for &b in &bools { + for &l in &lengths { let bitset = BitvSet::from_bitv(Bitv::from_elem(l, b)); assert_eq!(bitset.contains(&1u), b); assert_eq!(bitset.contains(&(l-1u)), b); @@ -3062,7 +3062,7 @@ mod bitv_set_bench { |idx| {idx % 3 == 0})); b.iter(|| { let mut sum = 0u; - for idx in bitv.iter() { + for idx in &bitv { sum += idx as uint; } sum diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index ce5e8f07be1..99ee5957913 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -116,13 +116,13 @@ pub struct IntoIter<K, V> { /// An iterator over a BTreeMap's keys. #[stable(feature = "rust1", since = "1.0.0")] pub struct Keys<'a, K: 'a, V: 'a> { - inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> + inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> } /// An iterator over a BTreeMap's values. #[stable(feature = "rust1", since = "1.0.0")] pub struct Values<'a, K: 'a, V: 'a> { - inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> + inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> } /// An iterator over a sub-range of BTreeMap's entries. @@ -197,7 +197,7 @@ impl<K: Ord, V> BTreeMap<K, V> { pub fn clear(&mut self) { let b = self.b; // avoid recursive destructors by manually traversing the tree - for _ in mem::replace(self, BTreeMap::with_b(b)).into_iter() {}; + for _ in mem::replace(self, BTreeMap::with_b(b)) {}; } // Searching in a B-Tree is pretty straightforward. @@ -846,7 +846,7 @@ impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> { #[stable(feature = "rust1", since = "1.0.0")] impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> { #[inline] - fn extend<T: Iterator<Item=(K, V)>>(&mut self, mut iter: T) { + fn extend<T: Iterator<Item=(K, V)>>(&mut self, iter: T) { for (k, v) in iter { self.insert(k, v); } @@ -856,7 +856,7 @@ impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> { #[stable(feature = "rust1", since = "1.0.0")] impl<S: Hasher, K: Hash<S>, V: Hash<S>> Hash<S> for BTreeMap<K, V> { fn hash(&self, state: &mut S) { - for elt in self.iter() { + for elt in self { elt.hash(state); } } @@ -1946,7 +1946,7 @@ mod bench { } b.iter(|| { - for entry in map.iter() { + for entry in &map { black_box(entry); } }); diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs index 8d6f06b25c5..8fdfe9ed56a 100644 --- a/src/libcollections/btree/node.rs +++ b/src/libcollections/btree/node.rs @@ -435,13 +435,13 @@ impl<K: Clone, V: Clone> Clone for Node<K, V> { let mut vals = RawItems::from_parts(ret.vals().as_ptr(), 0); let mut edges = RawItems::from_parts(ret.edges().as_ptr(), 0); - for key in self.keys().iter() { + for key in self.keys() { keys.push(key.clone()) } - for val in self.vals().iter() { + for val in self.vals() { vals.push(val.clone()) } - for edge in self.edges().iter() { + for edge in self.edges() { edges.push(edge.clone()) } diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 72d5bf6d799..1997fe189be 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -45,40 +45,40 @@ pub struct Iter<'a, T: 'a> { /// An owning iterator over a BTreeSet's items. #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter<T> { - iter: Map<(T, ()), T, ::btree_map::IntoIter<T, ()>, fn((T, ())) -> T> + iter: Map<::btree_map::IntoIter<T, ()>, fn((T, ())) -> T> } /// An iterator over a sub-range of BTreeSet's items. pub struct Range<'a, T: 'a> { - iter: Map<(&'a T, &'a ()), &'a T, ::btree_map::Range<'a, T, ()>, fn((&'a T, &'a ())) -> &'a T> + iter: Map<::btree_map::Range<'a, T, ()>, fn((&'a T, &'a ())) -> &'a T> } /// A lazy iterator producing elements in the set difference (in-order). #[stable(feature = "rust1", since = "1.0.0")] pub struct Difference<'a, T:'a> { - a: Peekable<&'a T, Iter<'a, T>>, - b: Peekable<&'a T, Iter<'a, T>>, + a: Peekable<Iter<'a, T>>, + b: Peekable<Iter<'a, T>>, } /// A lazy iterator producing elements in the set symmetric difference (in-order). #[stable(feature = "rust1", since = "1.0.0")] pub struct SymmetricDifference<'a, T:'a> { - a: Peekable<&'a T, Iter<'a, T>>, - b: Peekable<&'a T, Iter<'a, T>>, + a: Peekable<Iter<'a, T>>, + b: Peekable<Iter<'a, T>>, } /// A lazy iterator producing elements in the set intersection (in-order). #[stable(feature = "rust1", since = "1.0.0")] pub struct Intersection<'a, T:'a> { - a: Peekable<&'a T, Iter<'a, T>>, - b: Peekable<&'a T, Iter<'a, T>>, + a: Peekable<Iter<'a, T>>, + b: Peekable<Iter<'a, T>>, } /// A lazy iterator producing elements in the set union (in-order). #[stable(feature = "rust1", since = "1.0.0")] pub struct Union<'a, T:'a> { - a: Peekable<&'a T, Iter<'a, T>>, - b: Peekable<&'a T, Iter<'a, T>>, + a: Peekable<Iter<'a, T>>, + b: Peekable<Iter<'a, T>>, } impl<T: Ord> BTreeSet<T> { @@ -499,7 +499,7 @@ impl<'a, T> IntoIterator for &'a BTreeSet<T> { #[stable(feature = "rust1", since = "1.0.0")] impl<T: Ord> Extend<T> for BTreeSet<T> { #[inline] - fn extend<Iter: Iterator<Item=T>>(&mut self, mut iter: Iter) { + fn extend<Iter: Iterator<Item=T>>(&mut self, iter: Iter) { for elem in iter { self.insert(elem); } @@ -791,8 +791,8 @@ mod test { let mut set_a = BTreeSet::new(); let mut set_b = BTreeSet::new(); - for x in a.iter() { assert!(set_a.insert(*x)) } - for y in b.iter() { assert!(set_b.insert(*y)) } + for x in a { assert!(set_a.insert(*x)) } + for y in b { assert!(set_b.insert(*y)) } let mut i = 0; f(&set_a, &set_b, Counter { i: &mut i, expected: expected }); @@ -894,7 +894,7 @@ mod test { let set: BTreeSet<int> = xs.iter().map(|&x| x).collect(); - for x in xs.iter() { + for x in &xs { assert!(set.contains(x)); } } diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index beb2973febc..d85e9ee3226 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -856,7 +856,7 @@ impl<'a, T> IntoIterator for &'a mut DList<T> { #[stable(feature = "rust1", since = "1.0.0")] impl<A> Extend<A> for DList<A> { - fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) { + fn extend<T: Iterator<Item=A>>(&mut self, iterator: T) { for elt in iterator { self.push_back(elt); } } } @@ -917,7 +917,7 @@ impl<A: fmt::Debug> fmt::Debug for DList<A> { impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for DList<A> { fn hash(&self, state: &mut S) { self.len().hash(state); - for elt in self.iter() { + for elt in self { elt.hash(state); } } @@ -1061,7 +1061,7 @@ mod tests { let mut sum = v; sum.push_all(u.as_slice()); assert_eq!(sum.len(), m.len()); - for elt in sum.into_iter() { + for elt in sum { assert_eq!(m.pop_front(), Some(elt)) } assert_eq!(n.len(), 0); diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 9765bb5875e..8cbf50d29f2 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -36,7 +36,7 @@ impl<E:CLike + fmt::Debug> fmt::Debug for EnumSet<E> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "EnumSet {{")); let mut first = true; - for e in self.iter() { + for e in self { if !first { try!(write!(fmt, ", ")); } @@ -266,7 +266,7 @@ impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike { } impl<E:CLike> Extend<E> for EnumSet<E> { - fn extend<I: Iterator<Item=E>>(&mut self, mut iterator: I) { + fn extend<I: Iterator<Item=E>>(&mut self, iterator: I) { for element in iterator { self.insert(element); } diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index ce00bd48bb8..102dfb3df9d 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -22,8 +22,6 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] -#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap - #![feature(alloc)] #![feature(box_syntax)] #![feature(core)] diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index 7032a3d9137..18021dea9f2 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -1573,7 +1573,7 @@ impl<A: Ord> Ord for RingBuf<A> { impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for RingBuf<A> { fn hash(&self, state: &mut S) { self.len().hash(state); - for elt in self.iter() { + for elt in self { elt.hash(state); } } @@ -1635,7 +1635,7 @@ impl<'a, T> IntoIterator for &'a mut RingBuf<T> { #[stable(feature = "rust1", since = "1.0.0")] impl<A> Extend<A> for RingBuf<A> { - fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) { + fn extend<T: Iterator<Item=A>>(&mut self, iterator: T) { for elt in iterator { self.push_back(elt); } @@ -1856,7 +1856,7 @@ mod tests { b.iter(|| { let mut sum = 0; - for &i in ring.iter() { + for &i in &ring { sum += i; } test::black_box(sum); @@ -1869,7 +1869,7 @@ mod tests { b.iter(|| { let mut sum = 0; - for i in ring.iter_mut() { + for i in &mut ring { sum += *i; } test::black_box(sum); diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index d2f92d1c8db..4b4ea3e4c3c 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -98,9 +98,6 @@ use core::iter::{range_step, MultiplicativeIterator}; use core::marker::Sized; use core::mem::size_of; use core::mem; -#[cfg(stage0)] -use core::ops::{FnMut, FullRange}; -#[cfg(not(stage0))] use core::ops::FnMut; use core::option::Option::{self, Some, None}; use core::ptr::PtrExt; @@ -1121,7 +1118,7 @@ impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] { fn concat(&self) -> Vec<T> { let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len()); let mut result = Vec::with_capacity(size); - for v in self.iter() { + for v in self { result.push_all(v.as_slice()) } result @@ -1131,7 +1128,7 @@ impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] { let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len()); let mut result = Vec::with_capacity(size + self.len()); let mut first = true; - for v in self.iter() { + for v in self { if first { first = false } else { result.push(sep.clone()) } result.push_all(v.as_slice()) } @@ -1231,7 +1228,7 @@ impl Iterator for ElementSwaps { self.sdir.swap(i, j); // Swap the direction of each larger SizeDirection - for x in self.sdir.iter_mut() { + for x in &mut self.sdir { if x.size > sd.size { x.dir = match x.dir { Pos => Neg, Neg => Pos }; } @@ -1512,9 +1509,6 @@ mod tests { use core::prelude::{Some, None, range, Clone}; use core::prelude::{Iterator, IteratorExt}; use core::prelude::{AsSlice}; - #[cfg(stage0)] - use core::prelude::{Ord, FullRange}; - #[cfg(not(stage0))] use core::prelude::Ord; use core::default::Default; use core::mem; @@ -2362,7 +2356,7 @@ mod tests { #[test] fn test_mut_iterator() { let mut xs = [1, 2, 3, 4, 5]; - for x in xs.iter_mut() { + for x in &mut xs { *x += 1; } assert!(xs == [2, 3, 4, 5, 6]) @@ -2662,7 +2656,7 @@ mod tests { let left: &[_] = left; assert!(left[..left.len()] == [1, 2][]); } - for p in left.iter_mut() { + for p in left { *p += 1; } @@ -2670,7 +2664,7 @@ mod tests { let right: &[_] = right; assert!(right[..right.len()] == [3, 4, 5][]); } - for p in right.iter_mut() { + for p in right { *p += 2; } } @@ -2687,25 +2681,25 @@ mod tests { assert_eq!(v.len(), 3); let mut cnt = 0u; - for f in v.iter() { + for f in &v { assert!(*f == Foo); cnt += 1; } assert_eq!(cnt, 3); - for f in v[1..3].iter() { + for f in &v[1..3] { assert!(*f == Foo); cnt += 1; } assert_eq!(cnt, 5); - for f in v.iter_mut() { + for f in &mut v { assert!(*f == Foo); cnt += 1; } assert_eq!(cnt, 8); - for f in v.into_iter() { + for f in v { assert!(f == Foo); cnt += 1; } @@ -2713,7 +2707,7 @@ mod tests { let xs: [Foo; 3] = [Foo, Foo, Foo]; cnt = 0; - for f in xs.iter() { + for f in &xs { assert!(*f == Foo); cnt += 1; } @@ -2802,7 +2796,7 @@ mod tests { let mut v = [0u8, 1, 2, 3, 4, 5, 6]; assert_eq!(v.chunks_mut(2).len(), 4); for (i, chunk) in v.chunks_mut(3).enumerate() { - for x in chunk.iter_mut() { + for x in chunk { *x = i as u8; } } @@ -2814,7 +2808,7 @@ mod tests { fn test_mut_chunks_rev() { let mut v = [0u8, 1, 2, 3, 4, 5, 6]; for (i, chunk) in v.chunks_mut(3).rev().enumerate() { - for x in chunk.iter_mut() { + for x in chunk { *x = i as u8; } } @@ -2864,7 +2858,7 @@ mod bench { b.iter(|| { let mut sum = 0; - for x in v.iter() { + for x in &v { sum += *x; } // sum == 11806, to stop dead code elimination. @@ -2878,7 +2872,7 @@ mod bench { b.iter(|| { let mut i = 0; - for x in v.iter_mut() { + for x in &mut v { *x = i; i += 1; } @@ -3012,7 +3006,7 @@ mod bench { unsafe { v.set_len(1024); } - for x in v.iter_mut() { + for x in &mut v { *x = 0; } v diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index ded6385d293..75f7b812974 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -61,11 +61,6 @@ use core::clone::Clone; use core::iter::AdditiveIterator; use core::iter::{Iterator, IteratorExt}; use core::ops::Index; -#[cfg(stage0)] -use core::ops::FullRange as RangeFull; -#[cfg(stage0)] -use core::ops::FullRange; -#[cfg(not(stage0))] use core::ops::RangeFull; use core::option::Option::{self, Some, None}; use core::result::Result; @@ -104,7 +99,7 @@ impl<S: Str> SliceConcatExt<str, String> for [S] { let len = s.iter().map(|s| s.as_slice().len()).sum(); let mut result = String::with_capacity(len); - for s in s.iter() { + for s in s { result.push_str(s.as_slice()) } @@ -130,7 +125,7 @@ impl<S: Str> SliceConcatExt<str, String> for [S] { let mut result = String::with_capacity(len); let mut first = true; - for s in s.iter() { + for s in s { if first { first = false; } else { @@ -2010,7 +2005,7 @@ mod tests { let s = "ศไทย中华Việt Nam"; let v = vec!['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = 0; - for ch in v.iter() { + for ch in &v { assert!(s.char_at(pos) == *ch); pos += ch.to_string().len(); } @@ -2708,7 +2703,7 @@ mod tests { &["\u{378}\u{308}\u{903}"], &["\u{378}\u{308}", "\u{903}"]), ]; - for &(s, g) in test_same.iter() { + for &(s, g) in &test_same[] { // test forward iterator assert!(order::equals(s.graphemes(true), g.iter().map(|&x| x))); assert!(order::equals(s.graphemes(false), g.iter().map(|&x| x))); @@ -2718,7 +2713,7 @@ mod tests { assert!(order::equals(s.graphemes(false).rev(), g.iter().rev().map(|&x| x))); } - for &(s, gt, gf) in test_diff.iter() { + for &(s, gt, gf) in &test_diff { // test forward iterator assert!(order::equals(s.graphemes(true), gt.iter().map(|&x| x))); assert!(order::equals(s.graphemes(false), gf.iter().map(|&x| x))); diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 4cb7b05f967..554eee765f3 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -729,7 +729,7 @@ impl<'a> FromIterator<&'a str> for String { #[unstable(feature = "collections", reason = "waiting on Extend stabilization")] impl Extend<char> for String { - fn extend<I:Iterator<Item=char>>(&mut self, mut iterator: I) { + fn extend<I:Iterator<Item=char>>(&mut self, iterator: I) { let (lower_bound, _) = iterator.size_hint(); self.reserve(lower_bound); for ch in iterator { @@ -741,7 +741,7 @@ impl Extend<char> for String { #[unstable(feature = "collections", reason = "waiting on Extend stabilization")] impl<'a> Extend<&'a str> for String { - fn extend<I: Iterator<Item=&'a str>>(&mut self, mut iterator: I) { + fn extend<I: Iterator<Item=&'a str>>(&mut self, iterator: I) { // A guess that at least one byte per iterator element will be needed. let (lower_bound, _) = iterator.size_hint(); self.reserve(lower_bound); @@ -877,16 +877,6 @@ impl ops::Index<ops::RangeFrom<uint>> for String { &self[][*index] } } -#[cfg(stage0)] -#[stable(feature = "rust1", since = "1.0.0")] -impl ops::Index<ops::FullRange> for String { - type Output = str; - #[inline] - fn index(&self, _index: &ops::FullRange) -> &str { - unsafe { mem::transmute(self.vec.as_slice()) } - } -} -#[cfg(not(stage0))] #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeFull> for String { type Output = str; @@ -1011,8 +1001,6 @@ mod tests { use str::Utf8Error; use core::iter::repeat; use super::{as_string, CowString}; - #[cfg(stage0)] - use core::ops::FullRange; #[test] fn test_as_string() { @@ -1130,7 +1118,7 @@ mod tests { (String::from_str("\u{20000}"), vec![0xD840, 0xDC00])]; - for p in pairs.iter() { + for p in &pairs { let (s, u) = (*p).clone(); let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>(); let u_as_string = String::from_utf16(u.as_slice()).unwrap(); diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index c45879ae251..e9ddfd4872f 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1318,16 +1318,6 @@ impl<T> ops::Index<ops::RangeFrom<uint>> for Vec<T> { self.as_slice().index(index) } } -#[cfg(stage0)] -#[stable(feature = "rust1", since = "1.0.0")] -impl<T> ops::Index<ops::FullRange> for Vec<T> { - type Output = [T]; - #[inline] - fn index(&self, _index: &ops::FullRange) -> &[T] { - self.as_slice() - } -} -#[cfg(not(stage0))] #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::RangeFull> for Vec<T> { type Output = [T]; @@ -1361,16 +1351,6 @@ impl<T> ops::IndexMut<ops::RangeFrom<uint>> for Vec<T> { self.as_mut_slice().index_mut(index) } } -#[cfg(stage0)] -#[stable(feature = "rust1", since = "1.0.0")] -impl<T> ops::IndexMut<ops::FullRange> for Vec<T> { - type Output = [T]; - #[inline] - fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { - self.as_mut_slice() - } -} -#[cfg(not(stage0))] #[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> { type Output = [T]; @@ -1395,7 +1375,7 @@ impl<T> ops::DerefMut for Vec<T> { #[stable(feature = "rust1", since = "1.0.0")] impl<T> FromIterator<T> for Vec<T> { #[inline] - fn from_iter<I:Iterator<Item=T>>(mut iterator: I) -> Vec<T> { + fn from_iter<I:Iterator<Item=T>>(iterator: I) -> Vec<T> { let (lower, _) = iterator.size_hint(); let mut vector = Vec::with_capacity(lower); for element in iterator { @@ -1432,7 +1412,7 @@ impl<'a, T> IntoIterator for &'a mut Vec<T> { #[unstable(feature = "collections", reason = "waiting on Extend stability")] impl<T> Extend<T> for Vec<T> { #[inline] - fn extend<I: Iterator<Item=T>>(&mut self, mut iterator: I) { + fn extend<I: Iterator<Item=T>>(&mut self, iterator: I) { let (lower, _) = iterator.size_hint(); self.reserve(lower); for element in iterator { @@ -1567,7 +1547,7 @@ impl<T> Drop for Vec<T> { // zeroed (when moving out, because of #[unsafe_no_drop_flag]). if self.cap != 0 { unsafe { - for x in self.iter() { + for x in &*self { ptr::read(x); } dealloc(*self.ptr, self.cap) @@ -1934,8 +1914,6 @@ mod tests { use prelude::*; use core::mem::size_of; use core::iter::repeat; - #[cfg(stage0)] - use core::ops::FullRange; use test::Bencher; use super::as_vec; @@ -2044,7 +2022,7 @@ mod tests { { let slice = &mut values[2 ..]; assert!(slice == [3, 4, 5]); - for p in slice.iter_mut() { + for p in slice { *p += 2; } } @@ -2058,7 +2036,7 @@ mod tests { { let slice = &mut values[.. 2]; assert!(slice == [1, 2]); - for p in slice.iter_mut() { + for p in slice { *p += 1; } } @@ -2075,7 +2053,7 @@ mod tests { let left: &[_] = left; assert!(&left[..left.len()] == &[1, 2][]); } - for p in left.iter_mut() { + for p in left { *p += 1; } @@ -2083,7 +2061,7 @@ mod tests { let right: &[_] = right; assert!(&right[..right.len()] == &[3, 4, 5][]); } - for p in right.iter_mut() { + for p in right { *p += 2; } } @@ -2151,7 +2129,7 @@ mod tests { v.push(()); assert_eq!(v.iter().count(), 2); - for &() in v.iter() {} + for &() in &v {} assert_eq!(v.iter_mut().count(), 2); v.push(()); @@ -2159,7 +2137,7 @@ mod tests { v.push(()); assert_eq!(v.iter_mut().count(), 4); - for &mut () in v.iter_mut() {} + for &mut () in &mut v {} unsafe { v.set_len(0); } assert_eq!(v.iter_mut().count(), 0); } @@ -2355,7 +2333,7 @@ mod tests { fn test_move_items() { let vec = vec![1, 2, 3]; let mut vec2 : Vec<i32> = vec![]; - for i in vec.into_iter() { + for i in vec { vec2.push(i); } assert!(vec2 == vec![1, 2, 3]); @@ -2375,7 +2353,7 @@ mod tests { fn test_move_items_zero_sized() { let vec = vec![(), (), ()]; let mut vec2 : Vec<()> = vec![]; - for i in vec.into_iter() { + for i in vec { vec2.push(i); } assert!(vec2 == vec![(), (), ()]); diff --git a/src/libcollections/vec_map.rs b/src/libcollections/vec_map.rs index f2a9bb4392c..c74c870eef5 100644 --- a/src/libcollections/vec_map.rs +++ b/src/libcollections/vec_map.rs @@ -90,7 +90,7 @@ impl<S: Writer + Hasher, V: Hash<S>> Hash<S> for VecMap<V> { // In order to not traverse the `VecMap` twice, count the elements // during iteration. let mut count: uint = 0; - for elt in self.iter() { + for elt in self { elt.hash(state); count += 1; } @@ -562,7 +562,7 @@ impl<'a, T> IntoIterator for &'a mut VecMap<T> { #[stable(feature = "rust1", since = "1.0.0")] impl<V> Extend<(uint, V)> for VecMap<V> { - fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, mut iter: Iter) { + fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, iter: Iter) { for (k, v) in iter { self.insert(k, v); } @@ -687,7 +687,7 @@ double_ended_iterator! { impl IterMut -> (uint, &'a mut V), as_mut } /// An iterator over the keys of a map. #[stable(feature = "rust1", since = "1.0.0")] pub struct Keys<'a, V: 'a> { - iter: Map<(uint, &'a V), uint, Iter<'a, V>, fn((uint, &'a V)) -> uint> + iter: Map<Iter<'a, V>, fn((uint, &'a V)) -> uint> } // FIXME(#19839) Remove in favor of `#[derive(Clone)]` @@ -702,7 +702,7 @@ impl<'a, V> Clone for Keys<'a, V> { /// An iterator over the values of a map. #[stable(feature = "rust1", since = "1.0.0")] pub struct Values<'a, V: 'a> { - iter: Map<(uint, &'a V), &'a V, Iter<'a, V>, fn((uint, &'a V)) -> &'a V> + iter: Map<Iter<'a, V>, fn((uint, &'a V)) -> &'a V> } // FIXME(#19839) Remove in favor of `#[derive(Clone)]` @@ -718,8 +718,6 @@ impl<'a, V> Clone for Values<'a, V> { #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter<V> { iter: FilterMap< - (uint, Option<V>), - (uint, V), Enumerate<vec::IntoIter<Option<V>>>, fn((uint, Option<V>)) -> Option<(uint, V)>> } @@ -727,8 +725,6 @@ pub struct IntoIter<V> { #[unstable(feature = "collections")] pub struct Drain<'a, V> { iter: FilterMap< - (uint, Option<V>), - (uint, V), Enumerate<vec::Drain<'a, Option<V>>>, fn((uint, Option<V>)) -> Option<(uint, V)>> } @@ -924,7 +920,7 @@ mod test_map { assert!(m.insert(6, 10).is_none()); assert!(m.insert(10, 11).is_none()); - for (k, v) in m.iter_mut() { + for (k, v) in &mut m { *v += k as int; } @@ -984,7 +980,7 @@ mod test_map { let mut m = VecMap::new(); m.insert(1, box 2); let mut called = false; - for (k, v) in m.into_iter() { + for (k, v) in m { assert!(!called); called = true; assert_eq!(k, 1); @@ -1112,7 +1108,7 @@ mod test_map { let map: VecMap<char> = xs.iter().map(|&x| x).collect(); - for &(k, v) in xs.iter() { + for &(k, v) in &xs { assert_eq!(map.get(&k), Some(&v)); } } diff --git a/src/libcore/array.rs b/src/libcore/array.rs index ec3d9783255..5c4567e567b 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -20,9 +20,6 @@ use fmt; use hash::{Hash, Hasher, self}; use iter::IntoIterator; use marker::Copy; -#[cfg(stage0)] -use ops::{Deref, FullRange}; -#[cfg(not(stage0))] use ops::Deref; use option::Option; use slice::{Iter, IterMut, SliceExt}; diff --git a/src/libcore/atomic.rs b/src/libcore/atomic.rs index cf2854be016..0f3823eb7a5 100644 --- a/src/libcore/atomic.rs +++ b/src/libcore/atomic.rs @@ -415,6 +415,7 @@ impl AtomicIsize { /// let atomic_forty_two = AtomicIsize::new(42); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn new(v: isize) -> AtomicIsize { AtomicIsize {v: UnsafeCell::new(v)} } @@ -437,6 +438,7 @@ impl AtomicIsize { /// let value = some_isize.load(Ordering::Relaxed); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn load(&self, order: Ordering) -> isize { unsafe { atomic_load(self.v.get(), order) } } @@ -459,6 +461,7 @@ impl AtomicIsize { /// /// Panics if `order` is `Acquire` or `AcqRel`. #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn store(&self, val: isize, order: Ordering) { unsafe { atomic_store(self.v.get(), val, order); } } @@ -477,6 +480,7 @@ impl AtomicIsize { /// let value = some_isize.swap(10, Ordering::Relaxed); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn swap(&self, val: isize, order: Ordering) -> isize { unsafe { atomic_swap(self.v.get(), val, order) } } @@ -498,6 +502,7 @@ impl AtomicIsize { /// let value = some_isize.compare_and_swap(5, 10, Ordering::Relaxed); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn compare_and_swap(&self, old: isize, new: isize, order: Ordering) -> isize { unsafe { atomic_compare_and_swap(self.v.get(), old, new, order) } } @@ -514,6 +519,7 @@ impl AtomicIsize { /// assert_eq!(10, foo.load(Ordering::SeqCst)); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_add(&self, val: isize, order: Ordering) -> isize { unsafe { atomic_add(self.v.get(), val, order) } } @@ -530,6 +536,7 @@ impl AtomicIsize { /// assert_eq!(-10, foo.load(Ordering::SeqCst)); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_sub(&self, val: isize, order: Ordering) -> isize { unsafe { atomic_sub(self.v.get(), val, order) } } @@ -545,6 +552,7 @@ impl AtomicIsize { /// assert_eq!(0b101101, foo.fetch_and(0b110011, Ordering::SeqCst)); /// assert_eq!(0b100001, foo.load(Ordering::SeqCst)); #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_and(&self, val: isize, order: Ordering) -> isize { unsafe { atomic_and(self.v.get(), val, order) } } @@ -560,6 +568,7 @@ impl AtomicIsize { /// assert_eq!(0b101101, foo.fetch_or(0b110011, Ordering::SeqCst)); /// assert_eq!(0b111111, foo.load(Ordering::SeqCst)); #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_or(&self, val: isize, order: Ordering) -> isize { unsafe { atomic_or(self.v.get(), val, order) } } @@ -575,6 +584,7 @@ impl AtomicIsize { /// assert_eq!(0b101101, foo.fetch_xor(0b110011, Ordering::SeqCst)); /// assert_eq!(0b011110, foo.load(Ordering::SeqCst)); #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_xor(&self, val: isize, order: Ordering) -> isize { unsafe { atomic_xor(self.v.get(), val, order) } } @@ -592,6 +602,7 @@ impl AtomicUsize { /// let atomic_forty_two = AtomicUsize::new(42); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn new(v: usize) -> AtomicUsize { AtomicUsize { v: UnsafeCell::new(v) } } @@ -614,6 +625,7 @@ impl AtomicUsize { /// let value = some_usize.load(Ordering::Relaxed); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn load(&self, order: Ordering) -> usize { unsafe { atomic_load(self.v.get(), order) } } @@ -636,6 +648,7 @@ impl AtomicUsize { /// /// Panics if `order` is `Acquire` or `AcqRel`. #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn store(&self, val: usize, order: Ordering) { unsafe { atomic_store(self.v.get(), val, order); } } @@ -654,6 +667,7 @@ impl AtomicUsize { /// let value = some_usize.swap(10, Ordering::Relaxed); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn swap(&self, val: usize, order: Ordering) -> usize { unsafe { atomic_swap(self.v.get(), val, order) } } @@ -675,6 +689,7 @@ impl AtomicUsize { /// let value = some_usize.compare_and_swap(5, 10, Ordering::Relaxed); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn compare_and_swap(&self, old: usize, new: usize, order: Ordering) -> usize { unsafe { atomic_compare_and_swap(self.v.get(), old, new, order) } } @@ -691,6 +706,7 @@ impl AtomicUsize { /// assert_eq!(10, foo.load(Ordering::SeqCst)); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_add(&self, val: usize, order: Ordering) -> usize { unsafe { atomic_add(self.v.get(), val, order) } } @@ -707,6 +723,7 @@ impl AtomicUsize { /// assert_eq!(0, foo.load(Ordering::SeqCst)); /// ``` #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_sub(&self, val: usize, order: Ordering) -> usize { unsafe { atomic_sub(self.v.get(), val, order) } } @@ -722,6 +739,7 @@ impl AtomicUsize { /// assert_eq!(0b101101, foo.fetch_and(0b110011, Ordering::SeqCst)); /// assert_eq!(0b100001, foo.load(Ordering::SeqCst)); #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_and(&self, val: usize, order: Ordering) -> usize { unsafe { atomic_and(self.v.get(), val, order) } } @@ -737,6 +755,7 @@ impl AtomicUsize { /// assert_eq!(0b101101, foo.fetch_or(0b110011, Ordering::SeqCst)); /// assert_eq!(0b111111, foo.load(Ordering::SeqCst)); #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_or(&self, val: usize, order: Ordering) -> usize { unsafe { atomic_or(self.v.get(), val, order) } } @@ -752,6 +771,7 @@ impl AtomicUsize { /// assert_eq!(0b101101, foo.fetch_xor(0b110011, Ordering::SeqCst)); /// assert_eq!(0b011110, foo.load(Ordering::SeqCst)); #[inline] + #[stable(feature = "rust1", since = "1.0.0")] pub fn fetch_xor(&self, val: usize, order: Ordering) -> usize { unsafe { atomic_xor(self.v.get(), val, order) } } diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 65dccc8c244..c82d8c531d2 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -266,6 +266,18 @@ pub struct RefCell<T> { borrow: Cell<BorrowFlag>, } +/// An enumeration of values returned from the `state` method on a `RefCell<T>`. +#[derive(Copy, Clone, PartialEq, Debug)] +#[unstable(feature = "std_misc")] +pub enum BorrowState { + /// The cell is currently being read, there is at least one active `borrow`. + Reading, + /// The cell is currently being written to, there is an active `borrow_mut`. + Writing, + /// There are no outstanding borrows on this cell. + Unused, +} + // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; @@ -310,6 +322,19 @@ impl<T> RefCell<T> { unsafe { self.value.into_inner() } } + /// Query the current state of this `RefCell` + /// + /// The returned value can be dispatched on to determine if a call to + /// `borrow` or `borrow_mut` would succeed. + #[unstable(feature = "std_misc")] + pub fn borrow_state(&self) -> BorrowState { + match self.borrow.get() { + WRITING => BorrowState::Writing, + UNUSED => BorrowState::Unused, + _ => BorrowState::Reading, + } + } + /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple @@ -317,6 +342,8 @@ impl<T> RefCell<T> { /// /// Returns `None` if the value is currently mutably borrowed. #[unstable(feature = "core", reason = "may be renamed or removed")] + #[deprecated(since = "1.0.0", + reason = "dispatch on `cell.borrow_state()` instead")] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match BorrowRef::new(&self.borrow) { Some(b) => Some(Ref { _value: unsafe { &*self.value.get() }, _borrow: b }), @@ -326,8 +353,8 @@ impl<T> RefCell<T> { /// Immutably borrows the wrapped value. /// - /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be - /// taken out at the same time. + /// The borrow lasts until the returned `Ref` exits scope. Multiple + /// immutable borrows can be taken out at the same time. /// /// # Panics /// @@ -361,9 +388,12 @@ impl<T> RefCell<T> { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { - match self.try_borrow() { - Some(ptr) => ptr, - None => panic!("RefCell<T> already mutably borrowed") + match BorrowRef::new(&self.borrow) { + Some(b) => Ref { + _value: unsafe { &*self.value.get() }, + _borrow: b, + }, + None => panic!("RefCell<T> already mutably borrowed"), } } @@ -374,6 +404,8 @@ impl<T> RefCell<T> { /// /// Returns `None` if the value is currently borrowed. #[unstable(feature = "core", reason = "may be renamed or removed")] + #[deprecated(since = "1.0.0", + reason = "dispatch on `cell.borrow_state()` instead")] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match BorrowRefMut::new(&self.borrow) { Some(b) => Some(RefMut { _value: unsafe { &mut *self.value.get() }, _borrow: b }), @@ -383,8 +415,8 @@ impl<T> RefCell<T> { /// Mutably borrows the wrapped value. /// - /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed - /// while this borrow is active. + /// The borrow lasts until the returned `RefMut` exits scope. The value + /// cannot be borrowed while this borrow is active. /// /// # Panics /// @@ -417,9 +449,12 @@ impl<T> RefCell<T> { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { - match self.try_borrow_mut() { - Some(ptr) => ptr, - None => panic!("RefCell<T> already borrowed") + match BorrowRefMut::new(&self.borrow) { + Some(b) => RefMut { + _value: unsafe { &mut *self.value.get() }, + _borrow: b, + }, + None => panic!("RefCell<T> already borrowed"), } } diff --git a/src/libcore/char.rs b/src/libcore/char.rs index 22bfd47893c..28e0247f00a 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -67,7 +67,25 @@ static MAX_THREE_B: u32 = 0x10000u32; #[stable(feature = "rust1", since = "1.0.0")] pub const MAX: char = '\u{10ffff}'; -/// Converts from `u32` to a `char` +/// Converts a `u32` to an `Option<char>`. +/// +/// # Examples +/// +/// ``` +/// use std::char; +/// +/// let c = char::from_u32(10084); // produces `Some(❤)` +/// assert_eq!(c, Some('❤')); +/// ``` +/// +/// An invalid character: +/// +/// ``` +/// use std::char; +/// +/// let none = char::from_u32(1114112); +/// assert_eq!(none, None); +/// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_u32(i: u32) -> Option<char> { @@ -79,8 +97,7 @@ pub fn from_u32(i: u32) -> Option<char> { } } -/// -/// Converts a number to the character representing it +/// Converts a number to the character representing it. /// /// # Return value /// @@ -91,6 +108,15 @@ pub fn from_u32(i: u32) -> Option<char> { /// /// Panics if given an `radix` > 36. /// +/// # Examples +/// +/// ``` +/// use std::char; +/// +/// let c = char::from_digit(4, 10); +/// +/// assert_eq!(c, Some('4')); +/// ``` #[inline] #[unstable(feature = "core", reason = "pending integer conventions")] pub fn from_digit(num: uint, radix: uint) -> Option<char> { @@ -126,6 +152,16 @@ pub trait CharExt { /// # Panics /// /// Panics if given a radix > 36. + /// + /// # Examples + /// + /// ``` + /// let c = '1'; + /// + /// assert!(c.is_digit(10)); + /// + /// assert!('f'.is_digit(16)); + /// ``` #[unstable(feature = "core", reason = "pending integer conventions")] fn is_digit(self, radix: uint) -> bool; @@ -141,16 +177,53 @@ pub trait CharExt { /// # Panics /// /// Panics if given a radix outside the range [0..36]. + /// + /// # Examples + /// + /// ``` + /// let c = '1'; + /// + /// assert_eq!(c.to_digit(10), Some(1)); + /// + /// assert_eq!('f'.to_digit(16), Some(15)); + /// ``` #[unstable(feature = "core", reason = "pending integer conventions")] fn to_digit(self, radix: uint) -> Option<uint>; - /// Returns an iterator that yields the hexadecimal Unicode escape - /// of a character, as `char`s. + /// Returns an iterator that yields the hexadecimal Unicode escape of a character, as `char`s. + /// + /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` where `NNNN` is the + /// shortest hexadecimal representation of the code point. + /// + /// # Examples + /// + /// ``` + /// for i in '❤'.escape_unicode() { + /// println!("{}", i); + /// } + /// ``` /// - /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` - /// where `NNNN` is the shortest hexadecimal representation of the code - /// point. + /// This prints: + /// + /// ```text + /// \ + /// u + /// { + /// 2 + /// 7 + /// 6 + /// 4 + /// } + /// ``` + /// + /// Collecting into a `String`: + /// + /// ``` + /// let heart: String = '❤'.escape_unicode().collect(); + /// + /// assert_eq!(heart, r"\u{2764}"); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn escape_unicode(self) -> EscapeUnicode; @@ -166,32 +239,113 @@ pub trait CharExt { /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. + /// + /// # Examples + /// + /// ``` + /// for i in '"'.escape_default() { + /// println!("{}", i); + /// } + /// ``` + /// + /// This prints: + /// + /// ```text + /// \ + /// " + /// ``` + /// + /// Collecting into a `String`: + /// + /// ``` + /// let quote: String = '"'.escape_default().collect(); + /// + /// assert_eq!(quote, "\\\""); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn escape_default(self) -> EscapeDefault; - /// Returns the amount of bytes this character would need if encoded in - /// UTF-8. + /// Returns the number of bytes this character would need if encoded in UTF-8. + /// + /// # Examples + /// + /// ``` + /// let n = 'ß'.len_utf8(); + /// + /// assert_eq!(n, 2); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn len_utf8(self) -> uint; - /// Returns the amount of bytes this character would need if encoded in - /// UTF-16. + /// Returns the number of bytes this character would need if encoded in UTF-16. + /// + /// # Examples + /// + /// ``` + /// let n = 'ß'.len_utf16(); + /// + /// assert_eq!(n, 1); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn len_utf16(self) -> uint; - /// Encodes this character as UTF-8 into the provided byte buffer, - /// and then returns the number of bytes written. + /// Encodes this character as UTF-8 into the provided byte buffer, and then returns the number + /// of bytes written. + /// + /// If the buffer is not large enough, nothing will be written into it and a `None` will be + /// returned. + /// + /// # Examples + /// + /// In both of these examples, 'ß' takes two bytes to encode. + /// + /// ``` + /// let mut b = [0; 2]; /// - /// If the buffer is not large enough, nothing will be written into it - /// and a `None` will be returned. + /// let result = 'ß'.encode_utf8(&mut b); + /// + /// assert_eq!(result, Some(2)); + /// ``` + /// + /// A buffer that's too small: + /// + /// ``` + /// let mut b = [0; 1]; + /// + /// let result = 'ß'.encode_utf8(&mut b); + /// + /// assert_eq!(result, None); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>; - /// Encodes this character as UTF-16 into the provided `u16` buffer, - /// and then returns the number of `u16`s written. + /// Encodes this character as UTF-16 into the provided `u16` buffer, and then returns the + /// number of `u16`s written. + /// + /// If the buffer is not large enough, nothing will be written into it and a `None` will be + /// returned. + /// + /// # Examples + /// + /// In both of these examples, 'ß' takes one byte to encode. + /// + /// ``` + /// let mut b = [0; 1]; + /// + /// let result = 'ß'.encode_utf16(&mut b); + /// + /// assert_eq!(result, Some(1)); + /// ``` + /// + /// A buffer that's too small: + /// + /// ``` + /// let mut b = [0; 0]; + /// + /// let result = 'ß'.encode_utf8(&mut b); /// - /// If the buffer is not large enough, nothing will be written into it - /// and a `None` will be returned. + /// assert_eq!(result, None); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>; } diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 2ff67ebd550..551277bae5c 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -13,7 +13,7 @@ #![stable(feature = "rust1", since = "1.0.0")] use any; -use cell::{Cell, RefCell, Ref, RefMut}; +use cell::{Cell, RefCell, Ref, RefMut, BorrowState}; use char::CharExt; use iter::{Iterator, IteratorExt}; use marker::{Copy, Sized}; @@ -38,7 +38,6 @@ mod float; #[stable(feature = "rust1", since = "1.0.0")] #[doc(hidden)] pub mod rt { - #[cfg(stage0)] pub use self::v1::*; pub mod v1; } @@ -191,38 +190,6 @@ impl<'a> Arguments<'a> { } } - /// When using the format_args!() macro, this function is used to generate the - /// Arguments structure. - #[doc(hidden)] #[inline] - #[cfg(stage0)] - #[stable(feature = "rust1", since = "1.0.0")] - pub fn new(pieces: &'a [&'a str], - args: &'a [ArgumentV1<'a>]) -> Arguments<'a> { - Arguments { - pieces: pieces, - fmt: None, - args: args - } - } - - /// This function is used to specify nonstandard formatting parameters. - /// The `pieces` array must be at least as long as `fmt` to construct - /// a valid Arguments structure. Also, any `Count` within `fmt` that is - /// `CountIsParam` or `CountIsNextParam` has to point to an argument - /// created with `argumentuint`. However, failing to do so doesn't cause - /// unsafety, but will ignore invalid . - #[doc(hidden)] #[inline] - #[cfg(stage0)] - #[stable(feature = "rust1", since = "1.0.0")] - pub fn with_placeholders(pieces: &'a [&'a str], - fmt: &'a [rt::v1::Argument], - args: &'a [ArgumentV1<'a>]) -> Arguments<'a> { - Arguments { - pieces: pieces, - fmt: Some(fmt), - args: args - } - } /// This function is used to specify nonstandard formatting parameters. /// The `pieces` array must be at least as long as `fmt` to construct /// a valid Arguments structure. Also, any `Count` within `fmt` that is @@ -230,7 +197,6 @@ impl<'a> Arguments<'a> { /// created with `argumentuint`. However, failing to do so doesn't cause /// unsafety, but will ignore invalid . #[doc(hidden)] #[inline] - #[cfg(not(stage0))] pub fn new_v1_formatted(pieces: &'a [&'a str], args: &'a [ArgumentV1<'a>], fmt: &'a [rt::v1::Argument]) -> Arguments<'a> { @@ -516,7 +482,7 @@ impl<'a> Formatter<'a> { // Writes the sign if it exists, and then the prefix if it was requested let write_prefix = |&: f: &mut Formatter| { - for c in sign.into_iter() { + if let Some(c) = sign { let mut b = [0; 4]; let n = c.encode_utf8(&mut b).unwrap_or(0); let b = unsafe { str::from_utf8_unchecked(&b[..n]) }; @@ -684,25 +650,6 @@ impl Display for Error { } } -/// This is a function which calls are emitted to by the compiler itself to -/// create the Argument structures that are passed into the `format` function. -#[doc(hidden)] #[inline] -#[cfg(stage0)] -#[stable(feature = "rust1", since = "1.0.0")] -pub fn argument<'a, T>(f: fn(&T, &mut Formatter) -> Result, - t: &'a T) -> ArgumentV1<'a> { - ArgumentV1::new(t, f) -} - -/// When the compiler determines that the type of an argument *must* be a uint -/// (such as for width and precision), then it invokes this method. -#[doc(hidden)] #[inline] -#[cfg(stage0)] -#[stable(feature = "rust1", since = "1.0.0")] -pub fn argumentuint<'a>(s: &'a uint) -> ArgumentV1<'a> { - ArgumentV1::from_uint(s) -} - // Implementations of the core formatting traits macro_rules! fmt_refs { @@ -941,7 +888,7 @@ impl<T: Debug> Debug for [T] { try!(write!(f, "[")); } let mut is_first = true; - for x in self.iter() { + for x in self { if is_first { is_first = false; } else { @@ -973,9 +920,11 @@ impl<T: Copy + Debug> Debug for Cell<T> { #[stable(feature = "rust1", since = "1.0.0")] impl<T: Debug> Debug for RefCell<T> { fn fmt(&self, f: &mut Formatter) -> Result { - match self.try_borrow() { - Some(val) => write!(f, "RefCell {{ value: {:?} }}", val), - None => write!(f, "RefCell {{ <borrowed> }}") + match self.borrow_state() { + BorrowState::Unused | BorrowState::Reading => { + write!(f, "RefCell {{ value: {:?} }}", self.borrow()) + } + BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"), } } } diff --git a/src/libcore/fmt/rt/v1.rs b/src/libcore/fmt/rt/v1.rs index f0c82759b70..0c9bb6316e0 100644 --- a/src/libcore/fmt/rt/v1.rs +++ b/src/libcore/fmt/rt/v1.rs @@ -16,19 +16,6 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[cfg(stage0)] pub use self::Position::*; - -#[cfg(stage0)] pub use self::Alignment::Left as AlignLeft; -#[cfg(stage0)] pub use self::Alignment::Right as AlignRight; -#[cfg(stage0)] pub use self::Alignment::Center as AlignCenter; -#[cfg(stage0)] pub use self::Alignment::Unknown as AlignUnknown; -#[cfg(stage0)] pub use self::Count::Is as CountIs; -#[cfg(stage0)] pub use self::Count::Implied as CountImplied; -#[cfg(stage0)] pub use self::Count::Param as CountIsParam; -#[cfg(stage0)] pub use self::Count::NextParam as CountIsNextParam; -#[cfg(stage0)] pub use self::Position::Next as ArgumentNext; -#[cfg(stage0)] pub use self::Position::At as ArgumentIs; - #[derive(Copy)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Argument { diff --git a/src/libcore/hash/mod.rs b/src/libcore/hash/mod.rs index 5a4d2fffade..d73e6ed589f 100644 --- a/src/libcore/hash/mod.rs +++ b/src/libcore/hash/mod.rs @@ -205,7 +205,7 @@ impl<S: Writer + Hasher, T: Hash<S>> Hash<S> for [T] { #[inline] fn hash(&self, state: &mut S) { self.len().hash(state); - for elt in self.iter() { + for elt in self { elt.hash(state); } } diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index c782452d4cf..d0734f9c039 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -174,7 +174,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn last(mut self) -> Option<Self::Item> { + fn last(self) -> Option<Self::Item> { let mut last = None; for x in self { last = Some(x); } last @@ -239,9 +239,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn zip<B, U>(self, other: U) -> Zip<Self, U> where - U: Iterator<Item=B>, - { + fn zip<U: Iterator>(self, other: U) -> Zip<Self, U> { Zip{a: self, b: other} } @@ -259,7 +257,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn map<B, F>(self, f: F) -> Map<Self::Item, B, Self, F> where + fn map<B, F>(self, f: F) -> Map<Self, F> where F: FnMut(Self::Item) -> B, { Map{iter: self, f: f} @@ -279,7 +277,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn filter<P>(self, predicate: P) -> Filter<Self::Item, Self, P> where + fn filter<P>(self, predicate: P) -> Filter<Self, P> where P: FnMut(&Self::Item) -> bool, { Filter{iter: self, predicate: predicate} @@ -299,7 +297,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn filter_map<B, F>(self, f: F) -> FilterMap<Self::Item, B, Self, F> where + fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(Self::Item) -> Option<B>, { FilterMap { iter: self, f: f } @@ -342,7 +340,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn peekable(self) -> Peekable<Self::Item, Self> { + fn peekable(self) -> Peekable<Self> { Peekable{iter: self, peeked: None} } @@ -362,7 +360,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn skip_while<P>(self, predicate: P) -> SkipWhile<Self::Item, Self, P> where + fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where P: FnMut(&Self::Item) -> bool, { SkipWhile{iter: self, flag: false, predicate: predicate} @@ -383,7 +381,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn take_while<P>(self, predicate: P) -> TakeWhile<Self::Item, Self, P> where + fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where P: FnMut(&Self::Item) -> bool, { TakeWhile{iter: self, flag: false, predicate: predicate} @@ -448,12 +446,8 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn scan<St, B, F>( - self, - initial_state: St, - f: F, - ) -> Scan<Self::Item, B, Self, St, F> where - F: FnMut(&mut St, Self::Item) -> Option<B>, + fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> + where F: FnMut(&mut St, Self::Item) -> Option<B>, { Scan{iter: self, f: f, state: initial_state} } @@ -474,9 +468,8 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn flat_map<B, U, F>(self, f: F) -> FlatMap<Self::Item, B, Self, U, F> where - U: Iterator<Item=B>, - F: FnMut(Self::Item) -> U, + fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> + where U: Iterator, F: FnMut(Self::Item) -> U, { FlatMap{iter: self, f: f, frontiter: None, backiter: None } } @@ -534,7 +527,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn inspect<F>(self, f: F) -> Inspect<Self::Item, Self, F> where + fn inspect<F>(self, f: F) -> Inspect<Self, F> where F: FnMut(&Self::Item), { Inspect{iter: self, f: f} @@ -588,7 +581,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[unstable(feature = "core", reason = "recently added as part of collections reform")] - fn partition<B, F>(mut self, mut f: F) -> (B, B) where + fn partition<B, F>(self, mut f: F) -> (B, B) where B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool { @@ -617,7 +610,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn fold<B, F>(mut self, init: B, mut f: F) -> B where + fn fold<B, F>(self, init: B, mut f: F) -> B where F: FnMut(B, Self::Item) -> B, { let mut accum = init; @@ -638,7 +631,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn all<F>(mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool { + fn all<F>(self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool { for x in self { if !f(x) { return false; } } true } @@ -946,7 +939,7 @@ pub trait IteratorExt: Iterator + Sized { /// assert_eq!([2, 4], right); /// ``` #[unstable(feature = "core", reason = "recent addition")] - fn unzip<A, B, FromA, FromB>(mut self) -> (FromA, FromB) where + fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Iterator<Item=(A, B)>, @@ -1077,16 +1070,14 @@ pub trait ExactSizeIterator: Iterator { #[stable(feature = "rust1", since = "1.0.0")] impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {} #[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, F> ExactSizeIterator for Inspect<A, I, F> where - I: ExactSizeIterator<Item=A>, - F: FnMut(&A), +impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where + F: FnMut(&I::Item), {} #[stable(feature = "rust1", since = "1.0.0")] impl<I> ExactSizeIterator for Rev<I> where I: ExactSizeIterator + DoubleEndedIterator {} #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, F> ExactSizeIterator for Map<A, B, I, F> where - I: ExactSizeIterator<Item=A>, - F: FnMut(A) -> B, +impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where + F: FnMut(I::Item) -> B, {} #[stable(feature = "rust1", since = "1.0.0")] impl<A, B> ExactSizeIterator for Zip<A, B> where A: ExactSizeIterator, B: ExactSizeIterator {} @@ -1561,28 +1552,15 @@ impl<T, U, A, B> RandomAccessIterator for Zip<A, B> where /// An iterator that maps the values of `iter` with `f` #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Map<A, B, I: Iterator<Item=A>, F: FnMut(A) -> B> { +#[derive(Clone)] +pub struct Map<I, F> { iter: I, f: F, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, F> Clone for Map<A, B, I, F> where - I: Clone + Iterator<Item=A>, - F: Clone + FnMut(A) -> B, -{ - fn clone(&self) -> Map<A, B, I, F> { - Map { - iter: self.iter.clone(), - f: self.f.clone(), - } - } -} - -impl<A, B, I, F> Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B { +impl<I: Iterator, F, B> Map<I, F> where F: FnMut(I::Item) -> B { #[inline] - fn do_map(&mut self, elt: Option<A>) -> Option<B> { + fn do_map(&mut self, elt: Option<I::Item>) -> Option<B> { match elt { Some(a) => Some((self.f)(a)), _ => None @@ -1591,7 +1569,7 @@ impl<A, B, I, F> Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B { } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, F> Iterator for Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B { +impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B { type Item = B; #[inline] @@ -1607,9 +1585,8 @@ impl<A, B, I, F> Iterator for Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMu } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, F> DoubleEndedIterator for Map<A, B, I, F> where - I: DoubleEndedIterator<Item=A>, - F: FnMut(A) -> B, +impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where + F: FnMut(I::Item) -> B, { #[inline] fn next_back(&mut self) -> Option<B> { @@ -1619,9 +1596,8 @@ impl<A, B, I, F> DoubleEndedIterator for Map<A, B, I, F> where } #[unstable(feature = "core", reason = "trait is experimental")] -impl<A, B, I, F> RandomAccessIterator for Map<A, B, I, F> where - I: RandomAccessIterator<Item=A>, - F: FnMut(A) -> B, +impl<B, I: RandomAccessIterator, F> RandomAccessIterator for Map<I, F> where + F: FnMut(I::Item) -> B, { #[inline] fn indexable(&self) -> usize { @@ -1638,31 +1614,18 @@ impl<A, B, I, F> RandomAccessIterator for Map<A, B, I, F> where /// An iterator that filters the elements of `iter` with `predicate` #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool { +#[derive(Clone)] +pub struct Filter<I, P> { iter: I, predicate: P, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, P> Clone for Filter<A, I, P> where - I: Clone + Iterator<Item=A>, - P: Clone + FnMut(&A) -> bool, -{ - fn clone(&self) -> Filter<A, I, P> { - Filter { - iter: self.iter.clone(), - predicate: self.predicate.clone(), - } - } -} - #[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, P> Iterator for Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool { - type Item = A; +impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool { + type Item = I::Item; #[inline] - fn next(&mut self) -> Option<A> { + fn next(&mut self) -> Option<I::Item> { for x in self.iter.by_ref() { if (self.predicate)(&x) { return Some(x); @@ -1681,12 +1644,11 @@ impl<A, I, P> Iterator for Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(& } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, P> DoubleEndedIterator for Filter<A, I, P> where - I: DoubleEndedIterator<Item=A>, - P: FnMut(&A) -> bool, +impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P> + where P: FnMut(&I::Item) -> bool, { #[inline] - fn next_back(&mut self) -> Option<A> { + fn next_back(&mut self) -> Option<I::Item> { for x in self.iter.by_ref().rev() { if (self.predicate)(&x) { return Some(x); @@ -1699,29 +1661,15 @@ impl<A, I, P> DoubleEndedIterator for Filter<A, I, P> where /// An iterator that uses `f` to both filter and map elements from `iter` #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct FilterMap<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> Option<B> { +#[derive(Clone)] +pub struct FilterMap<I, F> { iter: I, f: F, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, F> Clone for FilterMap<A, B, I, F> where - I: Clone + Iterator<Item=A>, - F: Clone + FnMut(A) -> Option<B>, -{ - fn clone(&self) -> FilterMap<A, B, I, F> { - FilterMap { - iter: self.iter.clone(), - f: self.f.clone(), - } - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, F> Iterator for FilterMap<A, B, I, F> where - I: Iterator<Item=A>, - F: FnMut(A) -> Option<B>, +impl<B, I: Iterator, F> Iterator for FilterMap<I, F> + where F: FnMut(I::Item) -> Option<B>, { type Item = B; @@ -1744,9 +1692,8 @@ impl<A, B, I, F> Iterator for FilterMap<A, B, I, F> where } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, F> DoubleEndedIterator for FilterMap<A, B, I, F> where - I: DoubleEndedIterator<Item=A>, - F: FnMut(A) -> Option<B>, +impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F> + where F: FnMut(I::Item) -> Option<B>, { #[inline] fn next_back(&mut self) -> Option<B> { @@ -1824,20 +1771,28 @@ impl<I> RandomAccessIterator for Enumerate<I> where I: RandomAccessIterator { } /// An iterator with a `peek()` that returns an optional reference to the next element. -#[derive(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Peekable<T, I> where I: Iterator<Item=T> { +pub struct Peekable<I: Iterator> { iter: I, - peeked: Option<T>, + peeked: Option<I::Item>, +} + +impl<I: Iterator + Clone> Clone for Peekable<I> where I::Item: Clone { + fn clone(&self) -> Peekable<I> { + Peekable { + iter: self.iter.clone(), + peeked: self.peeked.clone(), + } + } } #[stable(feature = "rust1", since = "1.0.0")] -impl<T, I> Iterator for Peekable<T, I> where I: Iterator<Item=T> { - type Item = T; +impl<I: Iterator> Iterator for Peekable<I> { + type Item = I::Item; #[inline] - fn next(&mut self) -> Option<T> { + fn next(&mut self) -> Option<I::Item> { if self.peeked.is_some() { self.peeked.take() } else { self.iter.next() } } @@ -1859,14 +1814,14 @@ impl<T, I> Iterator for Peekable<T, I> where I: Iterator<Item=T> { } #[stable(feature = "rust1", since = "1.0.0")] -impl<T, I> ExactSizeIterator for Peekable<T, I> where I: ExactSizeIterator<Item = T> {} +impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {} #[stable(feature = "rust1", since = "1.0.0")] -impl<T, I> Peekable<T, I> where I: Iterator<Item=T> { - /// Return a reference to the next element of the iterator with out advancing it, - /// or None if the iterator is exhausted. +impl<I: Iterator> Peekable<I> { + /// Return a reference to the next element of the iterator with out + /// advancing it, or None if the iterator is exhausted. #[inline] - pub fn peek(&mut self) -> Option<&T> { + pub fn peek(&mut self) -> Option<&I::Item> { if self.peeked.is_none() { self.peeked = self.iter.next(); } @@ -1886,33 +1841,21 @@ impl<T, I> Peekable<T, I> where I: Iterator<Item=T> { /// An iterator that rejects elements while `predicate` is true #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool { +#[derive(Clone)] +pub struct SkipWhile<I, P> { iter: I, flag: bool, predicate: P, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` #[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, P> Clone for SkipWhile<A, I, P> where - I: Clone + Iterator<Item=A>, - P: Clone + FnMut(&A) -> bool, +impl<I: Iterator, P> Iterator for SkipWhile<I, P> + where P: FnMut(&I::Item) -> bool { - fn clone(&self) -> SkipWhile<A, I, P> { - SkipWhile { - iter: self.iter.clone(), - flag: self.flag, - predicate: self.predicate.clone(), - } - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, P> Iterator for SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool { - type Item = A; + type Item = I::Item; #[inline] - fn next(&mut self) -> Option<A> { + fn next(&mut self) -> Option<I::Item> { for x in self.iter.by_ref() { if self.flag || !(self.predicate)(&x) { self.flag = true; @@ -1932,33 +1875,21 @@ impl<A, I, P> Iterator for SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMu /// An iterator that only accepts elements while `predicate` is true #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool { +#[derive(Clone)] +pub struct TakeWhile<I, P> { iter: I, flag: bool, predicate: P, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` #[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, P> Clone for TakeWhile<A, I, P> where - I: Clone + Iterator<Item=A>, - P: Clone + FnMut(&A) -> bool, +impl<I: Iterator, P> Iterator for TakeWhile<I, P> + where P: FnMut(&I::Item) -> bool { - fn clone(&self) -> TakeWhile<A, I, P> { - TakeWhile { - iter: self.iter.clone(), - flag: self.flag, - predicate: self.predicate.clone(), - } - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, P> Iterator for TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool { - type Item = A; + type Item = I::Item; #[inline] - fn next(&mut self) -> Option<A> { + fn next(&mut self) -> Option<I::Item> { if self.flag { None } else { @@ -2118,7 +2049,8 @@ impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {} /// An iterator to maintain state while iterating another iterator #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Scan<A, B, I, St, F> where I: Iterator, F: FnMut(&mut St, A) -> Option<B> { +#[derive(Clone)] +pub struct Scan<I, St, F> { iter: I, f: F, @@ -2126,26 +2058,9 @@ pub struct Scan<A, B, I, St, F> where I: Iterator, F: FnMut(&mut St, A) -> Optio pub state: St, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, St, F> Clone for Scan<A, B, I, St, F> where - I: Clone + Iterator<Item=A>, - St: Clone, - F: Clone + FnMut(&mut St, A) -> Option<B>, -{ - fn clone(&self) -> Scan<A, B, I, St, F> { - Scan { - iter: self.iter.clone(), - f: self.f.clone(), - state: self.state.clone(), - } - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, St, F> Iterator for Scan<A, B, I, St, F> where - I: Iterator<Item=A>, - F: FnMut(&mut St, A) -> Option<B>, +impl<B, I: Iterator, St, F> Iterator for Scan<I, St, F> where + F: FnMut(&mut St, I::Item) -> Option<B>, { type Item = B; @@ -2166,46 +2081,24 @@ impl<A, B, I, St, F> Iterator for Scan<A, B, I, St, F> where /// #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct FlatMap<A, B, I, U, F> where - I: Iterator<Item=A>, - U: Iterator<Item=B>, - F: FnMut(A) -> U, -{ +#[derive(Clone)] +pub struct FlatMap<I, U, F> { iter: I, f: F, frontiter: Option<U>, backiter: Option<U>, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, U, F> Clone for FlatMap<A, B, I, U, F> where - I: Clone + Iterator<Item=A>, - U: Clone + Iterator<Item=B>, - F: Clone + FnMut(A) -> U, -{ - fn clone(&self) -> FlatMap<A, B, I, U, F> { - FlatMap { - iter: self.iter.clone(), - f: self.f.clone(), - frontiter: self.frontiter.clone(), - backiter: self.backiter.clone(), - } - } -} - #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, U, F> Iterator for FlatMap<A, B, I, U, F> where - I: Iterator<Item=A>, - U: Iterator<Item=B>, - F: FnMut(A) -> U, +impl<I: Iterator, U: Iterator, F> Iterator for FlatMap<I, U, F> + where F: FnMut(I::Item) -> U, { - type Item = B; + type Item = U::Item; #[inline] - fn next(&mut self) -> Option<B> { + fn next(&mut self) -> Option<U::Item> { loop { - for inner in self.frontiter.iter_mut() { + if let Some(ref mut inner) = self.frontiter { for x in inner.by_ref() { return Some(x) } @@ -2230,15 +2123,14 @@ impl<A, B, I, U, F> Iterator for FlatMap<A, B, I, U, F> where } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B, I, U, F> DoubleEndedIterator for FlatMap<A, B, I, U, F> where - I: DoubleEndedIterator<Item=A>, - U: DoubleEndedIterator<Item=B>, - F: FnMut(A) -> U, +impl<I: DoubleEndedIterator, U: DoubleEndedIterator, F> DoubleEndedIterator + for FlatMap<I, U, F> + where F: FnMut(I::Item) -> U { #[inline] - fn next_back(&mut self) -> Option<B> { + fn next_back(&mut self) -> Option<U::Item> { loop { - for inner in self.backiter.iter_mut() { + if let Some(ref mut inner) = self.backiter { match inner.next_back() { None => (), y => return y @@ -2340,28 +2232,15 @@ impl<I> Fuse<I> { /// element before yielding it. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) { +#[derive(Clone)] +pub struct Inspect<I, F> { iter: I, f: F, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, F> Clone for Inspect<A, I, F> where - I: Clone + Iterator<Item=A>, - F: Clone + FnMut(&A), -{ - fn clone(&self) -> Inspect<A, I, F> { - Inspect { - iter: self.iter.clone(), - f: self.f.clone(), - } - } -} - -impl<A, I, F> Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) { +impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) { #[inline] - fn do_inspect(&mut self, elt: Option<A>) -> Option<A> { + fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> { match elt { Some(ref a) => (self.f)(a), None => () @@ -2372,11 +2251,11 @@ impl<A, I, F> Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) { } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, F> Iterator for Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) { - type Item = A; +impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) { + type Item = I::Item; #[inline] - fn next(&mut self) -> Option<A> { + fn next(&mut self) -> Option<I::Item> { let next = self.iter.next(); self.do_inspect(next) } @@ -2388,21 +2267,19 @@ impl<A, I, F> Iterator for Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut( } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, I, F> DoubleEndedIterator for Inspect<A, I, F> where - I: DoubleEndedIterator<Item=A>, - F: FnMut(&A), +impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F> + where F: FnMut(&I::Item), { #[inline] - fn next_back(&mut self) -> Option<A> { + fn next_back(&mut self) -> Option<I::Item> { let next = self.iter.next_back(); self.do_inspect(next) } } #[unstable(feature = "core", reason = "trait is experimental")] -impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where - I: RandomAccessIterator<Item=A>, - F: FnMut(&A), +impl<I: RandomAccessIterator, F> RandomAccessIterator for Inspect<I, F> + where F: FnMut(&I::Item), { #[inline] fn indexable(&self) -> usize { @@ -2410,7 +2287,7 @@ impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where } #[inline] - fn idx(&mut self, index: usize) -> Option<A> { + fn idx(&mut self, index: usize) -> Option<I::Item> { let element = self.iter.idx(index); self.do_inspect(element) } @@ -2426,9 +2303,11 @@ impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where /// use std::iter::Unfold; /// use std::num::Int; // For `.checked_add()` /// -/// // This iterator will yield up to the last Fibonacci number before the max value of `u32`. -/// // You can simply change `u32` to `u64` in this line if you want higher values than that. -/// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&mut (ref mut x2, ref mut x1)| { +/// // This iterator will yield up to the last Fibonacci number before the max +/// // value of `u32`. You can simply change `u32` to `u64` in this line if +/// // you want higher values than that. +/// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), +/// |&mut (ref mut x2, ref mut x1)| { /// // Attempt to get the next Fibonacci number /// // `x1` will be `None` if previously overflowed. /// let next = match (*x2, *x1) { @@ -2449,32 +2328,19 @@ impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where /// } /// ``` #[unstable(feature = "core")] -pub struct Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> { +#[derive(Clone)] +pub struct Unfold<St, F> { f: F, /// Internal state that will be passed to the closure on the next iteration pub state: St, } -// FIXME(#19839) Remove in favor of `#[derive(Clone)]` -#[stable(feature = "rust1", since = "1.0.0")] -impl<A, St, F> Clone for Unfold<A, St, F> where - F: Clone + FnMut(&mut St) -> Option<A>, - St: Clone, -{ - fn clone(&self) -> Unfold<A, St, F> { - Unfold { - f: self.f.clone(), - state: self.state.clone(), - } - } -} - #[unstable(feature = "core")] -impl<A, St, F> Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> { +impl<A, St, F> Unfold<St, F> where F: FnMut(&mut St) -> Option<A> { /// Creates a new iterator with the specified closure as the "iterator /// function" and an initial state to eventually pass to the closure #[inline] - pub fn new(initial_state: St, f: F) -> Unfold<A, St, F> { + pub fn new(initial_state: St, f: F) -> Unfold<St, F> { Unfold { f: f, state: initial_state @@ -2483,7 +2349,7 @@ impl<A, St, F> Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> { } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, St, F> Iterator for Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> { +impl<A, St, F> Iterator for Unfold<St, F> where F: FnMut(&mut St) -> Option<A> { type Item = A; #[inline] @@ -2899,7 +2765,7 @@ type IterateState<T, F> = (F, Option<T>, bool); /// An iterator that repeatedly applies a given function, starting /// from a given seed value. #[unstable(feature = "core")] -pub type Iterate<T, F> = Unfold<T, IterateState<T, F>, fn(&mut IterateState<T, F>) -> Option<T>>; +pub type Iterate<T, F> = Unfold<IterateState<T, F>, fn(&mut IterateState<T, F>) -> Option<T>>; /// Create a new iterator that produces an infinite sequence of /// repeated applications of the given function `f`. diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index d2bc30fa74a..5e9793f270d 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -59,7 +59,6 @@ #![no_std] #![allow(raw_pointer_derive)] #![deny(missing_docs)] -#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap #![feature(int_uint)] #![feature(intrinsics, lang_items)] diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index f656fd4b8b9..7af94c73f32 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -947,28 +947,11 @@ pub trait IndexMut<Index: ?Sized> { } /// An unbounded range. -#[cfg(stage0)] -#[derive(Copy, Clone, PartialEq, Eq)] -#[lang="full_range"] -#[unstable(feature = "core", reason = "may be renamed to RangeFull")] -pub struct FullRange; - -/// An unbounded range. -#[cfg(not(stage0))] #[derive(Copy, Clone, PartialEq, Eq)] #[lang="range_full"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RangeFull; -#[cfg(stage0)] -#[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Debug for FullRange { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt("..", fmt) - } -} - -#[cfg(not(stage0))] #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for RangeFull { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index 9d253178664..f4b1a0633de 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -26,9 +26,6 @@ // Reexported core operators pub use marker::{Copy, Send, Sized, Sync}; -#[cfg(stage0)] -pub use ops::{Drop, Fn, FnMut, FnOnce, FullRange}; -#[cfg(not(stage0))] pub use ops::{Drop, Fn, FnMut, FnOnce}; // Reexported functions diff --git a/src/libcore/result.rs b/src/libcore/result.rs index fc7d4e868f7..d610962f862 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -956,7 +956,7 @@ pub fn fold<T, E, F: FnMut(V, T) -> V, Iter: Iterator<Item=Result<T, E>>>( - mut iterator: Iter, + iterator: Iter, mut init: V, mut f: F) -> Result<V, E> { diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index a368ddba9bc..a750e81bf59 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -43,9 +43,6 @@ use default::Default; use iter::*; use num::Int; use ops::{FnMut, self, Index}; -#[cfg(stage0)] -use ops::FullRange as RangeFull; -#[cfg(not(stage0))] use ops::RangeFull; use option::Option; use option::Option::{None, Some}; @@ -769,16 +766,6 @@ impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> { } } -#[cfg(stage0)] -#[unstable(feature = "core")] -impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> { - type Output = [T]; - #[inline] - fn index(&self, _index: &ops::FullRange) -> &[T] { - self.as_slice() - } -} -#[cfg(not(stage0))] #[unstable(feature = "core")] impl<'a, T> ops::Index<RangeFull> for Iter<'a, T> { type Output = [T]; diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index cb7af3b3d35..8c0c16bafc4 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -478,7 +478,7 @@ impl<'a> DoubleEndedIterator for CharIndices<'a> { /// Created with `StrExt::bytes` #[stable(feature = "rust1", since = "1.0.0")] #[derive(Clone)] -pub struct Bytes<'a>(Map<&'a u8, u8, slice::Iter<'a, u8>, BytesDeref>); +pub struct Bytes<'a>(Map<slice::Iter<'a, u8>, BytesDeref>); delegate_iter!{exact u8 : Bytes<'a>} /// A temporary fn new type that ensures that the `Bytes` iterator @@ -526,7 +526,7 @@ pub struct Lines<'a> { /// An iterator over the lines of a string, separated by either `\n` or (`\r\n`). #[stable(feature = "rust1", since = "1.0.0")] pub struct LinesAny<'a> { - inner: Map<&'a str, &'a str, Lines<'a>, fn(&str) -> &str>, + inner: Map<Lines<'a>, fn(&str) -> &str>, } impl<'a, Sep> CharSplits<'a, Sep> { @@ -1266,16 +1266,6 @@ mod traits { } } - #[cfg(stage0)] - #[stable(feature = "rust1", since = "1.0.0")] - impl ops::Index<ops::FullRange> for str { - type Output = str; - #[inline] - fn index(&self, _index: &ops::FullRange) -> &str { - self - } - } - #[cfg(not(stage0))] #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeFull> for str { type Output = str; diff --git a/src/libcoretest/cell.rs b/src/libcoretest/cell.rs index 5815dbc0acc..8939bd61fe4 100644 --- a/src/libcoretest/cell.rs +++ b/src/libcoretest/cell.rs @@ -60,6 +60,7 @@ fn no_mut_then_imm_borrow() { let x = RefCell::new(0); let _b1 = x.borrow_mut(); assert!(x.try_borrow().is_none()); + assert_eq!(x.borrow_state(), BorrowState::Writing); } #[test] @@ -67,13 +68,16 @@ fn no_imm_then_borrow_mut() { let x = RefCell::new(0); let _b1 = x.borrow(); assert!(x.try_borrow_mut().is_none()); + assert_eq!(x.borrow_state(), BorrowState::Reading); } #[test] fn no_double_borrow_mut() { let x = RefCell::new(0); + assert_eq!(x.borrow_state(), BorrowState::Unused); let _b1 = x.borrow_mut(); assert!(x.try_borrow_mut().is_none()); + assert_eq!(x.borrow_state(), BorrowState::Writing); } #[test] diff --git a/src/libcoretest/cmp.rs b/src/libcoretest/cmp.rs index 6bc1f14cc5a..2e5c6fe5a2f 100644 --- a/src/libcoretest/cmp.rs +++ b/src/libcoretest/cmp.rs @@ -66,11 +66,11 @@ fn test_partial_min() { (1.0f64, NAN, None) ]; - for &(a, b, result) in data_integer.iter() { + for &(a, b, result) in &data_integer { assert!(partial_min(a, b) == result); } - for &(a, b, result) in data_float.iter() { + for &(a, b, result) in &data_float { assert!(partial_min(a, b) == result); } } @@ -99,11 +99,11 @@ fn test_partial_max() { (1.0f64, NAN, None) ]; - for &(a, b, result) in data_integer.iter() { + for &(a, b, result) in &data_integer { assert!(partial_max(a, b) == result); } - for &(a, b, result) in data_float.iter() { + for &(a, b, result) in &data_float { assert!(partial_max(a, b) == result); } } diff --git a/src/libcoretest/hash/mod.rs b/src/libcoretest/hash/mod.rs index 07f3ab4a5a7..2da3f370b40 100644 --- a/src/libcoretest/hash/mod.rs +++ b/src/libcoretest/hash/mod.rs @@ -25,7 +25,7 @@ impl Default for MyHasher { impl Writer for MyHasher { // Most things we'll just add up the bytes. fn write(&mut self, buf: &[u8]) { - for byte in buf.iter() { + for byte in buf { self.hash += *byte as u64; } } diff --git a/src/libcoretest/hash/sip.rs b/src/libcoretest/hash/sip.rs index 431f7e748f6..a493f71925e 100644 --- a/src/libcoretest/hash/sip.rs +++ b/src/libcoretest/hash/sip.rs @@ -109,7 +109,7 @@ fn test_siphash() { fn to_hex_str(r: &[u8; 8]) -> String { let mut s = String::new(); - for b in r.iter() { + for b in r { s.push_str(format!("{}", fmt::radix(*b, 16)).as_slice()); } s @@ -130,7 +130,7 @@ fn test_siphash() { fn result_str(h: u64) -> String { let r = result_bytes(h); let mut s = String::new(); - for b in r.iter() { + for b in &r { s.push_str(format!("{}", fmt::radix(*b, 16)).as_slice()); } s diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs index 8a473ad43af..fc8d18df815 100644 --- a/src/libfmt_macros/lib.rs +++ b/src/libfmt_macros/lib.rs @@ -24,7 +24,6 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] -#![cfg_attr(stage0, feature(core))] #![feature(int_uint)] #![feature(slicing_syntax)] #![feature(staged_api)] diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 055672df5d1..b4eb8e9902a 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -315,7 +315,7 @@ impl Matches { /// Returns true if any of several options were matched. pub fn opts_present(&self, names: &[String]) -> bool { - for nm in names.iter() { + for nm in names { match find_opt(self.opts.as_slice(), Name::from_str(&nm[])) { Some(id) if !self.vals[id].is_empty() => return true, _ => (), @@ -326,7 +326,7 @@ impl Matches { /// Returns the string argument supplied to one of several matching options or `None`. pub fn opts_str(&self, names: &[String]) -> Option<String> { - for nm in names.iter() { + for nm in names { match self.opt_val(&nm[]) { Some(Val(ref s)) => return Some(s.clone()), _ => () @@ -342,7 +342,7 @@ impl Matches { pub fn opt_strs(&self, nm: &str) -> Vec<String> { let mut acc: Vec<String> = Vec::new(); let r = self.opt_vals(nm); - for v in r.iter() { + for v in &r { match *v { Val(ref s) => acc.push((*s).clone()), _ => () @@ -395,7 +395,7 @@ fn find_opt(opts: &[Opt], nm: Name) -> Option<uint> { } // Search in aliases. - for candidate in opts.iter() { + for candidate in opts { if candidate.aliases.iter().position(|opt| opt.name == nm).is_some() { return opts.iter().position(|opt| opt.name == candidate.name); } @@ -648,7 +648,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { } } let mut name_pos = 0; - for nm in names.iter() { + for nm in &names { name_pos += 1; let optid = match find_opt(opts.as_slice(), (*nm).clone()) { Some(id) => id, diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 3606387ad23..e9c7f837014 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -548,7 +548,7 @@ pub fn render_opts<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N options: &[RenderOption]) -> old_io::IoResult<()> { fn writeln<W:Writer>(w: &mut W, arg: &[&str]) -> old_io::IoResult<()> { - for &s in arg.iter() { try!(w.write_str(s)); } + for &s in arg { try!(w.write_str(s)); } w.write_char('\n') } @@ -557,7 +557,7 @@ pub fn render_opts<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N } try!(writeln(w, &["digraph ", g.graph_id().as_slice(), " {"])); - for n in g.nodes().iter() { + for n in &*g.nodes() { try!(indent(w)); let id = g.node_id(n); if options.contains(&RenderOption::NoNodeLabels) { @@ -569,7 +569,7 @@ pub fn render_opts<'a, N:Clone+'a, E:Clone+'a, G:Labeller<'a,N,E>+GraphWalk<'a,N } } - for e in g.edges().iter() { + for e in &*g.edges() { let escaped_label = g.edge_label(e).escape(); try!(indent(w)); let source = g.source(e); diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index bd8537f53cd..75867eb38be 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -280,7 +280,8 @@ pub use funcs::bsd43::{shutdown}; #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] pub use consts::os::posix01::{CLOCK_REALTIME, CLOCK_MONOTONIC}; #[cfg(any(target_os = "linux", target_os = "android"))] @@ -290,7 +291,7 @@ pub use types::os::arch::extra::{sockaddr_ll}; #[cfg(any(target_os = "linux", target_os = "android"))] pub use consts::os::extra::{AF_PACKET}; -#[cfg(all(unix, not(target_os = "freebsd")))] +#[cfg(all(unix, not(any(target_os = "freebsd", target_os = "openbsd"))))] pub use consts::os::extra::{MAP_STACK}; #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] @@ -1326,6 +1327,233 @@ pub mod types { } } + #[cfg(target_os = "openbsd")] + pub mod os { + pub mod common { + pub mod posix01 { + use types::common::c95::{c_void}; + use types::os::arch::c95::{c_char, c_int, size_t, + time_t, suseconds_t, c_long}; + use types::os::arch::c99::{uintptr_t}; + + pub type pthread_t = uintptr_t; + + #[repr(C)] + #[derive(Copy)] pub struct glob_t { + pub gl_pathc: c_int, + pub __unused1: c_int, + pub gl_offs: c_int, + pub __unused2: c_int, + pub gl_pathv: *mut *mut c_char, + + pub __unused3: *mut c_void, + + pub __unused4: *mut c_void, + pub __unused5: *mut c_void, + pub __unused6: *mut c_void, + pub __unused7: *mut c_void, + pub __unused8: *mut c_void, + pub __unused9: *mut c_void, + } + + #[repr(C)] + #[derive(Copy)] pub struct timeval { + pub tv_sec: time_t, + pub tv_usec: suseconds_t, + } + + #[repr(C)] + #[derive(Copy)] pub struct timespec { + pub tv_sec: time_t, + pub tv_nsec: c_long, + } + + #[derive(Copy)] pub enum timezone {} + + pub type sighandler_t = size_t; + } + pub mod bsd44 { + use types::common::c95::{c_void}; + use types::os::arch::c95::{c_char, c_int, c_uint}; + + pub type socklen_t = u32; + pub type sa_family_t = u8; + pub type in_port_t = u16; + pub type in_addr_t = u32; + #[repr(C)] + #[derive(Copy)] pub struct sockaddr { + pub sa_len: u8, + pub sa_family: sa_family_t, + pub sa_data: [u8; 14], + } + #[repr(C)] + #[derive(Copy)] pub struct sockaddr_storage { + pub ss_len: u8, + pub ss_family: sa_family_t, + pub __ss_pad1: [u8; 6], + pub __ss_pad2: i64, + pub __ss_pad3: [u8; 240], + } + #[repr(C)] + #[derive(Copy)] pub struct sockaddr_in { + pub sin_len: u8, + pub sin_family: sa_family_t, + pub sin_port: in_port_t, + pub sin_addr: in_addr, + pub sin_zero: [u8; 8], + } + #[repr(C)] + #[derive(Copy)] pub struct in_addr { + pub s_addr: in_addr_t, + } + #[repr(C)] + #[derive(Copy)] pub struct sockaddr_in6 { + pub sin6_len: u8, + pub sin6_family: sa_family_t, + pub sin6_port: in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: in6_addr, + pub sin6_scope_id: u32, + } + #[repr(C)] + #[derive(Copy)] pub struct in6_addr { + pub s6_addr: [u16; 8] + } + #[repr(C)] + #[derive(Copy)] pub struct ip_mreq { + pub imr_multiaddr: in_addr, + pub imr_interface: in_addr, + } + #[repr(C)] + #[derive(Copy)] pub struct ip6_mreq { + pub ipv6mr_multiaddr: in6_addr, + pub ipv6mr_interface: c_uint, + } + #[repr(C)] + #[derive(Copy)] pub struct addrinfo { + pub ai_flags: c_int, + pub ai_family: c_int, + pub ai_socktype: c_int, + pub ai_protocol: c_int, + pub ai_addrlen: socklen_t, + pub ai_addr: *mut sockaddr, + pub ai_canonname: *mut c_char, + pub ai_next: *mut addrinfo, + } + #[repr(C)] + #[derive(Copy)] pub struct sockaddr_un { + pub sun_len: u8, + pub sun_family: sa_family_t, + pub sun_path: [c_char; 104] + } + #[repr(C)] + #[derive(Copy)] pub struct ifaddrs { + pub ifa_next: *mut ifaddrs, + pub ifa_name: *mut c_char, + pub ifa_flags: c_uint, + pub ifa_addr: *mut sockaddr, + pub ifa_netmask: *mut sockaddr, + pub ifa_dstaddr: *mut sockaddr, + pub ifa_data: *mut c_void + } + + } + } + + #[cfg(target_arch = "x86_64")] + pub mod arch { + pub mod c95 { + pub type c_char = i8; + pub type c_schar = i8; + pub type c_uchar = u8; + pub type c_short = i16; + pub type c_ushort = u16; + pub type c_int = i32; + pub type c_uint = u32; + pub type c_long = i64; + pub type c_ulong = u64; + pub type c_float = f32; + pub type c_double = f64; + pub type size_t = u64; + pub type ptrdiff_t = i64; + pub type clock_t = i64; + pub type time_t = i64; + pub type suseconds_t = i64; + pub type wchar_t = i32; + } + pub mod c99 { + pub type c_longlong = i64; + pub type c_ulonglong = u64; + pub type intptr_t = i64; + pub type uintptr_t = u64; + pub type intmax_t = i64; + pub type uintmax_t = u64; + } + pub mod posix88 { + pub type off_t = i64; + pub type dev_t = u32; + pub type ino_t = u64; + pub type pid_t = i32; + pub type uid_t = u32; + pub type gid_t = u32; + pub type useconds_t = u32; + pub type mode_t = u32; + pub type ssize_t = i64; + } + pub mod posix01 { + use types::common::c95::{c_void}; + use types::common::c99::{uint32_t, uint64_t}; + use types::os::arch::c95::{c_long, time_t}; + use types::os::arch::posix88::{dev_t, gid_t}; + use types::os::arch::posix88::{mode_t, off_t}; + use types::os::arch::posix88::{uid_t}; + + pub type nlink_t = u32; + pub type blksize_t = uint32_t; + pub type ino_t = uint64_t; + pub type blkcnt_t = i64; + pub type fflags_t = u32; // type not declared, but struct stat have u_int32_t + + #[repr(C)] + #[derive(Copy)] pub struct stat { + pub st_mode: mode_t, + pub st_dev: dev_t, + pub st_ino: ino_t, + pub st_nlink: nlink_t, + pub st_uid: uid_t, + pub st_gid: gid_t, + pub st_rdev: dev_t, + pub st_atime: time_t, + pub st_atime_nsec: c_long, + pub st_mtime: time_t, + pub st_mtime_nsec: c_long, + pub st_ctime: time_t, + pub st_ctime_nsec: c_long, + pub st_size: off_t, + pub st_blocks: blkcnt_t, + pub st_blksize: blksize_t, + pub st_flags: fflags_t, + pub st_gen: uint32_t, + pub st_birthtime: time_t, + pub st_birthtime_nsec: c_long, + } + #[repr(C)] + #[derive(Copy)] pub struct utimbuf { + pub actime: time_t, + pub modtime: time_t, + } + + pub type pthread_attr_t = *mut c_void; + } + pub mod posix08 { + } + pub mod bsd44 { + } + pub mod extra { + } + } + } + #[cfg(target_os = "windows")] pub mod os { pub mod common { @@ -3254,7 +3482,8 @@ pub mod consts { } } - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(any(target_os = "freebsd", + target_os = "dragonfly"))] pub mod os { pub mod c95 { use types::os::arch::c95::{c_int, c_uint}; @@ -3663,6 +3892,401 @@ pub mod consts { } } + #[cfg(target_os = "openbsd")] + pub mod os { + pub mod c95 { + use types::os::arch::c95::{c_int, c_uint}; + + pub const EXIT_FAILURE : c_int = 1; + pub const EXIT_SUCCESS : c_int = 0; + pub const RAND_MAX : c_int = 2147483647; + pub const EOF : c_int = -1; + pub const SEEK_SET : c_int = 0; + pub const SEEK_CUR : c_int = 1; + pub const SEEK_END : c_int = 2; + pub const _IOFBF : c_int = 0; + pub const _IONBF : c_int = 2; + pub const _IOLBF : c_int = 1; + pub const BUFSIZ : c_uint = 1024_u32; + pub const FOPEN_MAX : c_uint = 20_u32; + pub const FILENAME_MAX : c_uint = 1024_u32; + pub const L_tmpnam : c_uint = 1024_u32; + pub const TMP_MAX : c_uint = 308915776_u32; + } + pub mod c99 { + } + pub mod posix88 { + use types::common::c95::c_void; + use types::os::arch::c95::c_int; + use types::os::arch::posix88::mode_t; + + pub const O_RDONLY : c_int = 0; + pub const O_WRONLY : c_int = 1; + pub const O_RDWR : c_int = 2; + pub const O_APPEND : c_int = 8; + pub const O_CREAT : c_int = 512; + pub const O_EXCL : c_int = 2048; + pub const O_TRUNC : c_int = 1024; + pub const S_IFIFO : mode_t = 4096; + pub const S_IFCHR : mode_t = 8192; + pub const S_IFBLK : mode_t = 24576; + pub const S_IFDIR : mode_t = 16384; + pub const S_IFREG : mode_t = 32768; + pub const S_IFLNK : mode_t = 40960; + pub const S_IFMT : mode_t = 61440; + pub const S_IEXEC : mode_t = 64; + pub const S_IWRITE : mode_t = 128; + pub const S_IREAD : mode_t = 256; + pub const S_IRWXU : mode_t = 448; + pub const S_IXUSR : mode_t = 64; + pub const S_IWUSR : mode_t = 128; + pub const S_IRUSR : mode_t = 256; + pub const F_OK : c_int = 0; + pub const R_OK : c_int = 4; + pub const W_OK : c_int = 2; + pub const X_OK : c_int = 1; + pub const STDIN_FILENO : c_int = 0; + pub const STDOUT_FILENO : c_int = 1; + pub const STDERR_FILENO : c_int = 2; + pub const F_LOCK : c_int = 1; + pub const F_TEST : c_int = 3; + pub const F_TLOCK : c_int = 2; + pub const F_ULOCK : c_int = 0; + pub const SIGHUP : c_int = 1; + pub const SIGINT : c_int = 2; + pub const SIGQUIT : c_int = 3; + pub const SIGILL : c_int = 4; + pub const SIGABRT : c_int = 6; + pub const SIGFPE : c_int = 8; + pub const SIGKILL : c_int = 9; + pub const SIGSEGV : c_int = 11; + pub const SIGPIPE : c_int = 13; + pub const SIGALRM : c_int = 14; + pub const SIGTERM : c_int = 15; + + pub const PROT_NONE : c_int = 0; + pub const PROT_READ : c_int = 1; + pub const PROT_WRITE : c_int = 2; + pub const PROT_EXEC : c_int = 4; + + pub const MAP_FILE : c_int = 0x0000; + pub const MAP_SHARED : c_int = 0x0001; + pub const MAP_PRIVATE : c_int = 0x0002; + pub const MAP_FIXED : c_int = 0x0010; + pub const MAP_ANON : c_int = 0x1000; + + pub const MAP_FAILED : *mut c_void = -1 as *mut c_void; + + pub const MCL_CURRENT : c_int = 0x0001; + pub const MCL_FUTURE : c_int = 0x0002; + + pub const MS_SYNC : c_int = 0x0002; // changed + pub const MS_ASYNC : c_int = 0x0001; + pub const MS_INVALIDATE : c_int = 0x0004; // changed + + pub const EPERM : c_int = 1; // not checked + pub const ENOENT : c_int = 2; + pub const ESRCH : c_int = 3; + pub const EINTR : c_int = 4; + pub const EIO : c_int = 5; + pub const ENXIO : c_int = 6; + pub const E2BIG : c_int = 7; + pub const ENOEXEC : c_int = 8; + pub const EBADF : c_int = 9; + pub const ECHILD : c_int = 10; + pub const EDEADLK : c_int = 11; + pub const ENOMEM : c_int = 12; + pub const EACCES : c_int = 13; + pub const EFAULT : c_int = 14; + pub const ENOTBLK : c_int = 15; + pub const EBUSY : c_int = 16; + pub const EEXIST : c_int = 17; + pub const EXDEV : c_int = 18; + pub const ENODEV : c_int = 19; + pub const ENOTDIR : c_int = 20; + pub const EISDIR : c_int = 21; + pub const EINVAL : c_int = 22; + pub const ENFILE : c_int = 23; + pub const EMFILE : c_int = 24; + pub const ENOTTY : c_int = 25; + pub const ETXTBSY : c_int = 26; + pub const EFBIG : c_int = 27; + pub const ENOSPC : c_int = 28; + pub const ESPIPE : c_int = 29; + pub const EROFS : c_int = 30; + pub const EMLINK : c_int = 31; + pub const EPIPE : c_int = 32; + pub const EDOM : c_int = 33; + pub const ERANGE : c_int = 34; + pub const EAGAIN : c_int = 35; + pub const EWOULDBLOCK : c_int = 35; + pub const EINPROGRESS : c_int = 36; + pub const EALREADY : c_int = 37; + pub const ENOTSOCK : c_int = 38; + pub const EDESTADDRREQ : c_int = 39; + pub const EMSGSIZE : c_int = 40; + pub const EPROTOTYPE : c_int = 41; + pub const ENOPROTOOPT : c_int = 42; + pub const EPROTONOSUPPORT : c_int = 43; + pub const ESOCKTNOSUPPORT : c_int = 44; + pub const EOPNOTSUPP : c_int = 45; + pub const EPFNOSUPPORT : c_int = 46; + pub const EAFNOSUPPORT : c_int = 47; + pub const EADDRINUSE : c_int = 48; + pub const EADDRNOTAVAIL : c_int = 49; + pub const ENETDOWN : c_int = 50; + pub const ENETUNREACH : c_int = 51; + pub const ENETRESET : c_int = 52; + pub const ECONNABORTED : c_int = 53; + pub const ECONNRESET : c_int = 54; + pub const ENOBUFS : c_int = 55; + pub const EISCONN : c_int = 56; + pub const ENOTCONN : c_int = 57; + pub const ESHUTDOWN : c_int = 58; + pub const ETOOMANYREFS : c_int = 59; + pub const ETIMEDOUT : c_int = 60; + pub const ECONNREFUSED : c_int = 61; + pub const ELOOP : c_int = 62; + pub const ENAMETOOLONG : c_int = 63; + pub const EHOSTDOWN : c_int = 64; + pub const EHOSTUNREACH : c_int = 65; + pub const ENOTEMPTY : c_int = 66; + pub const EPROCLIM : c_int = 67; + pub const EUSERS : c_int = 68; + pub const EDQUOT : c_int = 69; + pub const ESTALE : c_int = 70; + pub const EREMOTE : c_int = 71; + pub const EBADRPC : c_int = 72; + pub const ERPCMISMATCH : c_int = 73; + pub const EPROGUNAVAIL : c_int = 74; + pub const EPROGMISMATCH : c_int = 75; + pub const EPROCUNAVAIL : c_int = 76; + pub const ENOLCK : c_int = 77; + pub const ENOSYS : c_int = 78; + pub const EFTYPE : c_int = 79; + pub const EAUTH : c_int = 80; + pub const ENEEDAUTH : c_int = 81; + pub const EIDRM : c_int = 82; + pub const ENOMSG : c_int = 83; + pub const EOVERFLOW : c_int = 84; + pub const ECANCELED : c_int = 85; + pub const EILSEQ : c_int = 86; + pub const ENOATTR : c_int = 87; + pub const EDOOFUS : c_int = 88; + pub const EBADMSG : c_int = 89; + pub const EMULTIHOP : c_int = 90; + pub const ENOLINK : c_int = 91; + pub const EPROTO : c_int = 92; + pub const ENOMEDIUM : c_int = 93; + pub const EUNUSED94 : c_int = 94; + pub const EUNUSED95 : c_int = 95; + pub const EUNUSED96 : c_int = 96; + pub const EUNUSED97 : c_int = 97; + pub const EUNUSED98 : c_int = 98; + pub const EASYNC : c_int = 99; + pub const ELAST : c_int = 99; + } + pub mod posix01 { + use types::os::arch::c95::{c_int, size_t}; + + pub const F_DUPFD : c_int = 0; + pub const F_GETFD : c_int = 1; + pub const F_SETFD : c_int = 2; + pub const F_GETFL : c_int = 3; + pub const F_SETFL : c_int = 4; + + pub const SIGTRAP : c_int = 5; + pub const SIGPIPE: c_int = 13; + pub const SIG_IGN: size_t = 1; + + pub const GLOB_APPEND : c_int = 0x0001; + pub const GLOB_DOOFFS : c_int = 0x0002; + pub const GLOB_ERR : c_int = 0x0004; + pub const GLOB_MARK : c_int = 0x0008; + pub const GLOB_NOCHECK : c_int = 0x0010; + pub const GLOB_NOSORT : c_int = 0x0020; + pub const GLOB_NOESCAPE : c_int = 0x1000; // changed + + pub const GLOB_NOSPACE : c_int = -1; + pub const GLOB_ABORTED : c_int = -2; + pub const GLOB_NOMATCH : c_int = -3; + + pub const POSIX_MADV_NORMAL : c_int = 0; + pub const POSIX_MADV_RANDOM : c_int = 1; + pub const POSIX_MADV_SEQUENTIAL : c_int = 2; + pub const POSIX_MADV_WILLNEED : c_int = 3; + pub const POSIX_MADV_DONTNEED : c_int = 4; + + pub const _SC_IOV_MAX : c_int = 51; // all changed... + pub const _SC_GETGR_R_SIZE_MAX : c_int = 100; + pub const _SC_GETPW_R_SIZE_MAX : c_int = 101; + pub const _SC_LOGIN_NAME_MAX : c_int = 102; + pub const _SC_MQ_PRIO_MAX : c_int = 59; + pub const _SC_THREAD_ATTR_STACKADDR : c_int = 77; + pub const _SC_THREAD_ATTR_STACKSIZE : c_int = 78; + pub const _SC_THREAD_DESTRUCTOR_ITERATIONS : c_int = 80; + pub const _SC_THREAD_KEYS_MAX : c_int = 81; + pub const _SC_THREAD_PRIO_INHERIT : c_int = 82; + pub const _SC_THREAD_PRIO_PROTECT : c_int = 83; + pub const _SC_THREAD_PRIORITY_SCHEDULING : c_int = 84; + pub const _SC_THREAD_PROCESS_SHARED : c_int = 85; + pub const _SC_THREAD_SAFE_FUNCTIONS : c_int = 103; + pub const _SC_THREAD_STACK_MIN : c_int = 89; + pub const _SC_THREAD_THREADS_MAX : c_int = 90; + pub const _SC_THREADS : c_int = 91; + pub const _SC_TTY_NAME_MAX : c_int = 107; + pub const _SC_ATEXIT_MAX : c_int = 46; + pub const _SC_XOPEN_CRYPT : c_int = 117; + pub const _SC_XOPEN_ENH_I18N : c_int = 118; + pub const _SC_XOPEN_LEGACY : c_int = 119; + pub const _SC_XOPEN_REALTIME : c_int = 120; + pub const _SC_XOPEN_REALTIME_THREADS : c_int = 121; + pub const _SC_XOPEN_SHM : c_int = 30; + pub const _SC_XOPEN_UNIX : c_int = 123; + pub const _SC_XOPEN_VERSION : c_int = 125; + //pub const _SC_XOPEN_XCU_VERSION : c_int = ; + + pub const PTHREAD_CREATE_JOINABLE: c_int = 0; + pub const PTHREAD_CREATE_DETACHED: c_int = 1; + pub const PTHREAD_STACK_MIN: size_t = 2048; + + pub const CLOCK_REALTIME: c_int = 0; + pub const CLOCK_MONOTONIC: c_int = 3; + } + pub mod posix08 { + } + pub mod bsd44 { + use types::os::arch::c95::c_int; + + pub const MADV_NORMAL : c_int = 0; + pub const MADV_RANDOM : c_int = 1; + pub const MADV_SEQUENTIAL : c_int = 2; + pub const MADV_WILLNEED : c_int = 3; + pub const MADV_DONTNEED : c_int = 4; + pub const MADV_FREE : c_int = 6; // changed + //pub const MADV_NOSYNC : c_int = ; + //pub const MADV_AUTOSYNC : c_int = ; + //pub const MADV_NOCORE : c_int = ; + //pub const MADV_CORE : c_int = ; + //pub const MADV_PROTECT : c_int = ; + + //pub const MINCORE_INCORE : c_int = ; + //pub const MINCORE_REFERENCED : c_int = ; + //pub const MINCORE_MODIFIED : c_int = ; + //pub const MINCORE_REFERENCED_OTHER : c_int = ; + //pub const MINCORE_MODIFIED_OTHER : c_int = ; + //pub const MINCORE_SUPER : c_int = ; + + pub const AF_INET: c_int = 2; + pub const AF_INET6: c_int = 24; // changed + pub const AF_UNIX: c_int = 1; + pub const SOCK_STREAM: c_int = 1; + pub const SOCK_DGRAM: c_int = 2; + pub const SOCK_RAW: c_int = 3; + pub const IPPROTO_TCP: c_int = 6; + pub const IPPROTO_IP: c_int = 0; + pub const IPPROTO_IPV6: c_int = 41; + pub const IP_MULTICAST_TTL: c_int = 10; + pub const IP_MULTICAST_LOOP: c_int = 11; + pub const IP_TTL: c_int = 4; + pub const IP_HDRINCL: c_int = 2; + pub const IP_ADD_MEMBERSHIP: c_int = 12; + pub const IP_DROP_MEMBERSHIP: c_int = 13; + // don't exist, keep same as IP_ADD_MEMBERSHIP + pub const IPV6_ADD_MEMBERSHIP: c_int = 12; + // don't exist, keep same as IP_DROP_MEMBERSHIP + pub const IPV6_DROP_MEMBERSHIP: c_int = 13; + + pub const TCP_NODELAY: c_int = 1; + //pub const TCP_KEEPIDLE: c_int = ; + pub const SOL_SOCKET: c_int = 0xffff; + pub const SO_KEEPALIVE: c_int = 0x0008; + pub const SO_BROADCAST: c_int = 0x0020; + pub const SO_REUSEADDR: c_int = 0x0004; + pub const SO_ERROR: c_int = 0x1007; + + pub const IFF_LOOPBACK: c_int = 0x8; + + pub const SHUT_RD: c_int = 0; + pub const SHUT_WR: c_int = 1; + pub const SHUT_RDWR: c_int = 2; + } + pub mod extra { + use types::os::arch::c95::c_int; + + pub const O_SYNC : c_int = 128; + pub const O_NONBLOCK : c_int = 4; + pub const CTL_KERN: c_int = 1; + pub const KERN_PROC: c_int = 66; + + pub const MAP_COPY : c_int = 0x0002; + pub const MAP_RENAME : c_int = 0x0000; // changed + pub const MAP_NORESERVE : c_int = 0x0000; // changed + pub const MAP_HASSEMAPHORE : c_int = 0x0000; // changed + //pub const MAP_STACK : c_int = ; + //pub const MAP_NOSYNC : c_int = ; + //pub const MAP_NOCORE : c_int = ; + + pub const IPPROTO_RAW : c_int = 255; + } + pub mod sysconf { + use types::os::arch::c95::c_int; + + pub const _SC_ARG_MAX : c_int = 1; + pub const _SC_CHILD_MAX : c_int = 2; + pub const _SC_CLK_TCK : c_int = 3; + pub const _SC_NGROUPS_MAX : c_int = 4; + pub const _SC_OPEN_MAX : c_int = 5; + pub const _SC_JOB_CONTROL : c_int = 6; + pub const _SC_SAVED_IDS : c_int = 7; + pub const _SC_VERSION : c_int = 8; + pub const _SC_BC_BASE_MAX : c_int = 9; + pub const _SC_BC_DIM_MAX : c_int = 10; + pub const _SC_BC_SCALE_MAX : c_int = 11; + pub const _SC_BC_STRING_MAX : c_int = 12; + pub const _SC_COLL_WEIGHTS_MAX : c_int = 13; + pub const _SC_EXPR_NEST_MAX : c_int = 14; + pub const _SC_LINE_MAX : c_int = 15; + pub const _SC_RE_DUP_MAX : c_int = 16; + pub const _SC_2_VERSION : c_int = 17; + pub const _SC_2_C_BIND : c_int = 18; + pub const _SC_2_C_DEV : c_int = 19; + pub const _SC_2_CHAR_TERM : c_int = 20; + pub const _SC_2_FORT_DEV : c_int = 21; + pub const _SC_2_FORT_RUN : c_int = 22; + pub const _SC_2_LOCALEDEF : c_int = 23; + pub const _SC_2_SW_DEV : c_int = 24; + pub const _SC_2_UPE : c_int = 25; + pub const _SC_STREAM_MAX : c_int = 26; + pub const _SC_TZNAME_MAX : c_int = 27; + pub const _SC_ASYNCHRONOUS_IO : c_int = 45; // changed... + pub const _SC_MAPPED_FILES : c_int = 53; + pub const _SC_MEMLOCK : c_int = 54; + pub const _SC_MEMLOCK_RANGE : c_int = 55; + pub const _SC_MEMORY_PROTECTION : c_int = 56; + pub const _SC_MESSAGE_PASSING : c_int = 57; + pub const _SC_PRIORITIZED_IO : c_int = 60; + pub const _SC_PRIORITY_SCHEDULING : c_int = 61; + pub const _SC_REALTIME_SIGNALS : c_int = 64; + pub const _SC_SEMAPHORES : c_int = 67; + pub const _SC_FSYNC : c_int = 29; + pub const _SC_SHARED_MEMORY_OBJECTS : c_int = 68; + pub const _SC_SYNCHRONIZED_IO : c_int = 75; + pub const _SC_TIMERS : c_int = 94; // ...changed + pub const _SC_AIO_LISTIO_MAX : c_int = 42; + pub const _SC_AIO_MAX : c_int = 43; + pub const _SC_AIO_PRIO_DELTA_MAX : c_int = 44; + pub const _SC_DELAYTIMER_MAX : c_int = 50; // changed... + pub const _SC_MQ_OPEN_MAX : c_int = 58; + pub const _SC_PAGESIZE : c_int = 28; + pub const _SC_RTSIG_MAX : c_int = 66; + pub const _SC_SEM_NSEMS_MAX : c_int = 31; + pub const _SC_SEM_VALUE_MAX : c_int = 32; + pub const _SC_SIGQUEUE_MAX : c_int = 70; + pub const _SC_TIMER_MAX : c_int = 93; + } + } + #[cfg(any(target_os = "macos", target_os = "ios"))] pub mod os { pub mod c95 { @@ -4380,7 +5004,8 @@ pub mod funcs { target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] pub mod posix88 { pub mod stat_ { use types::os::arch::c95::{c_char, c_int}; @@ -4394,6 +5019,7 @@ pub mod funcs { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", + target_os = "openbsd", target_os = "android", target_os = "ios"))] pub fn fstat(fildes: c_int, buf: *mut stat) -> c_int; @@ -4408,6 +5034,7 @@ pub mod funcs { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", + target_os = "openbsd", target_os = "android", target_os = "ios"))] pub fn stat(path: *const c_char, buf: *mut stat) -> c_int; @@ -4600,7 +5227,8 @@ pub mod funcs { target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] pub mod posix01 { pub mod stat_ { use types::os::arch::c95::{c_char, c_int}; @@ -4610,6 +5238,7 @@ pub mod funcs { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", + target_os = "openbsd", target_os = "android", target_os = "ios"))] pub fn lstat(path: *const c_char, buf: *mut stat) -> c_int; @@ -4717,7 +5346,8 @@ pub mod funcs { target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] pub mod posix08 { pub mod unistd { } @@ -4803,7 +5433,8 @@ pub mod funcs { #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] pub mod bsd44 { use types::common::c95::{c_void}; use types::os::arch::c95::{c_char, c_uchar, c_int, c_uint, c_ulong, size_t}; @@ -4866,7 +5497,9 @@ pub mod funcs { } } - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(any(target_os = "freebsd", + target_os = "dragonfly", + target_os = "openbsd"))] pub mod extra { } diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index 81d8c60f893..34216518c21 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -173,15 +173,15 @@ #![feature(int_uint)] #![feature(core)] #![feature(io)] -#![feature(os)] #![feature(std_misc)] +#![feature(env)] use std::cell::RefCell; use std::fmt; use std::old_io::LineBufferedWriter; use std::old_io; use std::mem; -use std::os; +use std::env; use std::ptr; use std::rt; use std::slice; @@ -397,9 +397,9 @@ fn enabled(level: u32, /// This is not threadsafe at all, so initialization is performed through a /// `Once` primitive (and this function is called from that primitive). fn init() { - let (mut directives, filter) = match os::getenv("RUST_LOG") { - Some(spec) => directive::parse_logging_spec(&spec[]), - None => (Vec::new(), None), + let (mut directives, filter) = match env::var_string("RUST_LOG") { + Ok(spec) => directive::parse_logging_spec(&spec[]), + Err(..) => (Vec::new(), None), }; // Sort the provided directives by length of their name, this allows a diff --git a/src/librand/chacha.rs b/src/librand/chacha.rs index 6bd971e7b5d..aef6301dad7 100644 --- a/src/librand/chacha.rs +++ b/src/librand/chacha.rs @@ -194,7 +194,7 @@ impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { impl Rand for ChaChaRng { fn rand<R: Rng>(other: &mut R) -> ChaChaRng { let mut key : [u32; KEY_WORDS] = [0; KEY_WORDS]; - for word in key.iter_mut() { + for word in &mut key { *word = other.gen(); } SeedableRng::from_seed(key.as_slice()) diff --git a/src/librand/distributions/mod.rs b/src/librand/distributions/mod.rs index 1b5e5ae8398..4958784f614 100644 --- a/src/librand/distributions/mod.rs +++ b/src/librand/distributions/mod.rs @@ -123,7 +123,7 @@ impl<'a, T: Clone> WeightedChoice<'a, T> { // we convert the list from individual weights to cumulative // weights so we can binary search. This *could* drop elements // with weight == 0 as an optimisation. - for item in items.iter_mut() { + for item in &mut *items { running_total = match running_total.checked_add(item.weight) { Some(n) => n, None => panic!("WeightedChoice::new called with a total weight \ @@ -305,7 +305,7 @@ mod tests { let mut rng = CountingRng { i: 0 }; - for &val in expected.iter() { + for &val in &expected { assert_eq!(wc.ind_sample(&mut rng), val) } }} diff --git a/src/librand/distributions/range.rs b/src/librand/distributions/range.rs index 16830c84c46..ab0b45e7d32 100644 --- a/src/librand/distributions/range.rs +++ b/src/librand/distributions/range.rs @@ -188,7 +188,7 @@ mod tests { let v: &[($ty, $ty)] = &[(0, 10), (10, 127), (Int::min_value(), Int::max_value())]; - for &(low, high) in v.iter() { + for &(low, high) in v { let mut sampler: Range<$ty> = Range::new(low, high); for _ in 0u..1000 { let v = sampler.sample(&mut rng); @@ -214,7 +214,7 @@ mod tests { (-1e35, -1e25), (1e-35, 1e-25), (-1e35, 1e35)]; - for &(low, high) in v.iter() { + for &(low, high) in v { let mut sampler: Range<$ty> = Range::new(low, high); for _ in 0u..1000 { let v = sampler.sample(&mut rng); diff --git a/src/librand/isaac.rs b/src/librand/isaac.rs index a22ef704fa5..d0f4afdde72 100644 --- a/src/librand/isaac.rs +++ b/src/librand/isaac.rs @@ -134,7 +134,7 @@ impl IsaacRng { } let r = [(0, MIDPOINT), (MIDPOINT, 0)]; - for &(mr_offset, m2_offset) in r.iter() { + for &(mr_offset, m2_offset) in &r { macro_rules! rngstepp { ($j:expr, $shift:expr) => {{ @@ -373,7 +373,7 @@ impl Isaac64Rng { } } - for &(mr_offset, m2_offset) in MP_VEC.iter() { + for &(mr_offset, m2_offset) in &MP_VEC { for base in (0..MIDPOINT / 4).map(|i| i * 4) { macro_rules! rngstepp { diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 3ff40038872..5290e680333 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -154,7 +154,7 @@ pub trait Rng : Sized { // optimisations are on. let mut count = 0; let mut num = 0; - for byte in dest.iter_mut() { + for byte in dest { if count == 0 { // we could micro-optimise here by generating a u32 if // we only need a few more bytes to fill the vector diff --git a/src/librand/reseeding.rs b/src/librand/reseeding.rs index 57e90139876..75ac1b2cf44 100644 --- a/src/librand/reseeding.rs +++ b/src/librand/reseeding.rs @@ -225,7 +225,7 @@ mod test { // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; - for &x in v.iter() { + for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64 != 0.0); diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index 6ae861fcb04..00324820433 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -23,8 +23,6 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap - #![feature(box_syntax)] #![feature(collections)] #![feature(core)] @@ -32,7 +30,7 @@ #![feature(int_uint)] #![feature(io)] #![feature(libc)] -#![feature(os)] +#![feature(env)] #![feature(path)] #![feature(quote)] #![feature(rustc_diagnostic_macros)] diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 904c9c3adb5..53054f462c8 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -227,7 +227,7 @@ impl LintPass for TypeLimits { if (negative && v > (min.abs() as u64)) || (!negative && v > (max.abs() as u64)) { cx.span_lint(OVERFLOWING_LITERALS, e.span, - "literal out of range for its type"); + &*format!("literal out of range for {:?}", t)); return; } } @@ -246,7 +246,7 @@ impl LintPass for TypeLimits { }; if lit_val < min || lit_val > max { cx.span_lint(OVERFLOWING_LITERALS, e.span, - "literal out of range for its type"); + &*format!("literal out of range for {:?}", t)); } }, ty::ty_float(t) => { @@ -263,7 +263,7 @@ impl LintPass for TypeLimits { }; if lit_val < min || lit_val > max { cx.span_lint(OVERFLOWING_LITERALS, e.span, - "literal out of range for its type"); + &*format!("literal out of range for {:?}", t)); } }, _ => () @@ -459,7 +459,7 @@ impl LintPass for ImproperCTypes { } fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) { - for input in decl.inputs.iter() { + for input in &decl.inputs { check_ty(cx, &*input.ty); } if let ast::Return(ref ret_ty) = decl.output { @@ -469,7 +469,7 @@ impl LintPass for ImproperCTypes { match it.node { ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => { - for ni in nmod.items.iter() { + for ni in &nmod.items { match ni.node { ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl), ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t) @@ -532,7 +532,7 @@ impl LintPass for BoxPointers { // If it's a struct, we also have to check the fields' types match it.node { ast::ItemStruct(ref struct_def, _) => { - for struct_field in struct_def.fields.iter() { + for struct_field in &struct_def.fields { self.check_heap_type(cx, struct_field.span, ty::node_id_to_type(cx.tcx, struct_field.node.id)); } @@ -592,7 +592,15 @@ impl LintPass for RawPointerDerive { return } let did = match item.node { - ast::ItemImpl(..) => { + ast::ItemImpl(_, _, _, ref t_ref_opt, _, _) => { + // Deriving the Copy trait does not cause a warning + if let &Some(ref trait_ref) = t_ref_opt { + let def_id = ty::trait_ref_to_def_id(cx.tcx, trait_ref); + if Some(def_id) == cx.tcx.lang_items.copy_trait() { + return + } + } + match ty::node_id_to_type(cx.tcx, item.id).sty { ty::ty_enum(did, _) => did, ty::ty_struct(did, _) => did, @@ -683,7 +691,7 @@ impl LintPass for UnusedAttributes { "no_builtins", ]; - for &name in ATTRIBUTE_WHITELIST.iter() { + for &name in ATTRIBUTE_WHITELIST { if attr.check_name(name) { break; } @@ -785,7 +793,7 @@ impl LintPass for UnusedResults { } fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool { - for attr in attrs.iter() { + for attr in attrs { if attr.check_name("must_use") { let mut msg = "unused result which must be used".to_string(); // check for #[must_use="..."] @@ -869,7 +877,7 @@ impl LintPass for NonCamelCaseTypes { ast::ItemEnum(ref enum_definition, _) => { if has_extern_repr { return } self.check_case(cx, "type", it.ident, it.span); - for variant in enum_definition.variants.iter() { + for variant in &enum_definition.variants { self.check_case(cx, "variant", variant.node.name, variant.span); } } @@ -878,7 +886,7 @@ impl LintPass for NonCamelCaseTypes { } fn check_generics(&mut self, cx: &Context, it: &ast::Generics) { - for gen in it.ty_params.iter() { + for gen in &*it.ty_params { self.check_case(cx, "type parameter", gen.ident, gen.span); } } @@ -1048,7 +1056,7 @@ impl LintPass for NonSnakeCase { fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { - for sf in s.fields.iter() { + for sf in &s.fields { if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node { self.check_snake_case(cx, "structure field", ident, sf.span); } @@ -1346,7 +1354,7 @@ impl UnusedMut { // avoid false warnings in match arms with multiple patterns let mut mutables = FnvHashMap(); - for p in pats.iter() { + for p in pats { pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| { let ident = path1.node; if let ast::BindByValue(ast::MutMutable) = mode { @@ -1361,7 +1369,7 @@ impl UnusedMut { } let used_mutables = cx.tcx.used_mut_nodes.borrow(); - for (_, v) in mutables.iter() { + for (_, v) in &mutables { if !v.iter().any(|e| used_mutables.contains(e)) { cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]), "variable does not need to be mutable"); @@ -1377,7 +1385,7 @@ impl LintPass for UnusedMut { fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { if let ast::ExprMatch(_, ref arms, _) = e.node { - for a in arms.iter() { + for a in arms { self.check_unused_mut_pat(cx, &a.pats[]) } } @@ -1394,7 +1402,7 @@ impl LintPass for UnusedMut { fn check_fn(&mut self, cx: &Context, _: visit::FnKind, decl: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { - for a in decl.inputs.iter() { + for a in &decl.inputs { self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat)); } } @@ -1871,7 +1879,7 @@ impl LintPass for UnconditionalRecursion { if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow { let sess = cx.sess(); // offer some help to the programmer. - for call in self_call_spans.iter() { + for call in &self_call_spans { sess.span_note(*call, "recursive call site") } sess.span_help(sp, "a `loop` may express intention better if this is on purpose") @@ -2006,7 +2014,7 @@ declare_lint! { declare_lint! { pub UNUSED_FEATURES, - Deny, + Warn, "unused or unknown features found in crate-level #[feature] directives" } diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index c649ff2635b..91dba90b0d2 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -116,7 +116,7 @@ impl LintStore { pub fn register_pass(&mut self, sess: Option<&Session>, from_plugin: bool, pass: LintPassObject) { - for &lint in pass.get_lints().iter() { + for &lint in pass.get_lints() { self.lints.push((*lint, from_plugin)); let id = LintId::of(*lint); @@ -260,7 +260,7 @@ impl LintStore { } pub fn process_command_line(&mut self, sess: &Session) { - for &(ref lint_name, level) in sess.opts.lint_opts.iter() { + for &(ref lint_name, level) in &sess.opts.lint_opts { match self.find_lint(&lint_name[], sess, None) { Some(lint_id) => self.set_level(lint_id, (level, CommandLine)), None => { @@ -329,7 +329,7 @@ macro_rules! run_lints { ($cx:expr, $f:ident, $($args:expr),*) => ({ // Move the vector of passes out of `$cx` so that we can // iterate over it mutably while passing `$cx` to the methods. let mut passes = $cx.lints.passes.take().unwrap(); - for obj in passes.iter_mut() { + for obj in &mut passes { obj.$f($cx, $($args),*); } $cx.lints.passes = Some(passes); @@ -340,7 +340,7 @@ macro_rules! run_lints { ($cx:expr, $f:ident, $($args:expr),*) => ({ pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec<Result<(InternedString, Level, Span), Span>> { let mut out = vec!(); - for attr in attrs.iter() { + for attr in attrs { let level = match Level::from_str(attr.name().get()) { None => continue, Some(lvl) => lvl, @@ -357,7 +357,7 @@ pub fn gather_attrs(attrs: &[ast::Attribute]) } }; - for meta in metas.iter() { + for meta in metas { out.push(match meta.node { ast::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)), _ => Err(meta.span), @@ -417,11 +417,11 @@ pub fn raw_emit_lint(sess: &Session, lint: &'static Lint, _ => sess.bug("impossible level in raw_emit_lint"), } - for note in note.into_iter() { + if let Some(note) = note { sess.note(¬e[]); } - for span in def.into_iter() { + if let Some(span) = def { sess.span_note(span, "lint level defined here"); } } @@ -492,7 +492,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> { // specified closure let mut pushed = 0; - for result in gather_attrs(attrs).into_iter() { + for result in gather_attrs(attrs) { let v = match result { Err(span) => { self.tcx.sess.span_err(span, "malformed lint attribute"); @@ -519,7 +519,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> { } }; - for (lint_id, level, span) in v.into_iter() { + for (lint_id, level, span) in v { let now = self.lints.get_level_source(lint_id).0; if now == Forbid && level != Forbid { let lint_name = lint_id.as_str(); @@ -727,7 +727,7 @@ impl<'a, 'tcx> IdVisitingOperation for Context<'a, 'tcx> { match self.tcx.sess.lints.borrow_mut().remove(&id) { None => {} Some(lints) => { - for (lint_id, span, msg) in lints.into_iter() { + for (lint_id, span, msg) in lints { self.span_lint(lint_id.lint, span, &msg[]) } } @@ -794,8 +794,8 @@ pub fn check_crate(tcx: &ty::ctxt, // If we missed any lints added to the session, then there's a bug somewhere // in the iteration code. - for (id, v) in tcx.sess.lints.borrow().iter() { - for &(lint, span, ref msg) in v.iter() { + for (id, v) in &*tcx.sess.lints.borrow() { + for &(lint, span, ref msg) in v { tcx.sess.span_bug(span, format!("unprocessed lint {} at {}: {}", lint.as_str(), tcx.map.node_to_string(*id), *msg).as_slice()) diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 7b71120ba64..a787369dc63 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -162,7 +162,7 @@ impl<'a> CrateReader<'a> { dump_crates(&self.sess.cstore); } - for &(ref name, kind) in self.sess.opts.libs.iter() { + for &(ref name, kind) in &self.sess.opts.libs { register_native_lib(self.sess, None, name.clone(), kind); } } @@ -235,7 +235,7 @@ impl<'a> CrateReader<'a> { None }) .collect::<Vec<&ast::Attribute>>(); - for m in link_args.iter() { + for m in &link_args { match m.value_str() { Some(linkarg) => self.sess.cstore.add_used_link_args(linkarg.get()), None => { /* fallthrough */ } @@ -250,7 +250,7 @@ impl<'a> CrateReader<'a> { None }) .collect::<Vec<&ast::Attribute>>(); - for m in link_args.iter() { + for m in &link_args { match m.meta_item_list() { Some(items) => { let kind = items.iter().find(|k| { @@ -330,6 +330,7 @@ impl<'a> CrateReader<'a> { if found { ret = Some(cnum); } + return } // Alright, so we've gotten this far which means that `data` has the diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index 1295970d667..619cfc1b52c 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -382,7 +382,7 @@ pub fn get_stability(cstore: &cstore::CStore, pub fn is_staged_api(cstore: &cstore::CStore, def: ast::DefId) -> bool { let cdata = cstore.get_crate_data(def.krate); let attrs = decoder::get_crate_attributes(cdata.data()); - for attr in attrs.iter() { + for attr in &attrs { if attr.name().get() == "staged_api" { match attr.node.value.node { ast::MetaWord(_) => return true, _ => (/*pass*/) } } diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 40242f52493..0a3e173b35e 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -113,7 +113,7 @@ impl CStore { pub fn iter_crate_data<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata), { - for (&k, v) in self.metas.borrow().iter() { + for (&k, v) in &*self.metas.borrow() { i(k, &**v); } } @@ -122,7 +122,7 @@ impl CStore { pub fn iter_crate_data_origins<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata, Option<CrateSource>), { - for (&k, v) in self.metas.borrow().iter() { + for (&k, v) in &*self.metas.borrow() { let origin = self.get_used_crate_source(k); origin.as_ref().map(|cs| { assert!(k == cs.cnum); }); i(k, &**v, origin); @@ -167,12 +167,12 @@ impl CStore { ordering: &mut Vec<ast::CrateNum>) { if ordering.contains(&cnum) { return } let meta = cstore.get_crate_data(cnum); - for (_, &dep) in meta.cnum_map.iter() { + for (_, &dep) in &meta.cnum_map { visit(cstore, dep, ordering); } ordering.push(cnum); }; - for (&num, _) in self.metas.borrow().iter() { + for (&num, _) in &*self.metas.borrow() { visit(self, num, &mut ordering); } ordering.reverse(); diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 94fe99ff07d..3a70490771e 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -1022,7 +1022,7 @@ pub fn get_methods_if_impl(intr: Rc<IdentInterner>, }); let mut impl_methods = Vec::new(); - for impl_method_id in impl_method_ids.iter() { + for impl_method_id in &impl_method_ids { let impl_method_doc = lookup_item(impl_method_id.node, cdata.data()); let family = item_family(impl_method_doc); match family { @@ -1189,7 +1189,7 @@ fn list_crate_attributes(md: rbml::Doc, hash: &Svh, try!(write!(out, "=Crate Attributes ({})=\n", *hash)); let r = get_attributes(md); - for attr in r.iter() { + for attr in &r { try!(write!(out, "{}\n", pprust::attribute_to_string(attr))); } @@ -1232,7 +1232,7 @@ pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> { fn list_crate_deps(data: &[u8], out: &mut old_io::Writer) -> old_io::IoResult<()> { try!(write!(out, "=External Dependencies=\n")); - for dep in get_crate_deps(data).iter() { + for dep in &get_crate_deps(data) { try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash)); } try!(write!(out, "\n")); diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 7ad91d4d71c..ccd524a2c03 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -288,7 +288,7 @@ fn encode_parent_item(rbml_w: &mut Encoder, id: DefId) { fn encode_struct_fields(rbml_w: &mut Encoder, fields: &[ty::field_ty], origin: DefId) { - for f in fields.iter() { + for f in fields { if f.name == special_idents::unnamed_field.name { rbml_w.start_tag(tag_item_unnamed_field); } else { @@ -316,7 +316,7 @@ fn encode_enum_variant_info(ecx: &EncodeContext, let mut i = 0; let vi = ty::enum_variants(ecx.tcx, DefId { krate: ast::LOCAL_CRATE, node: id }); - for variant in variants.iter() { + for variant in variants { let def_id = local_def(variant.node.id); index.push(entry { val: variant.node.id as i64, @@ -367,7 +367,7 @@ fn encode_path<PI: Iterator<Item=PathElem>>(rbml_w: &mut Encoder, path: PI) { let path = path.collect::<Vec<_>>(); rbml_w.start_tag(tag_path); rbml_w.wr_tagged_u32(tag_path_len, path.len() as u32); - for pe in path.iter() { + for pe in &path { let tag = match *pe { ast_map::PathMod(_) => tag_path_elem_mod, ast_map::PathName(_) => tag_path_elem_name @@ -402,8 +402,8 @@ fn encode_reexported_static_base_methods(ecx: &EncodeContext, let impl_items = ecx.tcx.impl_items.borrow(); match ecx.tcx.inherent_impls.borrow().get(&exp.def_id) { Some(implementations) => { - for base_impl_did in implementations.iter() { - for &method_did in (*impl_items)[*base_impl_did].iter() { + for base_impl_did in &**implementations { + for &method_did in &*(*impl_items)[*base_impl_did] { let impl_item = ty::impl_or_trait_item( ecx.tcx, method_did.def_id()); @@ -431,7 +431,7 @@ fn encode_reexported_static_trait_methods(ecx: &EncodeContext, -> bool { match ecx.tcx.trait_items_cache.borrow().get(&exp.def_id) { Some(trait_items) => { - for trait_item in trait_items.iter() { + for trait_item in &**trait_items { if let ty::MethodTraitItem(ref m) = *trait_item { encode_reexported_static_method(rbml_w, exp, @@ -517,9 +517,9 @@ fn encode_reexports(ecx: &EncodeContext, path: PathElems) { debug!("(encoding info for module) encoding reexports for {}", id); match ecx.reexports.get(&id) { - Some(ref exports) => { + Some(exports) => { debug!("(encoding info for module) found reexports for {}", id); - for exp in exports.iter() { + for exp in exports { debug!("(encoding info for module) reexport '{}' ({}/{}) for \ {}", exp.name, @@ -559,7 +559,7 @@ fn encode_info_for_mod(ecx: &EncodeContext, debug!("(encoding info for module) encoding info for module ID {}", id); // Encode info about all the module children. - for item in md.items.iter() { + for item in &md.items { rbml_w.start_tag(tag_mod_child); rbml_w.wr_str(&def_to_string(local_def(item.id))[]); rbml_w.end_tag(); @@ -665,9 +665,9 @@ fn encode_parent_sort(rbml_w: &mut Encoder, sort: char) { fn encode_provided_source(rbml_w: &mut Encoder, source_opt: Option<DefId>) { - for source in source_opt.iter() { + if let Some(source) = source_opt { rbml_w.start_tag(tag_item_method_provided_source); - let s = def_to_string(*source); + let s = def_to_string(source); rbml_w.writer.write_all(s.as_bytes()); rbml_w.end_tag(); } @@ -684,7 +684,7 @@ fn encode_info_for_struct(ecx: &EncodeContext, let mut index = Vec::new(); /* We encode both private and public fields -- need to include private fields to get the offsets right */ - for field in fields.iter() { + for field in fields { let nm = field.name; let id = field.id.node; @@ -783,7 +783,7 @@ fn encode_generics<'a, 'tcx>(rbml_w: &mut Encoder, rbml_w.wr_tagged_u64(tag_region_param_def_index, param.index as u64); - for &bound_region in param.bounds.iter() { + for &bound_region in ¶m.bounds { encode_region(ecx, rbml_w, bound_region); } @@ -911,7 +911,7 @@ fn encode_info_for_associated_type(ecx: &EncodeContext, fn encode_method_argument_names(rbml_w: &mut Encoder, decl: &ast::FnDecl) { rbml_w.start_tag(tag_method_argument_names); - for arg in decl.inputs.iter() { + for arg in &decl.inputs { rbml_w.start_tag(tag_method_argument_name); if let ast::PatIdent(_, ref path1, _) = arg.pat.node { let name = token::get_ident(path1.node); @@ -926,7 +926,7 @@ fn encode_repr_attrs(rbml_w: &mut Encoder, ecx: &EncodeContext, attrs: &[ast::Attribute]) { let mut repr_attrs = Vec::new(); - for attr in attrs.iter() { + for attr in attrs { repr_attrs.extend(attr::find_repr_attrs(ecx.tcx.sess.diagnostic(), attr).into_iter()); } @@ -962,7 +962,7 @@ fn encode_inherent_implementations(ecx: &EncodeContext, match ecx.tcx.inherent_impls.borrow().get(&def_id) { None => {} Some(implementations) => { - for &impl_def_id in implementations.iter() { + for &impl_def_id in &**implementations { rbml_w.start_tag(tag_items_data_item_inherent_impl); encode_def_id(rbml_w, impl_def_id); rbml_w.end_tag(); @@ -978,7 +978,7 @@ fn encode_extension_implementations(ecx: &EncodeContext, match ecx.tcx.trait_impls.borrow().get(&trait_def_id) { None => {} Some(implementations) => { - for &impl_def_id in implementations.borrow().iter() { + for &impl_def_id in &*implementations.borrow() { rbml_w.start_tag(tag_items_data_item_extension_impl); encode_def_id(rbml_w, impl_def_id); rbml_w.end_tag(); @@ -1091,7 +1091,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_path(rbml_w, path); // Encode all the items in this module. - for foreign_item in fm.items.iter() { + for foreign_item in &fm.items { rbml_w.start_tag(tag_mod_child); rbml_w.wr_str(&def_to_string(local_def(foreign_item.id))[]); rbml_w.end_tag(); @@ -1123,7 +1123,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_name(rbml_w, item.ident.name); encode_attributes(rbml_w, &item.attrs[]); encode_repr_attrs(rbml_w, ecx, &item.attrs[]); - for v in (*enum_definition).variants.iter() { + for v in &enum_definition.variants { encode_variant_id(rbml_w, local_def(v.node.id)); } encode_inlined_item(ecx, rbml_w, IIItemRef(item)); @@ -1216,7 +1216,7 @@ fn encode_info_for_item(ecx: &EncodeContext, } _ => {} } - for &item_def_id in items.iter() { + for &item_def_id in items { rbml_w.start_tag(tag_item_impl_item); match item_def_id { ty::MethodTraitItemId(item_def_id) => { @@ -1230,7 +1230,7 @@ fn encode_info_for_item(ecx: &EncodeContext, } rbml_w.end_tag(); } - for ast_trait_ref in opt_trait.iter() { + if let Some(ref ast_trait_ref) = *opt_trait { let trait_ref = ty::node_id_to_trait_ref( tcx, ast_trait_ref.ref_id); encode_trait_ref(rbml_w, ecx, &*trait_ref, tag_item_trait_ref); @@ -1314,7 +1314,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_attributes(rbml_w, &item.attrs[]); encode_visibility(rbml_w, vis); encode_stability(rbml_w, stab); - for &method_def_id in ty::trait_item_def_ids(tcx, def_id).iter() { + for &method_def_id in &*ty::trait_item_def_ids(tcx, def_id) { rbml_w.start_tag(tag_item_trait_item); match method_def_id { ty::MethodTraitItemId(method_def_id) => { @@ -1589,7 +1589,7 @@ fn encode_index<T, F>(rbml_w: &mut Encoder, index: Vec<entry<T>>, mut write_fn: T: Hash<SipHasher>, { let mut buckets: Vec<Vec<entry<T>>> = (0..256u16).map(|_| Vec::new()).collect(); - for elt in index.into_iter() { + for elt in index { let mut s = SipHasher::new(); elt.val.hash(&mut s); let h = s.finish() as uint; @@ -1599,10 +1599,10 @@ fn encode_index<T, F>(rbml_w: &mut Encoder, index: Vec<entry<T>>, mut write_fn: rbml_w.start_tag(tag_index); let mut bucket_locs = Vec::new(); rbml_w.start_tag(tag_index_buckets); - for bucket in buckets.iter() { + for bucket in &buckets { bucket_locs.push(rbml_w.writer.tell().unwrap()); rbml_w.start_tag(tag_index_buckets_bucket); - for elt in bucket.iter() { + for elt in bucket { rbml_w.start_tag(tag_index_buckets_bucket_elt); assert!(elt.pos < 0xffff_ffff); { @@ -1616,7 +1616,7 @@ fn encode_index<T, F>(rbml_w: &mut Encoder, index: Vec<entry<T>>, mut write_fn: } rbml_w.end_tag(); rbml_w.start_tag(tag_index_table); - for pos in bucket_locs.iter() { + for pos in &bucket_locs { assert!(*pos < 0xffff_ffff); let wr: &mut SeekableMemWriter = rbml_w.writer; wr.write_be_u32(*pos as u32); @@ -1660,7 +1660,7 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) { rbml_w.start_tag(tag_meta_item_name); rbml_w.writer.write_all(name.get().as_bytes()); rbml_w.end_tag(); - for inner_item in items.iter() { + for inner_item in items { encode_meta_item(rbml_w, &**inner_item); } rbml_w.end_tag(); @@ -1670,7 +1670,7 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) { fn encode_attributes(rbml_w: &mut Encoder, attrs: &[ast::Attribute]) { rbml_w.start_tag(tag_attributes); - for attr in attrs.iter() { + for attr in attrs { rbml_w.start_tag(tag_attribute); rbml_w.wr_tagged_u8(tag_attribute_is_sugared_doc, attr.node.is_sugared_doc as u8); encode_meta_item(rbml_w, &*attr.node.value); @@ -1694,7 +1694,7 @@ fn encode_paren_sugar(rbml_w: &mut Encoder, paren_sugar: bool) { fn encode_associated_type_names(rbml_w: &mut Encoder, names: &[ast::Name]) { rbml_w.start_tag(tag_associated_type_names); - for &name in names.iter() { + for &name in names { rbml_w.wr_tagged_str(tag_associated_type_name, token::get_name(name).get()); } rbml_w.end_tag(); @@ -1726,7 +1726,7 @@ fn encode_crate_deps(rbml_w: &mut Encoder, cstore: &cstore::CStore) { // Sanity-check the crate numbers let mut expected_cnum = 1; - for n in deps.iter() { + for n in &deps { assert_eq!(n.cnum, expected_cnum); expected_cnum += 1; } @@ -1740,7 +1740,7 @@ fn encode_crate_deps(rbml_w: &mut Encoder, cstore: &cstore::CStore) { // but is enough to get transitive crate dependencies working. rbml_w.start_tag(tag_crate_deps); let r = get_ordered_deps(cstore); - for dep in r.iter() { + for dep in &r { encode_crate_dep(rbml_w, (*dep).clone()); } rbml_w.end_tag(); @@ -1749,8 +1749,8 @@ fn encode_crate_deps(rbml_w: &mut Encoder, cstore: &cstore::CStore) { fn encode_lang_items(ecx: &EncodeContext, rbml_w: &mut Encoder) { rbml_w.start_tag(tag_lang_items); - for (i, def_id) in ecx.tcx.lang_items.items() { - for id in def_id.iter() { + for (i, &def_id) in ecx.tcx.lang_items.items() { + if let Some(id) = def_id { if id.krate == ast::LOCAL_CRATE { rbml_w.start_tag(tag_lang_items_item); @@ -1773,7 +1773,7 @@ fn encode_lang_items(ecx: &EncodeContext, rbml_w: &mut Encoder) { } } - for i in ecx.tcx.lang_items.missing.iter() { + for i in &ecx.tcx.lang_items.missing { rbml_w.wr_tagged_u32(tag_lang_items_missing, *i as u32); } @@ -1817,7 +1817,7 @@ fn encode_plugin_registrar_fn(ecx: &EncodeContext, rbml_w: &mut Encoder) { fn encode_macro_defs(rbml_w: &mut Encoder, krate: &ast::Crate) { rbml_w.start_tag(tag_macro_defs); - for def in krate.exported_macros.iter() { + for def in &krate.exported_macros { rbml_w.start_tag(tag_macro_def); encode_name(rbml_w, def.ident.name); @@ -1911,7 +1911,7 @@ fn encode_misc_info(ecx: &EncodeContext, rbml_w: &mut Encoder) { rbml_w.start_tag(tag_misc_info); rbml_w.start_tag(tag_misc_info_crate_items); - for item in krate.module.items.iter() { + for item in &krate.module.items { rbml_w.start_tag(tag_mod_child); rbml_w.wr_str(&def_to_string(local_def(item.id))[]); rbml_w.end_tag(); @@ -1935,7 +1935,7 @@ fn encode_misc_info(ecx: &EncodeContext, fn encode_reachable_extern_fns(ecx: &EncodeContext, rbml_w: &mut Encoder) { rbml_w.start_tag(tag_reachable_extern_fns); - for id in ecx.reachable.iter() { + for id in ecx.reachable { if let Some(ast_map::NodeItem(i)) = ecx.tcx.map.find(*id) { if let ast::ItemFn(_, _, abi, ref generics, _) = i.node { if abi != abi::Rust && !generics.is_type_parameterized() { @@ -2150,7 +2150,7 @@ fn encode_metadata_inner(wr: &mut SeekableMemWriter, stats.total_bytes = rbml_w.writer.tell().unwrap(); if tcx.sess.meta_stats() { - for e in rbml_w.writer.get_ref().iter() { + for e in rbml_w.writer.get_ref() { if *e == 0 { stats.zero_bytes += 1; } diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index 26046cfb43d..1b2d82e68c1 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -13,9 +13,9 @@ pub use self::FileMatch::*; use std::collections::HashSet; +use std::env; use std::old_io::fs::PathExtensions; use std::old_io::fs; -use std::os; use util::fs as myfs; use session::search_paths::{SearchPaths, PathKind}; @@ -66,7 +66,7 @@ impl<'a> FileSearch<'a> { // Try RUST_PATH if !found { let rustpath = rust_path(); - for path in rustpath.iter() { + for path in &rustpath { let tlib_path = make_rustpkg_lib_path( self.sysroot, path, self.triple); debug!("is {} in visited_dirs? {}", tlib_path.display(), @@ -194,7 +194,7 @@ pub fn get_or_default_sysroot() -> Path { }) } - match canonicalize(os::self_exe_name()) { + match canonicalize(env::current_exe().ok()) { Some(mut p) => { p.pop(); p.pop(); p } None => panic!("can't determine value for sysroot") } @@ -207,7 +207,7 @@ static PATH_ENTRY_SEPARATOR: &'static str = ":"; /// Returns RUST_PATH as a string, without default paths added pub fn get_rust_path() -> Option<String> { - os::getenv("RUST_PATH").map(|x| x.to_string()) + env::var_string("RUST_PATH").ok() } /// Returns the value of RUST_PATH, as a list @@ -224,7 +224,7 @@ pub fn rust_path() -> Vec<Path> { } None => Vec::new() }; - let mut cwd = os::getcwd().unwrap(); + let mut cwd = env::current_dir().unwrap(); // now add in default entries let cwd_dot_rust = cwd.join(".rust"); if !env_rust_path.contains(&cwd_dot_rust) { @@ -243,8 +243,7 @@ pub fn rust_path() -> Vec<Path> { } cwd.pop(); } - let h = os::homedir(); - for h in h.iter() { + if let Some(h) = env::home_dir() { let p = h.join(".rust"); if !env_rust_path.contains(&p) && p.exists() { env_rust_path.push(p); diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 09957f58bcc..2fb5a6b64a6 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -425,7 +425,7 @@ impl<'a> Context<'a> { // libraries corresponds to the crate id and hash criteria that this // search is being performed for. let mut libraries = Vec::new(); - for (_hash, (rlibs, dylibs)) in candidates.into_iter() { + for (_hash, (rlibs, dylibs)) in candidates { let mut metadata = None; let rlib = self.extract_one(rlibs, "rlib", &mut metadata); let dylib = self.extract_one(dylibs, "dylib", &mut metadata); @@ -452,7 +452,7 @@ impl<'a> Context<'a> { &format!("multiple matching crates for `{}`", self.crate_name)[]); self.sess.note("candidates:"); - for lib in libraries.iter() { + for lib in &libraries { match lib.dylib { Some((ref p, _)) => { self.sess.note(&format!("path: {}", @@ -501,7 +501,7 @@ impl<'a> Context<'a> { } } - for (lib, kind) in m.into_iter() { + for (lib, kind) in m { info!("{} reading metadata from: {}", flavor, lib.display()); let metadata = match get_metadata_section(self.target.options.is_like_osx, &lib) { @@ -610,7 +610,7 @@ impl<'a> Context<'a> { let mut rlibs = HashMap::new(); let mut dylibs = HashMap::new(); { - let mut locs = locs.iter().map(|l| Path::new(&l[])).filter(|loc| { + let locs = locs.iter().map(|l| Path::new(&l[])).filter(|loc| { if !loc.exists() { sess.err(&format!("extern location for {} does not exist: {}", self.crate_name, loc.display())[]); diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index ac6d2d0174c..4c0aefaf83d 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -249,7 +249,7 @@ fn parse_vec_per_param_space<'a, 'tcx, T, F>(st: &mut PState<'a, 'tcx>, F: FnMut(&mut PState<'a, 'tcx>) -> T, { let mut r = VecPerParamSpace::empty(); - for &space in subst::ParamSpace::all().iter() { + for &space in &subst::ParamSpace::all() { assert_eq!(next(st), '['); while peek(st) != ']' { r.push(space, f(st)); diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index 2dc334bfe95..f8081e2c309 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -97,7 +97,7 @@ pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'t } ty::ty_tup(ref ts) => { mywrite!(w, "T["); - for t in ts.iter() { enc_ty(w, cx, *t); } + for t in ts { enc_ty(w, cx, *t); } mywrite!(w, "]"); } ty::ty_uniq(typ) => { mywrite!(w, "~"); enc_ty(w, cx, typ); } @@ -206,9 +206,9 @@ fn enc_vec_per_param_space<'a, 'tcx, T, F>(w: &mut SeekableMemWriter, mut op: F) where F: FnMut(&mut SeekableMemWriter, &ctxt<'a, 'tcx>, &T), { - for &space in subst::ParamSpace::all().iter() { + for &space in &subst::ParamSpace::all() { mywrite!(w, "["); - for t in v.get_slice(space).iter() { + for t in v.get_slice(space) { op(w, cx, t); } mywrite!(w, "]"); @@ -337,7 +337,7 @@ pub fn enc_closure_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, fn enc_fn_sig<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, fsig: &ty::PolyFnSig<'tcx>) { mywrite!(w, "["); - for ty in fsig.0.inputs.iter() { + for ty in &fsig.0.inputs { enc_ty(w, cx, *ty); } mywrite!(w, "]"); @@ -357,7 +357,7 @@ fn enc_fn_sig<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, } pub fn enc_builtin_bounds(w: &mut SeekableMemWriter, _cx: &ctxt, bs: &ty::BuiltinBounds) { - for bound in bs.iter() { + for bound in bs { match bound { ty::BoundSend => mywrite!(w, "S"), ty::BoundSized => mywrite!(w, "Z"), @@ -383,17 +383,17 @@ pub fn enc_bounds<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, bs: &ty::ParamBounds<'tcx>) { enc_builtin_bounds(w, cx, &bs.builtin_bounds); - for &r in bs.region_bounds.iter() { + for &r in &bs.region_bounds { mywrite!(w, "R"); enc_region(w, cx, r); } - for tp in bs.trait_bounds.iter() { + for tp in &bs.trait_bounds { mywrite!(w, "I"); enc_trait_ref(w, cx, &*tp.0); } - for tp in bs.projection_bounds.iter() { + for tp in &bs.projection_bounds { mywrite!(w, "P"); enc_projection_predicate(w, cx, &tp.0); } diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 6d9b9c23504..4130195ae40 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -766,7 +766,7 @@ fn encode_vec_per_param_space<T, F>(rbml_w: &mut Encoder, mut f: F) where F: FnMut(&mut Encoder, &T), { - for &space in subst::ParamSpace::all().iter() { + for &space in &subst::ParamSpace::all() { rbml_w.emit_from_vec(v.get_slice(space), |rbml_w, n| Ok(f(rbml_w, n))).unwrap(); } @@ -1156,14 +1156,14 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, debug!("Encoding side tables for id {}", id); - for def in tcx.def_map.borrow().get(&id).iter() { + if let Some(def) = tcx.def_map.borrow().get(&id) { rbml_w.tag(c::tag_table_def, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| (*def).encode(rbml_w).unwrap()); }) } - for &ty in tcx.node_types.borrow().get(&id).iter() { + if let Some(ty) = tcx.node_types.borrow().get(&id) { rbml_w.tag(c::tag_table_node_type, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1172,7 +1172,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) } - for &item_substs in tcx.item_substs.borrow().get(&id).iter() { + if let Some(item_substs) = tcx.item_substs.borrow().get(&id) { rbml_w.tag(c::tag_table_item_subst, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1181,7 +1181,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) } - for &fv in tcx.freevars.borrow().get(&id).iter() { + if let Some(fv) = tcx.freevars.borrow().get(&id) { rbml_w.tag(c::tag_table_freevars, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1191,7 +1191,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) }); - for freevar in fv.iter() { + for freevar in fv { rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1209,7 +1209,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, } let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id }; - for &type_scheme in tcx.tcache.borrow().get(&lid).iter() { + if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) { rbml_w.tag(c::tag_table_tcache, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1218,7 +1218,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) } - for &type_param_def in tcx.ty_param_defs.borrow().get(&id).iter() { + if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) { rbml_w.tag(c::tag_table_param_defs, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1228,7 +1228,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, } let method_call = MethodCall::expr(id); - for &method in tcx.method_map.borrow().get(&method_call).iter() { + if let Some(method) = tcx.method_map.borrow().get(&method_call) { rbml_w.tag(c::tag_table_method_map, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1237,7 +1237,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) } - for &trait_ref in tcx.object_cast_map.borrow().get(&id).iter() { + if let Some(trait_ref) = tcx.object_cast_map.borrow().get(&id) { rbml_w.tag(c::tag_table_object_cast_map, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1246,11 +1246,11 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) } - for &adjustment in tcx.adjustments.borrow().get(&id).iter() { + if let Some(adjustment) = tcx.adjustments.borrow().get(&id) { match *adjustment { _ if ty::adjust_is_object(adjustment) => { let method_call = MethodCall::autoobject(id); - for &method in tcx.method_map.borrow().get(&method_call).iter() { + if let Some(method) = tcx.method_map.borrow().get(&method_call) { rbml_w.tag(c::tag_table_method_map, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1263,7 +1263,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, assert!(!ty::adjust_is_object(adjustment)); for autoderef in 0..adj.autoderefs { let method_call = MethodCall::autoderef(id, autoderef); - for &method in tcx.method_map.borrow().get(&method_call).iter() { + if let Some(method) = tcx.method_map.borrow().get(&method_call) { rbml_w.tag(c::tag_table_method_map, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1287,7 +1287,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) } - for &closure_type in tcx.closure_tys.borrow().get(&ast_util::local_def(id)).iter() { + if let Some(closure_type) = tcx.closure_tys.borrow().get(&ast_util::local_def(id)) { rbml_w.tag(c::tag_table_closure_tys, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { @@ -1296,11 +1296,11 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) } - for &&closure_kind in tcx.closure_kinds.borrow().get(&ast_util::local_def(id)).iter() { + if let Some(closure_kind) = tcx.closure_kinds.borrow().get(&ast_util::local_def(id)) { rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| { rbml_w.id(id); rbml_w.tag(c::tag_table_val, |rbml_w| { - encode_closure_kind(rbml_w, closure_kind) + encode_closure_kind(rbml_w, *closure_kind) }) }) } diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index 0a575a31ead..d39b94a202e 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -68,7 +68,7 @@ fn add_initial_dummy_node(g: &mut CFGGraph) -> CFGIndex { impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { fn block(&mut self, blk: &ast::Block, pred: CFGIndex) -> CFGIndex { let mut stmts_exit = pred; - for stmt in blk.stmts.iter() { + for stmt in &blk.stmts { stmts_exit = self.stmt(&**stmt, stmts_exit); } @@ -166,7 +166,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { self.pat(&*pats[0], pred) } else { let collect = self.add_dummy_node(&[]); - for pat in pats.iter() { + for pat in pats { let pat_exit = self.pat(&**pat, pred); self.add_contained_edge(pat_exit, collect); } @@ -325,7 +325,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { let expr_exit = self.add_node(expr.id, &[]); let mut cond_exit = discr_exit; - for arm in arms.iter() { + for arm in arms { cond_exit = self.add_dummy_node(&[cond_exit]); // 2 let pats_exit = self.pats_any(&arm.pats[], cond_exit); // 3 @@ -522,7 +522,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { assert!(!self.exit_map.contains_key(&id)); self.exit_map.insert(id, node); } - for &pred in preds.iter() { + for &pred in preds { self.add_contained_edge(pred, node); } node @@ -574,7 +574,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { Some(_) => { match self.tcx.def_map.borrow().get(&expr.id) { Some(&def::DefLabel(loop_id)) => { - for l in self.loop_scopes.iter() { + for l in &self.loop_scopes { if l.loop_id == loop_id { return *l; } diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index 202020a9033..925bd5b6395 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -46,7 +46,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> { } ast::ItemEnum(ref enum_definition, _) => { self.inside_const(|v| { - for var in enum_definition.variants.iter() { + for var in &enum_definition.variants { if let Some(ref ex) = var.node.disr_expr { v.visit_expr(&**ex); } @@ -137,7 +137,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) { } ast::ExprBlock(ref block) => { // Check all statements in the block - for stmt in block.stmts.iter() { + for stmt in &block.stmts { let block_span_err = |&: span| span_err!(v.tcx.sess, span, E0016, "blocks in constants are limited to items and \ diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index 6de517b2906..38084d1c2c0 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -77,7 +77,7 @@ impl<'a> fmt::Debug for Matrix<'a> { let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1; let br = repeat('+').take(total_width).collect::<String>(); try!(write!(f, "{}\n", br)); - for row in pretty_printed_matrix.into_iter() { + for row in pretty_printed_matrix { try!(write!(f, "+")); for (column, pat_str) in row.into_iter().enumerate() { try!(write!(f, " ")); @@ -157,7 +157,7 @@ fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) { visit::walk_expr(cx, ex); match ex.node { ast::ExprMatch(ref scrut, ref arms, source) => { - for arm in arms.iter() { + for arm in arms { // First, check legality of move bindings. check_legality_of_move_bindings(cx, arm.guard.is_some(), @@ -285,8 +285,8 @@ fn check_arms(cx: &MatchCheckCtxt, source: ast::MatchSource) { let mut seen = Matrix(vec![]); let mut printed_if_let_err = false; - for &(ref pats, guard) in arms.iter() { - for pat in pats.iter() { + for &(ref pats, guard) in arms { + for pat in pats { let v = vec![&**pat]; match is_useful(cx, &seen, &v[], LeaveOutWitness) { @@ -979,7 +979,7 @@ fn check_fn(cx: &mut MatchCheckCtxt, visit::walk_fn(cx, kind, decl, body, sp); - for input in decl.inputs.iter() { + for input in &decl.inputs { is_refutable(cx, &*input.pat, |pat| { span_err!(cx.tcx.sess, input.pat.span, E0006, "refutable pattern in function argument: `{}` not covered", @@ -1012,7 +1012,7 @@ fn check_legality_of_move_bindings(cx: &MatchCheckCtxt, let tcx = cx.tcx; let def_map = &tcx.def_map; let mut by_ref_span = None; - for pat in pats.iter() { + for pat in pats { pat_bindings(def_map, &**pat, |bm, _, span, _path| { match bm { ast::BindByRef(_) => { @@ -1039,7 +1039,7 @@ fn check_legality_of_move_bindings(cx: &MatchCheckCtxt, } }; - for pat in pats.iter() { + for pat in pats { walk_pat(&**pat, |p| { if pat_is_binding(def_map, &*p) { match p.node { diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index 00141903c7c..fa5d5227be5 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -104,7 +104,7 @@ fn lookup_variant_by_id<'a>(tcx: &'a ty::ctxt, -> Option<&'a Expr> { fn variant_expr<'a>(variants: &'a [P<ast::Variant>], id: ast::NodeId) -> Option<&'a Expr> { - for variant in variants.iter() { + for variant in variants { if variant.node.id == id { return variant.node.disr_expr.as_ref().map(|e| &**e); } diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 3e2e81077da..8f5906db589 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -399,7 +399,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let mut orig_kills = self.kills[start.. end].to_vec(); let mut changed = false; - for &node_id in edge.data.exiting_scopes.iter() { + for &node_id in &edge.data.exiting_scopes { let opt_cfg_idx = self.nodeid_to_index.get(&node_id).map(|&i|i); match opt_cfg_idx { Some(cfg_idx) => { @@ -501,7 +501,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { fn reset(&mut self, bits: &mut [uint]) { let e = if self.dfcx.oper.initial_value() {uint::MAX} else {0}; - for b in bits.iter_mut() { + for b in bits { *b = e; } } @@ -550,7 +550,7 @@ fn bits_to_string(words: &[uint]) -> String { // Note: this is a little endian printout of bytes. - for &word in words.iter() { + for &word in words { let mut v = word; for _ in 0..uint::BYTES { result.push(sep); diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index 3db931002d2..4478e327087 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -173,7 +173,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { } }; let fields = ty::lookup_struct_fields(self.tcx, id); - for pat in pats.iter() { + for pat in pats { let field_id = fields.iter() .find(|field| field.name == pat.node.ident.name).unwrap().id; self.live_symbols.insert(field_id.node); @@ -318,7 +318,7 @@ fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool { } let dead_code = lint::builtin::DEAD_CODE.name_lower(); - for attr in lint::gather_attrs(attrs).into_iter() { + for attr in lint::gather_attrs(attrs) { match attr { Ok((ref name, lint::Allow, _)) if name.get() == dead_code => return true, @@ -356,7 +356,7 @@ impl<'v> Visitor<'v> for LifeSeeder { self.worklist.extend(enum_def.variants.iter().map(|variant| variant.node.id)); } ast::ItemImpl(_, _, _, Some(ref _trait_ref), _, ref impl_items) => { - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref method) => { self.worklist.push(method.id); @@ -397,10 +397,10 @@ fn create_and_seed_worklist(tcx: &ty::ctxt, // depending on whether a crate is built as bin or lib, and we want // the warning to be consistent, we also seed the worklist with // exported symbols. - for id in exported_items.iter() { + for id in exported_items { worklist.push(*id); } - for id in reachable_symbols.iter() { + for id in reachable_symbols { worklist.push(*id); } @@ -499,8 +499,8 @@ impl<'a, 'tcx> DeadVisitor<'a, 'tcx> { match self.tcx.inherent_impls.borrow().get(&local_def(id)) { None => (), Some(impl_list) => { - for impl_did in impl_list.iter() { - for item_did in (*impl_items)[*impl_did].iter() { + for impl_did in &**impl_list { + for item_did in &(*impl_items)[*impl_did] { if self.live_symbols.contains(&item_did.def_id() .node) { return true; @@ -536,7 +536,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for DeadVisitor<'a, 'tcx> { } else { match item.node { ast::ItemEnum(ref enum_def, _) => { - for variant in enum_def.variants.iter() { + for variant in &enum_def.variants { if self.should_warn_about_variant(&variant.node) { self.warn_dead_code(variant.node.id, variant.span, variant.node.name, "variant"); diff --git a/src/librustc/middle/dependency_format.rs b/src/librustc/middle/dependency_format.rs index 16b7d6134c3..6d35a82d153 100644 --- a/src/librustc/middle/dependency_format.rs +++ b/src/librustc/middle/dependency_format.rs @@ -85,7 +85,7 @@ pub type Dependencies = FnvHashMap<config::CrateType, DependencyList>; pub fn calculate(tcx: &ty::ctxt) { let mut fmts = tcx.dependency_formats.borrow_mut(); - for &ty in tcx.sess.crate_types.borrow().iter() { + for &ty in &*tcx.sess.crate_types.borrow() { fmts.insert(ty, calculate_type(&tcx.sess, ty)); } tcx.sess.abort_if_errors(); @@ -148,7 +148,7 @@ fn calculate_type(sess: &session::Session, debug!("adding dylib: {}", data.name); add_library(sess, cnum, cstore::RequireDynamic, &mut formats); let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum); - for &(depnum, style) in deps.iter() { + for &(depnum, style) in &deps { debug!("adding {:?}: {}", style, sess.cstore.get_crate_data(depnum).name.clone()); add_library(sess, depnum, style, &mut formats); diff --git a/src/librustc/middle/entry.rs b/src/librustc/middle/entry.rs index 417e5336249..24073848edf 100644 --- a/src/librustc/middle/entry.rs +++ b/src/librustc/middle/entry.rs @@ -139,7 +139,7 @@ fn configure_main(this: &mut EntryContext) { but you have one or more functions named 'main' that are not \ defined at the crate level. Either move the definition or \ attach the `#[main]` attribute to override this behavior."); - for &(_, span) in this.non_main_fns.iter() { + for &(_, span) in &this.non_main_fns { this.session.span_note(span, "here is a function named 'main'"); } this.session.abort_if_errors(); diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 4a0bed57433..44a816eb2f8 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -342,7 +342,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { fn walk_arg_patterns(&mut self, decl: &ast::FnDecl, body: &ast::Block) { - for arg in decl.inputs.iter() { + for arg in &decl.inputs { let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id)); let fn_body_scope = region::CodeExtent::from_node_id(body.id); @@ -372,7 +372,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { } fn consume_exprs(&mut self, exprs: &Vec<P<ast::Expr>>) { - for expr in exprs.iter() { + for expr in exprs { self.consume_expr(&**expr); } } @@ -476,7 +476,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { ast::ExprIf(ref cond_expr, ref then_blk, ref opt_else_expr) => { self.consume_expr(&**cond_expr); self.walk_block(&**then_blk); - for else_expr in opt_else_expr.iter() { + if let Some(ref else_expr) = *opt_else_expr { self.consume_expr(&**else_expr); } } @@ -490,7 +490,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { self.borrow_expr(&**discr, ty::ReEmpty, ty::ImmBorrow, MatchDiscriminant); // treatment of the discriminant is handled while walking the arms. - for arm in arms.iter() { + for arm in arms { let mode = self.arm_move_mode(discr_cmt.clone(), arm); let mode = mode.match_mode(); self.walk_arm(discr_cmt.clone(), arm, mode); @@ -511,11 +511,11 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { } ast::ExprInlineAsm(ref ia) => { - for &(_, ref input) in ia.inputs.iter() { + for &(_, ref input) in &ia.inputs { self.consume_expr(&**input); } - for &(_, ref output, is_rw) in ia.outputs.iter() { + for &(_, ref output, is_rw) in &ia.outputs { self.mutate_expr(expr, &**output, if is_rw { WriteAndRead } else { JustWrite }); } @@ -572,7 +572,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { } ast::ExprRet(ref opt_expr) => { - for expr in opt_expr.iter() { + if let Some(ref expr) = *opt_expr { self.consume_expr(&**expr); } } @@ -715,11 +715,11 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { fn walk_block(&mut self, blk: &ast::Block) { debug!("walk_block(blk.id={})", blk.id); - for stmt in blk.stmts.iter() { + for stmt in &blk.stmts { self.walk_stmt(&**stmt); } - for tail_expr in blk.expr.iter() { + if let Some(ref tail_expr) = blk.expr { self.consume_expr(&**tail_expr); } } @@ -729,7 +729,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { fields: &Vec<ast::Field>, opt_with: &Option<P<ast::Expr>>) { // Consume the expressions supplying values for each field. - for field in fields.iter() { + for field in fields { self.consume_expr(&*field.expr); } @@ -762,7 +762,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { }; // Consume those fields of the with expression that are needed. - for with_field in with_fields.iter() { + for with_field in &with_fields { if !contains_field_named(with_field, fields) { let cmt_field = self.mc.cat_field(&*with_expr, with_cmt.clone(), @@ -908,7 +908,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { match pass_args { PassArgs::ByValue => { self.consume_expr(receiver); - for &arg in rhs.iter() { + for &arg in &rhs { self.consume_expr(arg); } @@ -926,7 +926,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { let r = ty::ReScope(region::CodeExtent::from_node_id(expr.id)); let bk = ty::ImmBorrow; - for &arg in rhs.iter() { + for &arg in &rhs { self.borrow_expr(arg, r, bk, OverloadedOperator); } return true; @@ -934,18 +934,18 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &ast::Arm) -> TrackMatchMode<Span> { let mut mode = Unknown; - for pat in arm.pats.iter() { + for pat in &arm.pats { self.determine_pat_move_mode(discr_cmt.clone(), &**pat, &mut mode); } mode } fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &ast::Arm, mode: MatchMode) { - for pat in arm.pats.iter() { + for pat in &arm.pats { self.walk_pat(discr_cmt.clone(), &**pat, mode); } - for guard in arm.guard.iter() { + if let Some(ref guard) = arm.guard { self.consume_expr(&**guard); } @@ -1195,7 +1195,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { debug!("walk_captures({})", closure_expr.repr(self.tcx())); ty::with_freevars(self.tcx(), closure_expr.id, |freevars| { - for freevar in freevars.iter() { + for freevar in freevars { let id_var = freevar.def.def_id().node; let upvar_id = ty::UpvarId { var_id: id_var, closure_expr_id: closure_expr.id }; diff --git a/src/librustc/middle/infer/combine.rs b/src/librustc/middle/infer/combine.rs index 8b29ef9b880..8cb2774f7df 100644 --- a/src/librustc/middle/infer/combine.rs +++ b/src/librustc/middle/infer/combine.rs @@ -116,7 +116,7 @@ pub trait Combine<'tcx> : Sized { { let mut substs = subst::Substs::empty(); - for &space in subst::ParamSpace::all().iter() { + for &space in &subst::ParamSpace::all() { let a_tps = a_subst.types.get_slice(space); let b_tps = b_subst.types.get_slice(space); let tps = try!(self.tps(space, a_tps, b_tps)); @@ -129,7 +129,7 @@ pub trait Combine<'tcx> : Sized { } (&NonerasedRegions(ref a), &NonerasedRegions(ref b)) => { - for &space in subst::ParamSpace::all().iter() { + for &space in &subst::ParamSpace::all() { let a_regions = a.get_slice(space); let b_regions = b.get_slice(space); @@ -139,7 +139,7 @@ pub trait Combine<'tcx> : Sized { variances.regions.get_slice(space) } None => { - for _ in a_regions.iter() { + for _ in a_regions { invariance.push(ty::Invariant); } &invariance[] diff --git a/src/librustc/middle/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs index f0174c5b0c6..17b62e463da 100644 --- a/src/librustc/middle/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -170,7 +170,7 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { errors: &Vec<RegionResolutionError<'tcx>>) { let p_errors = self.process_errors(errors); let errors = if p_errors.is_empty() { errors } else { &p_errors }; - for error in errors.iter() { + for error in errors { match error.clone() { ConcreteFailure(origin, sub, sup) => { self.report_concrete_failure(origin, sub, sup); @@ -222,7 +222,7 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { let mut trace_origins = Vec::new(); let mut same_regions = Vec::new(); let mut processed_errors = Vec::new(); - for error in errors.iter() { + for error in errors { match error.clone() { ConcreteFailure(origin, sub, sup) => { debug!("processing ConcreteFailure"); @@ -257,7 +257,7 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { } if !same_regions.is_empty() { let common_scope_id = same_regions[0].scope_id; - for sr in same_regions.iter() { + for sr in &same_regions { // Since ProcessedErrors is used to reconstruct the function // declaration, we want to make sure that they are, in fact, // from the same scope @@ -335,7 +335,7 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { same_frs: &FreeRegionsFromSameFn) { let scope_id = same_frs.scope_id; let (sub_fr, sup_fr) = (same_frs.sub_fr, same_frs.sup_fr); - for sr in same_regions.iter_mut() { + for sr in &mut *same_regions { if sr.contains(&sup_fr.bound_region) && scope_id == sr.scope_id { sr.push(sub_fr.bound_region); @@ -796,11 +796,11 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { var_origins: &[RegionVariableOrigin], trace_origins: &[(TypeTrace<'tcx>, ty::type_err<'tcx>)], same_regions: &[SameRegions]) { - for vo in var_origins.iter() { + for vo in var_origins { self.report_inference_failure(vo.clone()); } self.give_suggestion(same_regions); - for &(ref trace, terr) in trace_origins.iter() { + for &(ref trace, terr) in trace_origins { self.report_type_error(trace.clone(), &terr); } } @@ -916,7 +916,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { let mut ty_params = self.generics.ty_params.clone(); let where_clause = self.generics.where_clause.clone(); let mut kept_lifetimes = HashSet::new(); - for sr in self.same_regions.iter() { + for sr in self.same_regions { self.cur_anon.set(0); self.offset_cur_anon(); let (anon_nums, region_names) = @@ -958,7 +958,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { // vector of string and then sort them. However, it makes the // choice of lifetime name deterministic and thus easier to test. let mut names = Vec::new(); - for rn in region_names.iter() { + for rn in region_names { let lt_name = token::get_name(*rn).get().to_string(); names.push(lt_name); } @@ -973,7 +973,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { -> (HashSet<u32>, HashSet<ast::Name>) { let mut anon_nums = HashSet::new(); let mut region_names = HashSet::new(); - for br in same_regions.regions.iter() { + for br in &same_regions.regions { match *br { ty::BrAnon(i) => { anon_nums.insert(i); @@ -989,8 +989,8 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { fn extract_all_region_names(&self) -> HashSet<ast::Name> { let mut all_region_names = HashSet::new(); - for sr in self.same_regions.iter() { - for br in sr.regions.iter() { + for sr in self.same_regions { + for br in &sr.regions { match *br { ty::BrNamed(_, name) => { all_region_names.insert(name); @@ -1123,11 +1123,11 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { where_clause: ast::WhereClause) -> ast::Generics { let mut lifetimes = Vec::new(); - for lt in add.iter() { + for lt in add { lifetimes.push(ast::LifetimeDef { lifetime: *lt, bounds: Vec::new() }); } - for lt in generics.lifetimes.iter() { + for lt in &generics.lifetimes { if keep.contains(<.lifetime.name) || !remove.contains(<.lifetime.name) { lifetimes.push((*lt).clone()); @@ -1147,7 +1147,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { region_names: &HashSet<ast::Name>) -> Vec<ast::Arg> { let mut new_inputs = Vec::new(); - for arg in inputs.iter() { + for arg in inputs { let new_ty = self.rebuild_arg_ty_or_output(&*arg.ty, lifetime, anon_nums, region_names); let possibly_new_arg = ast::Arg { @@ -1729,7 +1729,7 @@ struct LifeGiver { impl LifeGiver { fn with_taken(taken: &[ast::LifetimeDef]) -> LifeGiver { let mut taken_ = HashSet::new(); - for lt in taken.iter() { + for lt in taken { let lt_name = token::get_name(lt.lifetime.name).get().to_string(); taken_.insert(lt_name); } diff --git a/src/librustc/middle/infer/higher_ranked/mod.rs b/src/librustc/middle/infer/higher_ranked/mod.rs index 0df84323ae5..e4eecd919c8 100644 --- a/src/librustc/middle/infer/higher_ranked/mod.rs +++ b/src/librustc/middle/infer/higher_ranked/mod.rs @@ -176,7 +176,7 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C // in both A and B. Replace the variable with the "first" // bound region from A that we find it to be associated // with. - for (a_br, a_r) in a_map.iter() { + for (a_br, a_r) in a_map { if tainted.iter().any(|x| x == a_r) { debug!("generalize_region(r0={:?}): \ replacing with {:?}, tainted={:?}", @@ -258,7 +258,7 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C let mut a_r = None; let mut b_r = None; let mut only_new_vars = true; - for r in tainted.iter() { + for r in &tainted { if is_var_in_set(a_vars, *r) { if a_r.is_some() { return fresh_bound_variable(infcx, debruijn); @@ -315,7 +315,7 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C a_map: &FnvHashMap<ty::BoundRegion, ty::Region>, r: ty::Region) -> ty::Region { - for (a_br, a_r) in a_map.iter() { + for (a_br, a_r) in a_map { if *a_r == r { return ty::ReLateBound(ty::DebruijnIndex::new(1), *a_br); } @@ -497,9 +497,9 @@ pub fn leak_check<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, skol_map.repr(infcx.tcx)); let new_vars = infcx.region_vars_confined_to_snapshot(snapshot); - for (&skol_br, &skol) in skol_map.iter() { + for (&skol_br, &skol) in skol_map { let tainted = infcx.tainted_regions(snapshot, skol); - for &tainted_region in tainted.iter() { + for &tainted_region in &tainted { // Each skolemized should only be relatable to itself // or new variables: match tainted_region { diff --git a/src/librustc/middle/infer/mod.rs b/src/librustc/middle/infer/mod.rs index 1665966a5e5..f8dae3e92da 100644 --- a/src/librustc/middle/infer/mod.rs +++ b/src/librustc/middle/infer/mod.rs @@ -998,8 +998,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { mk_msg(resolved_expected.map(|t| self.ty_to_string(t)), actual_ty), error_str)[]); - for err in err.iter() { - ty::note_and_explain_type_err(self.tcx, *err) + if let Some(err) = err { + ty::note_and_explain_type_err(self.tcx, err) } } } diff --git a/src/librustc/middle/infer/region_inference/graphviz.rs b/src/librustc/middle/infer/region_inference/graphviz.rs index 460687629e7..87ea5436dab 100644 --- a/src/librustc/middle/infer/region_inference/graphviz.rs +++ b/src/librustc/middle/infer/region_inference/graphviz.rs @@ -27,7 +27,7 @@ use util::ppaux::Repr; use std::collections::hash_map::Entry::Vacant; use std::old_io::{self, File}; -use std::os; +use std::env; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use syntax::ast; @@ -59,13 +59,13 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a, } let requested_node : Option<ast::NodeId> = - os::getenv("RUST_REGION_GRAPH_NODE").and_then(|s| s.parse().ok()); + env::var_string("RUST_REGION_GRAPH_NODE").ok().and_then(|s| s.parse().ok()); if requested_node.is_some() && requested_node != Some(subject_node) { return; } - let requested_output = os::getenv("RUST_REGION_GRAPH"); + let requested_output = env::var_string("RUST_REGION_GRAPH").ok(); debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); diff --git a/src/librustc/middle/infer/region_inference/mod.rs b/src/librustc/middle/infer/region_inference/mod.rs index 8952452cb4b..919ea0a2520 100644 --- a/src/librustc/middle/infer/region_inference/mod.rs +++ b/src/librustc/middle/infer/region_inference/mod.rs @@ -667,7 +667,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { a, b); } VerifyGenericBound(_, _, a, ref bs) => { - for &b in bs.iter() { + for &b in bs { consider_adding_bidirectional_edges( &mut result_set, r, a, b); @@ -1200,7 +1200,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { errors: &mut Vec<RegionResolutionError<'tcx>>) { let mut reg_reg_dups = FnvHashSet(); - for verify in self.verifys.borrow().iter() { + for verify in &*self.verifys.borrow() { match *verify { VerifyRegSubReg(ref origin, sub, sup) => { if self.is_subregion_of(sub, sup) { @@ -1333,7 +1333,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } let dummy_idx = graph.add_node(()); - for (constraint, _) in constraints.iter() { + for (constraint, _) in &*constraints { match *constraint { ConstrainVarSubVar(a_id, b_id) => { graph.add_edge(NodeIndex(a_id.index as uint), @@ -1393,8 +1393,8 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { lower_bounds.sort_by(|a, b| { free_regions_first(a, b) }); upper_bounds.sort_by(|a, b| { free_regions_first(a, b) }); - for lower_bound in lower_bounds.iter() { - for upper_bound in upper_bounds.iter() { + for lower_bound in &lower_bounds { + for upper_bound in &upper_bounds { if !self.is_subregion_of(lower_bound.region, upper_bound.region) { errors.push(SubSupConflict( @@ -1435,8 +1435,8 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { return; } - for upper_bound_1 in upper_bounds.iter() { - for upper_bound_2 in upper_bounds.iter() { + for upper_bound_1 in &upper_bounds { + for upper_bound_2 in &upper_bounds { match self.glb_concrete_regions(upper_bound_1.region, upper_bound_2.region) { Ok(_) => {} @@ -1554,7 +1554,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { changed = false; iteration += 1; debug!("---- {} Iteration {}{}", "#", tag, iteration); - for (constraint, _) in self.constraints.borrow().iter() { + for (constraint, _) in &*self.constraints.borrow() { let edge_changed = body(constraint); if edge_changed { debug!("Updated due to constraint {}", diff --git a/src/librustc/middle/infer/type_variable.rs b/src/librustc/middle/infer/type_variable.rs index 65061a29b78..9b8a4a84412 100644 --- a/src/librustc/middle/infer/type_variable.rs +++ b/src/librustc/middle/infer/type_variable.rs @@ -105,7 +105,7 @@ impl<'tcx> TypeVariableTable<'tcx> { already instantiated") }; - for &(dir, vid) in relations.iter() { + for &(dir, vid) in &relations { stack.push((ty, dir, vid)); } @@ -165,7 +165,7 @@ impl<'tcx> TypeVariableTable<'tcx> { let mut escaping_types = Vec::new(); let actions_since_snapshot = self.values.actions_since_snapshot(&s.snapshot); debug!("actions_since_snapshot.len() = {}", actions_since_snapshot.len()); - for action in actions_since_snapshot.iter() { + for action in actions_since_snapshot { match *action { sv::UndoLog::NewElem(index) => { // if any new variables were created during the diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 29a615f2b40..d9b90c1935a 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -120,7 +120,7 @@ impl LanguageItems { (self.fn_once_trait(), ty::FnOnceClosureKind), ]; - for &(opt_def_id, kind) in def_id_kinds.iter() { + for &(opt_def_id, kind) in &def_id_kinds { if Some(id) == opt_def_id { return Some(kind); } @@ -217,7 +217,7 @@ impl<'a> LanguageItemCollector<'a> { } pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> { - for attribute in attrs.iter() { + for attribute in attrs { match attribute.value_str() { Some(ref value) if attribute.check_name("lang") => { return Some(value.clone()); diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index cb0157fed87..e40e04bdee8 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -378,7 +378,7 @@ fn visit_fn(ir: &mut IrMaps, debug!("creating fn_maps: {:?}", &fn_maps as *const IrMaps); - for arg in decl.inputs.iter() { + for arg in &decl.inputs { pat_util::pat_bindings(&ir.tcx.def_map, &*arg.pat, |_bm, arg_id, _x, path1| { @@ -427,7 +427,7 @@ fn visit_local(ir: &mut IrMaps, local: &ast::Local) { } fn visit_arm(ir: &mut IrMaps, arm: &ast::Arm) { - for pat in arm.pats.iter() { + for pat in &arm.pats { pat_util::pat_bindings(&ir.tcx.def_map, &**pat, |bm, p_id, sp, path1| { debug!("adding local variable {} from match with bm {:?}", p_id, bm); @@ -464,7 +464,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) { // construction site. let mut call_caps = Vec::new(); ty::with_freevars(ir.tcx, expr.id, |freevars| { - for fv in freevars.iter() { + for fv in freevars { if let DefLocal(rv) = fv.def { let fv_ln = ir.add_live_node(FreeVarNode(fv.span)); call_caps.push(CaptureInfo {ln: fv_ln, @@ -1049,7 +1049,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let ln = self.live_node(expr.id, expr.span); self.init_empty(ln, succ); let mut first_merge = true; - for arm in arms.iter() { + for arm in arms { let body_succ = self.propagate_through_expr(&*arm.body, succ); let guard_succ = @@ -1445,12 +1445,12 @@ fn check_expr(this: &mut Liveness, expr: &Expr) { } ast::ExprInlineAsm(ref ia) => { - for &(_, ref input) in ia.inputs.iter() { + for &(_, ref input) in &ia.inputs { this.visit_expr(&**input); } // Output operands must be lvalues - for &(_, ref out, _) in ia.outputs.iter() { + for &(_, ref out, _) in &ia.outputs { this.check_lvalue(&**out); this.visit_expr(&**out); } @@ -1590,7 +1590,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } fn warn_about_unused_args(&self, decl: &ast::FnDecl, entry_ln: LiveNode) { - for arg in decl.inputs.iter() { + for arg in &decl.inputs { pat_util::pat_bindings(&self.ir.tcx.def_map, &*arg.pat, |_bm, p_id, sp, path1| { @@ -1620,7 +1620,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { -> bool { if !self.used_on_entry(ln, var) { let r = self.should_warn(var); - for name in r.iter() { + if let Some(name) = r { // annoying: for parameters in funcs like `fn(x: int) // {ret}`, there is only one node, so asking about @@ -1634,10 +1634,10 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { if is_assigned { self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLES, id, sp, format!("variable `{}` is assigned to, but never used", - *name)); + name)); } else { self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLES, id, sp, - format!("unused variable: `{}`", *name)); + format!("unused variable: `{}`", name)); } } true @@ -1653,9 +1653,9 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { var: Variable) { if self.live_on_exit(ln, var).is_none() { let r = self.should_warn(var); - for name in r.iter() { + if let Some(name) = r { self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_ASSIGNMENTS, id, sp, - format!("value assigned to `{}` is never read", *name)); + format!("value assigned to `{}` is never read", name)); } } } diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 93daaa72843..1ae483be269 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -1208,7 +1208,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { } } Some(&def::DefConst(..)) => { - for subpat in subpats.iter() { + for subpat in subpats { try!(self.cat_pattern_(cmt.clone(), &**subpat, op)); } } @@ -1230,7 +1230,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { ast::PatStruct(_, ref field_pats, _) => { // {f1: p1, ..., fN: pN} - for fp in field_pats.iter() { + for fp in field_pats { let field_ty = try!(self.pat_ty(&*fp.node.pat)); // see (*2) let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.ident.name, field_ty); try!(self.cat_pattern_(cmt_field, &*fp.node.pat, op)); @@ -1259,15 +1259,15 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { ast::PatVec(ref before, ref slice, ref after) => { let elt_cmt = try!(self.cat_index(pat, try!(self.deref_vec(pat, cmt)))); - for before_pat in before.iter() { + for before_pat in before { try!(self.cat_pattern_(elt_cmt.clone(), &**before_pat, op)); } - for slice_pat in slice.iter() { + if let Some(ref slice_pat) = *slice { let slice_ty = try!(self.pat_ty(&**slice_pat)); let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty); try!(self.cat_pattern_(slice_cmt, &**slice_pat, op)); } - for after_pat in after.iter() { + for after_pat in after { try!(self.cat_pattern_(elt_cmt.clone(), &**after_pat, op)); } } diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index b93cde4bf64..0af226de251 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -353,7 +353,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { // this properly would result in the necessity of computing *type* // reachability, which might result in a compile time loss. fn mark_destructors_reachable(&mut self) { - for (_, destructor_def_id) in self.tcx.destructor_for_type.borrow().iter() { + for (_, destructor_def_id) in &*self.tcx.destructor_for_type.borrow() { if destructor_def_id.krate == ast::LOCAL_CRATE { self.reachable_symbols.insert(destructor_def_id.node); } @@ -371,7 +371,7 @@ pub fn find_reachable(tcx: &ty::ctxt, // other crates link to us, they're going to expect to be able to // use the lang items, so we need to be sure to mark them as // exported. - for id in exported_items.iter() { + for id in exported_items { reachable_context.worklist.push(*id); } for (_, item) in tcx.lang_items.items() { diff --git a/src/librustc/middle/recursion_limit.rs b/src/librustc/middle/recursion_limit.rs index da83833fba3..7dcd358165c 100644 --- a/src/librustc/middle/recursion_limit.rs +++ b/src/librustc/middle/recursion_limit.rs @@ -20,7 +20,7 @@ use syntax::ast; use syntax::attr::AttrMetaMethods; pub fn update_recursion_limit(sess: &Session, krate: &ast::Crate) { - for attr in krate.attrs.iter() { + for attr in &krate.attrs { if !attr.check_name("recursion_limit") { continue; } diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 3f8b7e5a7b3..87d386d94c9 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -888,14 +888,14 @@ fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) { record_rvalue_scope(visitor, &**subexpr, blk_id); } ast::ExprStruct(_, ref fields, _) => { - for field in fields.iter() { + for field in fields { record_rvalue_scope_if_borrow_expr( visitor, &*field.expr, blk_id); } } ast::ExprVec(ref subexprs) | ast::ExprTup(ref subexprs) => { - for subexpr in subexprs.iter() { + for subexpr in subexprs { record_rvalue_scope_if_borrow_expr( visitor, &**subexpr, blk_id); } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 9433f7b0a70..365355c4a2a 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -187,14 +187,14 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> { } fn visit_generics(&mut self, generics: &ast::Generics) { - for ty_param in generics.ty_params.iter() { + for ty_param in &*generics.ty_params { visit::walk_ty_param_bounds_helper(self, &ty_param.bounds); match ty_param.default { Some(ref ty) => self.visit_ty(&**ty), None => {} } } - for predicate in generics.where_clause.predicates.iter() { + for predicate in &generics.where_clause.predicates { match predicate { &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ ref bounded_ty, ref bounds, @@ -207,7 +207,7 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> { .. }) => { self.visit_lifetime_ref(lifetime); - for bound in bounds.iter() { + for bound in bounds { self.visit_lifetime_ref(bound); } } @@ -229,7 +229,7 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> { self.with(LateScope(&trait_ref.bound_lifetimes, self.scope), |old_scope, this| { this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes); - for lifetime in trait_ref.bound_lifetimes.iter() { + for lifetime in &trait_ref.bound_lifetimes { this.visit_lifetime_def(lifetime); } this.visit_trait_ref(&trait_ref.trait_ref) @@ -408,7 +408,7 @@ impl<'a> LifetimeContext<'a> { let lifetime_i = &lifetimes[i]; let special_idents = [special_idents::static_lifetime]; - for lifetime in lifetimes.iter() { + for lifetime in lifetimes { if special_idents.iter().any(|&i| i.name == lifetime.lifetime.name) { span_err!(self.sess, lifetime.lifetime.span, E0262, "illegal lifetime parameter name: `{}`", @@ -431,7 +431,7 @@ impl<'a> LifetimeContext<'a> { // It is a soft error to shadow a lifetime within a parent scope. self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime); - for bound in lifetime_i.bounds.iter() { + for bound in &lifetime_i.bounds { self.resolve_lifetime_ref(bound); } } @@ -535,10 +535,10 @@ fn early_bound_lifetime_names(generics: &ast::Generics) -> Vec<ast::Name> { let mut collector = FreeLifetimeCollector { early_bound: &mut early_bound, late_bound: &mut late_bound }; - for ty_param in generics.ty_params.iter() { + for ty_param in &*generics.ty_params { visit::walk_ty_param_bounds_helper(&mut collector, &ty_param.bounds); } - for predicate in generics.where_clause.predicates.iter() { + for predicate in &generics.where_clause.predicates { match predicate { &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bounds, ref bounded_ty, @@ -551,7 +551,7 @@ fn early_bound_lifetime_names(generics: &ast::Generics) -> Vec<ast::Name> { ..}) => { collector.visit_lifetime_ref(lifetime); - for bound in bounds.iter() { + for bound in bounds { collector.visit_lifetime_ref(bound); } } @@ -562,11 +562,11 @@ fn early_bound_lifetime_names(generics: &ast::Generics) -> Vec<ast::Name> { // Any lifetime that either has a bound or is referenced by a // bound is early. - for lifetime_def in generics.lifetimes.iter() { + for lifetime_def in &generics.lifetimes { if !lifetime_def.bounds.is_empty() { shuffle(&mut early_bound, &mut late_bound, lifetime_def.lifetime.name); - for bound in lifetime_def.bounds.iter() { + for bound in &lifetime_def.bounds { shuffle(&mut early_bound, &mut late_bound, bound.name); } diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index 7b5af0ab1aa..5028a1322ca 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -148,7 +148,7 @@ impl Index { /// Construct the stability index for a crate being compiled. pub fn build(sess: &Session, krate: &Crate) -> Index { let mut staged_api = false; - for attr in krate.attrs.iter() { + for attr in &krate.attrs { if attr.name().get() == "staged_api" { match attr.node.value.node { ast::MetaWord(_) => { @@ -273,7 +273,7 @@ pub fn check_item(tcx: &ty::ctxt, item: &ast::Item, maybe_do_stability_check(tcx, id, item.span, cb); } ast::ItemTrait(_, _, ref supertraits, _) => { - for t in supertraits.iter() { + for t in &**supertraits { if let ast::TraitTyParamBound(ref t, _) = *t { let id = ty::trait_ref_to_def_id(tcx, &t.trait_ref); maybe_do_stability_check(tcx, id, t.trait_ref.path.span, cb); @@ -410,11 +410,11 @@ pub fn check_unused_features(sess: &Session, let mut active_lib_features: FnvHashMap<InternedString, Span> = lib_features.clone().into_iter().collect(); - for used_feature in used_lib_features.iter() { + for used_feature in used_lib_features { active_lib_features.remove(used_feature); } - for (_, &span) in active_lib_features.iter() { + for (_, &span) in &active_lib_features { sess.add_lint(lint::builtin::UNUSED_FEATURES, ast::CRATE_NODE_ID, span, diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index cbf65080a86..eb6bc4c3835 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -241,7 +241,7 @@ pub struct SeparateVecsPerParamSpace<T> { impl<T: fmt::Debug> fmt::Debug for VecPerParamSpace<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "VecPerParamSpace {{")); - for space in ParamSpace::all().iter() { + for space in &ParamSpace::all() { try!(write!(fmt, "{:?}: {:?}, ", *space, self.get_slice(*space))); } try!(write!(fmt, "}}")); @@ -317,7 +317,7 @@ impl<T> VecPerParamSpace<T> { /// /// Unlike the `extend` method in `Vec`, this should not be assumed /// to be a cheap operation (even when amortized over many calls). - pub fn extend<I:Iterator<Item=T>>(&mut self, space: ParamSpace, mut values: I) { + pub fn extend<I:Iterator<Item=T>>(&mut self, space: ParamSpace, values: I) { // This could be made more efficient, obviously. for item in values { self.push(space, item); @@ -352,7 +352,7 @@ impl<T> VecPerParamSpace<T> { pub fn replace(&mut self, space: ParamSpace, elems: Vec<T>) { // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n). self.truncate(space, 0); - for t in elems.into_iter() { + for t in elems { self.push(space, t); } } diff --git a/src/librustc/middle/traits/doc.rs b/src/librustc/middle/traits/doc.rs index 4a01e964fd2..8ce4e38896e 100644 --- a/src/librustc/middle/traits/doc.rs +++ b/src/librustc/middle/traits/doc.rs @@ -35,7 +35,7 @@ provide an impl. To see what I mean, consider the body of `clone_slice`: fn clone_slice<T:Clone>(x: &[T]) -> Vec<T> { let mut v = Vec::new(); - for e in x.iter() { + for e in &x { v.push((*e).clone()); // (*) } } diff --git a/src/librustc/middle/traits/error_reporting.rs b/src/librustc/middle/traits/error_reporting.rs index 5e7168b6735..b8886fa65ba 100644 --- a/src/librustc/middle/traits/error_reporting.rs +++ b/src/librustc/middle/traits/error_reporting.rs @@ -28,7 +28,7 @@ use util::ppaux::{Repr, UserString}; pub fn report_fulfillment_errors<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, errors: &Vec<FulfillmentError<'tcx>>) { - for error in errors.iter() { + for error in errors { report_fulfillment_error(infcx, error); } } @@ -68,7 +68,7 @@ fn report_on_unimplemented<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, span: Span) -> Option<String> { let def_id = trait_ref.def_id; let mut report = None; - for item in ty::get_attrs(infcx.tcx, def_id).iter() { + for item in &*ty::get_attrs(infcx.tcx, def_id) { if item.check_name("rustc_on_unimplemented") { let err_sp = if item.meta().span == DUMMY_SP { span diff --git a/src/librustc/middle/traits/fulfill.rs b/src/librustc/middle/traits/fulfill.rs index ed058280483..8adcd256cce 100644 --- a/src/librustc/middle/traits/fulfill.rs +++ b/src/librustc/middle/traits/fulfill.rs @@ -125,7 +125,7 @@ impl<'tcx> FulfillmentContext<'tcx> { let mut selcx = SelectionContext::new(infcx, typer); let normalized = project::normalize_projection_type(&mut selcx, projection_ty, cause, 0); - for obligation in normalized.obligations.into_iter() { + for obligation in normalized.obligations { self.register_predicate_obligation(infcx, obligation); } @@ -289,7 +289,7 @@ impl<'tcx> FulfillmentContext<'tcx> { // Now go through all the successful ones, // registering any nested obligations for the future. - for new_obligation in new_obligations.into_iter() { + for new_obligation in new_obligations { self.register_predicate_obligation(selcx.infcx(), new_obligation); } } diff --git a/src/librustc/middle/traits/mod.rs b/src/librustc/middle/traits/mod.rs index 94da688181e..f69bf31626f 100644 --- a/src/librustc/middle/traits/mod.rs +++ b/src/librustc/middle/traits/mod.rs @@ -438,7 +438,7 @@ pub fn normalize_param_env<'a,'tcx>(param_env: &ty::ParameterEnvironment<'a,'tcx let mut fulfill_cx = FulfillmentContext::new(); let Normalized { value: predicates, obligations } = project::normalize(selcx, cause, ¶m_env.caller_bounds); - for obligation in obligations.into_iter() { + for obligation in obligations { fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation); } try!(fulfill_cx.select_all_or_error(selcx.infcx(), param_env)); diff --git a/src/librustc/middle/traits/object_safety.rs b/src/librustc/middle/traits/object_safety.rs index 530190ddfc1..c88e58266a0 100644 --- a/src/librustc/middle/traits/object_safety.rs +++ b/src/librustc/middle/traits/object_safety.rs @@ -176,7 +176,7 @@ fn object_safety_violations_for_method<'tcx>(tcx: &ty::ctxt<'tcx>, // The `Self` type is erased, so it should not appear in list of // arguments or return type apart from the receiver. let ref sig = method.fty.sig; - for &input_ty in sig.0.inputs[1..].iter() { + for &input_ty in &sig.0.inputs[1..] { if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) { return Some(MethodViolationCode::ReferencesSelf); } diff --git a/src/librustc/middle/traits/project.rs b/src/librustc/middle/traits/project.rs index ce66f4d5b35..3ede6bbb965 100644 --- a/src/librustc/middle/traits/project.rs +++ b/src/librustc/middle/traits/project.rs @@ -802,7 +802,7 @@ fn confirm_impl_candidate<'cx,'tcx>( let impl_items = &impl_items_map[impl_vtable.impl_def_id]; let mut impl_ty = None; - for impl_item in impl_items.iter() { + for impl_item in impl_items { let assoc_type = match impl_or_trait_items_map[impl_item.def_id()] { ty::TypeTraitItem(ref assoc_type) => assoc_type.clone(), ty::MethodTraitItem(..) => { continue; } diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 106c07baaa7..000572cdd40 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -295,7 +295,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn evaluate_predicates_recursively<'a,'o,I>(&mut self, stack: Option<&TraitObligationStack<'o, 'tcx>>, - mut predicates: I) + predicates: I) -> EvaluationResult<'tcx> where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a { @@ -1089,7 +1089,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { debug!("assemble_candidates_from_impls(self_ty={})", self_ty.repr(self.tcx())); let all_impls = self.all_impls(obligation.predicate.def_id()); - for &impl_def_id in all_impls.iter() { + for &impl_def_id in &all_impls { self.infcx.probe(|snapshot| { let (skol_obligation_trait_pred, skol_map) = self.infcx().skolemize_late_bound_regions(&obligation.predicate, snapshot); diff --git a/src/librustc/middle/traits/util.rs b/src/librustc/middle/traits/util.rs index edeca83d569..45ce692bb07 100644 --- a/src/librustc/middle/traits/util.rs +++ b/src/librustc/middle/traits/util.rs @@ -343,7 +343,7 @@ pub fn get_vtable_index_of_object_method<'tcx>(tcx: &ty::ctxt<'tcx>, } let trait_items = ty::trait_items(tcx, bound_ref.def_id()); - for trait_item in trait_items.iter() { + for trait_item in &**trait_items { match *trait_item { ty::MethodTraitItem(_) => method_count += 1, ty::TypeTraitItem(_) => {} diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 1544db8ce4a..a772555d8fc 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -872,7 +872,7 @@ macro_rules! sty_debug_print { $(let mut $variant = total;)* - for (_, t) in tcx.interner.borrow().iter() { + for (_, t) in &*tcx.interner.borrow() { let variant = match t.sty { ty::ty_bool | ty::ty_char | ty::ty_int(..) | ty::ty_uint(..) | ty::ty_float(..) | ty::ty_str => continue, @@ -2579,7 +2579,7 @@ impl FlagComputation { &ty_trait(box TyTrait { ref principal, ref bounds }) => { let mut computation = FlagComputation::new(); computation.add_substs(principal.0.substs); - for projection_bound in bounds.projection_bounds.iter() { + for projection_bound in &bounds.projection_bounds { let mut proj_computation = FlagComputation::new(); proj_computation.add_projection_predicate(&projection_bound.0); computation.add_bound_computation(&proj_computation); @@ -2618,7 +2618,7 @@ impl FlagComputation { } fn add_tys(&mut self, tys: &[Ty]) { - for &ty in tys.iter() { + for &ty in tys { self.add_ty(ty); } } @@ -3099,10 +3099,7 @@ pub fn type_is_unsafe_ptr(ty: Ty) -> bool { pub fn type_is_unique(ty: Ty) -> bool { match ty.sty { - ty_uniq(_) => match ty.sty { - ty_trait(..) => false, - _ => true - }, + ty_uniq(_) => true, _ => false } } @@ -3530,7 +3527,7 @@ pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents { // make no assumptions (other than that it cannot have an // in-scope type parameter within, which makes no sense). let mut tc = TC::All - TC::InteriorParam; - for bound in bounds.builtin_bounds.iter() { + for bound in &bounds.builtin_bounds { tc = tc - match bound { BoundSync | BoundSend | BoundCopy => TC::None, BoundSized => TC::Nonsized, @@ -4644,7 +4641,7 @@ pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId { pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field]) -> uint { let mut i = 0; - for f in fields.iter() { if f.name == name { return i; } i += 1; } + for f in fields { if f.name == name { return i; } i += 1; } tcx.sess.bug(&format!( "no field named `{}` found in the list of fields `{:?}`", token::get_name(name), @@ -5468,25 +5465,25 @@ pub fn predicates<'tcx>( { let mut vec = Vec::new(); - for builtin_bound in bounds.builtin_bounds.iter() { + for builtin_bound in &bounds.builtin_bounds { match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) { Ok(trait_ref) => { vec.push(trait_ref.as_predicate()); } Err(ErrorReported) => { } } } - for ®ion_bound in bounds.region_bounds.iter() { + for ®ion_bound in &bounds.region_bounds { // account for the binder being introduced below; no need to shift `param_ty` // because, at present at least, it can only refer to early-bound regions let region_bound = ty_fold::shift_region(region_bound, 1); vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).as_predicate()); } - for bound_trait_ref in bounds.trait_bounds.iter() { + for bound_trait_ref in &bounds.trait_bounds { vec.push(bound_trait_ref.as_predicate()); } - for projection in bounds.projection_bounds.iter() { + for projection in &bounds.projection_bounds { vec.push(projection.as_predicate()); } @@ -5931,17 +5928,17 @@ pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt, // Record the trait->implementation mappings, if applicable. let associated_traits = csearch::get_impl_trait(tcx, impl_def_id); - for trait_ref in associated_traits.iter() { + if let Some(ref trait_ref) = associated_traits { record_trait_implementation(tcx, trait_ref.def_id, impl_def_id); } // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. - for impl_item_def_id in impl_items.iter() { + for impl_item_def_id in &impl_items { let method_def_id = impl_item_def_id.def_id(); match impl_or_trait_item(tcx, method_def_id) { MethodTraitItem(method) => { - for &source in method.provided_source.iter() { + if let Some(source) = method.provided_source { tcx.provided_method_sources .borrow_mut() .insert(method_def_id, source); @@ -5985,11 +5982,11 @@ pub fn populate_implementations_for_trait_if_necessary( // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. - for impl_item_def_id in impl_items.iter() { + for impl_item_def_id in &impl_items { let method_def_id = impl_item_def_id.def_id(); match impl_or_trait_item(tcx, method_def_id) { MethodTraitItem(method) => { - for &source in method.provided_source.iter() { + if let Some(source) = method.provided_source { tcx.provided_method_sources .borrow_mut() .insert(method_def_id, source); @@ -6121,7 +6118,7 @@ pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) - }; let fn_sig = |&: state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| { let sig = anonymize_late_bound_regions(tcx, sig).0; - for a in sig.inputs.iter() { helper(tcx, *a, svh, state); } + for a in &sig.inputs { helper(tcx, *a, svh, state); } if let ty::FnConverging(output) = sig.output { helper(tcx, output, svh, state); } @@ -6270,7 +6267,7 @@ pub fn construct_free_substs<'a,'tcx>( free_id: ast::NodeId, region_params: &[RegionParameterDef]) { - for r in region_params.iter() { + for r in region_params { regions.push(r.space, ty::free_region_from_def(free_id, r)); } } @@ -6278,7 +6275,7 @@ pub fn construct_free_substs<'a,'tcx>( fn push_types_from_defs<'tcx>(tcx: &ty::ctxt<'tcx>, types: &mut VecPerParamSpace<Ty<'tcx>>, defs: &[TypeParameterDef<'tcx>]) { - for def in defs.iter() { + for def in defs { debug!("construct_parameter_environment(): push_types_from_defs: def={:?}", def.repr(tcx)); let ty = ty::mk_param_from_def(tcx, def); @@ -6351,7 +6348,7 @@ pub fn construct_parameter_environment<'a,'tcx>( fn record_region_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, predicates: &[ty::Predicate<'tcx>]) { debug!("record_region_bounds(predicates={:?})", predicates.repr(tcx)); - for predicate in predicates.iter() { + for predicate in predicates { match *predicate { Predicate::Projection(..) | Predicate::Trait(..) | @@ -6870,7 +6867,7 @@ pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tc let did = match self_type.sty { ty::ty_struct(struct_did, substs) => { let fields = ty::struct_fields(tcx, struct_did, substs); - for field in fields.iter() { + for field in &fields { if type_moves_by_default(param_env, span, field.mt.ty) { return Err(FieldDoesNotImplementCopy(field.name)) } @@ -6879,8 +6876,8 @@ pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tc } ty::ty_enum(enum_did, substs) => { let enum_variants = ty::enum_variants(tcx, enum_did); - for variant in enum_variants.iter() { - for variant_arg_type in variant.args.iter() { + for variant in &*enum_variants { + for variant_arg_type in &variant.args { let substd_arg_type = variant_arg_type.subst(tcx, substs); if type_moves_by_default(param_env, span, substd_arg_type) { diff --git a/src/librustc/middle/weak_lang_items.rs b/src/librustc/middle/weak_lang_items.rs index 25cca98c5fb..425c9a4c9f7 100644 --- a/src/librustc/middle/weak_lang_items.rs +++ b/src/librustc/middle/weak_lang_items.rs @@ -78,7 +78,7 @@ fn verify(sess: &Session, items: &lang_items::LanguageItems) { let mut missing = HashSet::new(); sess.cstore.iter_crate_data(|cnum, _| { - for item in csearch::get_missing_lang_items(&sess.cstore, cnum).iter() { + for item in &csearch::get_missing_lang_items(&sess.cstore, cnum) { missing.insert(*item); } }); diff --git a/src/librustc/plugin/build.rs b/src/librustc/plugin/build.rs index a8018662d29..110e672b70f 100644 --- a/src/librustc/plugin/build.rs +++ b/src/librustc/plugin/build.rs @@ -48,7 +48,7 @@ pub fn find_plugin_registrar(diagnostic: &diagnostic::SpanHandler, }, _ => { diagnostic.handler().err("multiple plugin registration functions found"); - for &(_, span) in finder.registrars.iter() { + for &(_, span) in &finder.registrars { diagnostic.span_note(span, "one is here"); } diagnostic.handler().abort_if_errors(); diff --git a/src/librustc/plugin/load.rs b/src/librustc/plugin/load.rs index c420d1f15b4..dd0b0a63ced 100644 --- a/src/librustc/plugin/load.rs +++ b/src/librustc/plugin/load.rs @@ -15,7 +15,7 @@ use metadata::creader::{CrateOrString, CrateReader}; use plugin::registry::Registry; use std::mem; -use std::os; +use std::env; use std::dynamic_lib::DynamicLibrary; use std::collections::HashSet; use syntax::ast; @@ -73,7 +73,7 @@ pub fn load_plugins(sess: &Session, krate: &ast::Crate, // We need to error on `#[macro_use] extern crate` when it isn't at the // crate root, because `$crate` won't work properly. Identify these by // spans, because the crate map isn't set up yet. - for item in krate.module.items.iter() { + for item in &krate.module.items { if let ast::ItemExternCrate(_) = item.node { loader.span_whitelist.insert(item.span); } @@ -82,7 +82,7 @@ pub fn load_plugins(sess: &Session, krate: &ast::Crate, visit::walk_crate(&mut loader, krate); if let Some(plugins) = addl_plugins { - for plugin in plugins.iter() { + for plugin in &plugins { loader.load_plugin(CrateOrString::Str(plugin.as_slice()), None, None, None) } @@ -107,7 +107,7 @@ impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { let mut plugin_attr = None; let mut macro_selection = Some(HashSet::new()); // None => load all let mut reexport = HashSet::new(); - for attr in item.attrs.iter() { + for attr in &item.attrs { let mut used = true; match attr.name().get() { "phase" => { @@ -127,7 +127,7 @@ impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { macro_selection = None; } if let (Some(sel), Some(names)) = (macro_selection.as_mut(), names) { - for name in names.iter() { + for name in names { if let ast::MetaWord(ref name) = name.node { sel.insert(name.clone()); } else { @@ -145,7 +145,7 @@ impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { } }; - for name in names.iter() { + for name in names { if let ast::MetaWord(ref name) = name.node { reexport.insert(name.clone()); } else { @@ -204,7 +204,7 @@ impl<'a> PluginLoader<'a> { } } - for mut def in macros.into_iter() { + for mut def in macros { let name = token::get_ident(def.ident); def.use_locally = match macro_selection.as_ref() { None => true, @@ -233,7 +233,7 @@ impl<'a> PluginLoader<'a> { path: Path, symbol: String) -> PluginRegistrarFun { // Make sure the path contains a / or the linker will search for it. - let path = os::make_absolute(&path).unwrap(); + let path = env::current_dir().unwrap().join(&path); let lib = match DynamicLibrary::open(Some(&path)) { Ok(lib) => lib, diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index ab182dd2256..88f6dc673cf 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -300,13 +300,13 @@ macro_rules! options { pub fn $buildfn(matches: &getopts::Matches) -> $struct_name { let mut op = $defaultfn(); - for option in matches.opt_strs($prefix).into_iter() { + for option in matches.opt_strs($prefix) { let mut iter = option.splitn(1, '='); let key = iter.next().unwrap(); let value = iter.next(); let option_to_lookup = key.replace("-", "_"); let mut found = false; - for &(candidate, setter, opt_type_desc, _) in $stat.iter() { + for &(candidate, setter, opt_type_desc, _) in $stat { if option_to_lookup != candidate { continue } if !setter(&mut op, value) { match (value, opt_type_desc) { @@ -830,8 +830,8 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let mut lint_opts = vec!(); let mut describe_lints = false; - for &level in [lint::Allow, lint::Warn, lint::Deny, lint::Forbid].iter() { - for lint_name in matches.opt_strs(level.as_str()).into_iter() { + for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] { + for lint_name in matches.opt_strs(level.as_str()) { if lint_name == "help" { describe_lints = true; } else { @@ -853,7 +853,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let mut output_types = Vec::new(); if !debugging_opts.parse_only && !no_trans { let unparsed_output_types = matches.opt_strs("emit"); - for unparsed_output_type in unparsed_output_types.iter() { + for unparsed_output_type in &unparsed_output_types { for part in unparsed_output_type.split(',') { let output_type = match part.as_slice() { "asm" => OutputTypeAssembly, @@ -923,7 +923,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { }; let mut search_paths = SearchPaths::new(); - for s in matches.opt_strs("L").iter() { + for s in &matches.opt_strs("L") { search_paths.add_path(&s[]); } @@ -997,7 +997,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { }; let mut externs = HashMap::new(); - for arg in matches.opt_strs("extern").iter() { + for arg in &matches.opt_strs("extern") { let mut parts = arg.splitn(1, '='); let name = match parts.next() { Some(s) => s, @@ -1049,7 +1049,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> { let mut crate_types: Vec<CrateType> = Vec::new(); - for unparsed_crate_type in list_list.iter() { + for unparsed_crate_type in &list_list { for part in unparsed_crate_type.split(',') { let new_part = match part { "lib" => default_lib_output(), diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 54384da33fc..07fbecbdebc 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -27,7 +27,7 @@ use syntax::{ast, codemap}; use rustc_back::target::Target; -use std::os; +use std::env; use std::cell::{Cell, RefCell}; pub mod config; @@ -347,7 +347,7 @@ pub fn build_session_(sopts: config::Options, if path.is_absolute() { path.clone() } else { - os::getcwd().unwrap().join(&path) + env::current_dir().unwrap().join(&path) } ); @@ -370,7 +370,7 @@ pub fn build_session_(sopts: config::Options, plugin_registrar_fn: Cell::new(None), default_sysroot: default_sysroot, local_crate_source_file: local_crate_source_file, - working_dir: os::getcwd().unwrap(), + working_dir: env::current_dir().unwrap(), lint_store: RefCell::new(lint::LintStore::new()), lints: RefCell::new(NodeMap()), crate_types: RefCell::new(Vec::new()), diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index a433161d659..b77a70f1f5d 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -163,7 +163,7 @@ pub fn can_reach<T, S>(edges_map: &HashMap<T, Vec<T>, S>, source: T, while i < queue.len() { match edges_map.get(&queue[i]) { Some(edges) => { - for target in edges.iter() { + for target in edges { if *target == destination { return true; } diff --git a/src/librustc/util/nodemap.rs b/src/librustc/util/nodemap.rs index 7aa126371c4..8da06e63dae 100644 --- a/src/librustc/util/nodemap.rs +++ b/src/librustc/util/nodemap.rs @@ -62,7 +62,7 @@ impl Hasher for FnvHasher { impl Writer for FnvHasher { fn write(&mut self, bytes: &[u8]) { let FnvHasher(mut hash) = *self; - for byte in bytes.iter() { + for byte in bytes { hash = hash ^ (*byte as u64); hash = hash * 0x100000001b3; } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index eb73757bf6a..458701f2dd7 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -494,11 +494,11 @@ pub fn parameterized<'tcx>(cx: &ctxt<'tcx>, 0 }; - for t in tps[..tps.len() - num_defaults].iter() { + for t in &tps[..tps.len() - num_defaults] { strs.push(ty_to_string(cx, *t)) } - for projection in projections.iter() { + for projection in projections { strs.push(format!("{}={}", projection.projection_ty.item_name.user_string(cx), projection.ty.user_string(cx))); @@ -665,7 +665,7 @@ impl<'tcx> UserString<'tcx> for ty::TyTrait<'tcx> { components.push(tap.user_string(tcx)); // Builtin bounds. - for bound in bounds.builtin_bounds.iter() { + for bound in &bounds.builtin_bounds { components.push(bound.user_string(tcx)); } @@ -748,7 +748,7 @@ impl<'tcx> Repr<'tcx> for subst::RegionSubsts { impl<'tcx> Repr<'tcx> for ty::BuiltinBounds { fn repr(&self, _tcx: &ctxt) -> String { let mut res = Vec::new(); - for b in self.iter() { + for b in self { res.push(match b { ty::BoundSend => "Send".to_string(), ty::BoundSized => "Sized".to_string(), @@ -764,7 +764,7 @@ impl<'tcx> Repr<'tcx> for ty::ParamBounds<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { let mut res = Vec::new(); res.push(self.builtin_bounds.repr(tcx)); - for t in self.trait_bounds.iter() { + for t in &self.trait_bounds { res.push(t.repr(tcx)); } res.connect("+") @@ -1157,7 +1157,7 @@ impl<'tcx> UserString<'tcx> for ty::ParamBounds<'tcx> { if !s.is_empty() { result.push(s); } - for n in self.trait_bounds.iter() { + for n in &self.trait_bounds { result.push(n.user_string(tcx)); } result.connect(" + ") @@ -1173,11 +1173,11 @@ impl<'tcx> Repr<'tcx> for ty::ExistentialBounds<'tcx> { res.push(region_str); } - for bound in self.builtin_bounds.iter() { + for bound in &self.builtin_bounds { res.push(bound.user_string(tcx)); } - for projection_bound in self.projection_bounds.iter() { + for projection_bound in &self.projection_bounds { res.push(projection_bound.user_string(tcx)); } diff --git a/src/librustc_back/archive.rs b/src/librustc_back/archive.rs index ee8bc71668b..b779963a219 100644 --- a/src/librustc_back/archive.rs +++ b/src/librustc_back/archive.rs @@ -14,7 +14,7 @@ use std::old_io::fs::PathExtensions; use std::old_io::process::{Command, ProcessOutput}; use std::old_io::{fs, TempDir}; use std::old_io; -use std::os; +use std::env; use std::str; use syntax::diagnostic::Handler as ErrorHandler; @@ -99,7 +99,7 @@ pub fn find_library(name: &str, osprefix: &str, ossuffix: &str, let oslibname = format!("{}{}{}", osprefix, name, ossuffix); let unixlibname = format!("lib{}.a", name); - for path in search_paths.iter() { + for path in search_paths { debug!("looking for {} inside {:?}", name, path.display()); let test = path.join(&oslibname[]); if test.exists() { return test } @@ -224,7 +224,7 @@ impl<'a> ArchiveBuilder<'a> { pub fn build(self) -> Archive<'a> { // Get an absolute path to the destination, so `ar` will work even // though we run it from `self.work_dir`. - let abs_dst = os::getcwd().unwrap().join(&self.archive.dst); + let abs_dst = env::current_dir().unwrap().join(&self.archive.dst); assert!(!abs_dst.is_relative()); let mut args = vec![&abs_dst]; let mut total_len = abs_dst.as_vec().len(); @@ -244,7 +244,7 @@ impl<'a> ArchiveBuilder<'a> { // 32,768, and we leave a bit of extra space for the program name. static ARG_LENGTH_LIMIT: uint = 32000; - for member_name in self.members.iter() { + for member_name in &self.members { let len = member_name.as_vec().len(); // `len + 1` to account for the space that's inserted before each @@ -283,7 +283,7 @@ impl<'a> ArchiveBuilder<'a> { // First, extract the contents of the archive to a temporary directory. // We don't unpack directly into `self.work_dir` due to the possibility // of filename collisions. - let archive = os::make_absolute(archive).unwrap(); + let archive = env::current_dir().unwrap().join(archive); run_ar(self.archive.handler, &self.archive.maybe_ar_prog, "x", Some(loc.path()), &[&archive]); @@ -297,7 +297,7 @@ impl<'a> ArchiveBuilder<'a> { // all SYMDEF files as these are just magical placeholders which get // re-created when we make a new archive anyway. let files = try!(fs::readdir(loc.path())); - for file in files.iter() { + for file in &files { let filename = file.filename_str().unwrap(); if skip(filename) { continue } if filename.contains(".SYMDEF") { continue } diff --git a/src/librustc_back/arm.rs b/src/librustc_back/arm.rs index 7e28cd699a1..a4417b49f1c 100644 --- a/src/librustc_back/arm.rs +++ b/src/librustc_back/arm.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -61,7 +61,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -a:0:64-n32".to_string() } - abi::OsFreebsd | abi::OsDragonfly => { + abi::OsFreebsd | abi::OsDragonfly | abi::OsOpenbsd => { "e-p:32:32:32\ -i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\ -f32:32:32-f64:64:64\ diff --git a/src/librustc_back/fs.rs b/src/librustc_back/fs.rs index 24f81b02478..acf49d1ca46 100644 --- a/src/librustc_back/fs.rs +++ b/src/librustc_back/fs.rs @@ -10,13 +10,13 @@ use std::old_io; use std::old_io::fs; -use std::os; +use std::env; /// Returns an absolute path in the filesystem that `path` points to. The /// returned path does not contain any symlinks in its hierarchy. pub fn realpath(original: &Path) -> old_io::IoResult<Path> { static MAX_LINKS_FOLLOWED: uint = 256; - let original = os::make_absolute(original).unwrap(); + let original = try!(env::current_dir()).join(original); // Right now lstat on windows doesn't work quite well if cfg!(windows) { diff --git a/src/librustc_back/lib.rs b/src/librustc_back/lib.rs index 2c6b5797f57..54b3e8f2081 100644 --- a/src/librustc_back/lib.rs +++ b/src/librustc_back/lib.rs @@ -40,6 +40,7 @@ #![feature(path)] #![feature(rustc_private)] #![feature(staged_api)] +#![feature(env)] extern crate syntax; extern crate serialize; diff --git a/src/librustc_back/mips.rs b/src/librustc_back/mips.rs index bc7732157ce..cb44fe117f5 100644 --- a/src/librustc_back/mips.rs +++ b/src/librustc_back/mips.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -56,7 +56,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -a:0:64-n32".to_string() } - abi::OsFreebsd | abi::OsDragonfly => { + abi::OsFreebsd | abi::OsDragonfly | abi::OsOpenbsd => { "E-p:32:32:32\ -i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\ -f32:32:32-f64:64:64\ diff --git a/src/librustc_back/mipsel.rs b/src/librustc_back/mipsel.rs index 3eea0a0dba4..7ee357fb1ea 100644 --- a/src/librustc_back/mipsel.rs +++ b/src/librustc_back/mipsel.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -56,7 +56,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -a:0:64-n32".to_string() } - abi::OsFreebsd | abi::OsDragonfly => { + abi::OsFreebsd | abi::OsDragonfly | abi::OsOpenbsd => { "e-p:32:32:32\ -i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\ -f32:32:32-f64:64:64\ diff --git a/src/librustc_back/rpath.rs b/src/librustc_back/rpath.rs index 47b909df5e8..36bbd4b9872 100644 --- a/src/librustc_back/rpath.rs +++ b/src/librustc_back/rpath.rs @@ -1,4 +1,4 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -10,7 +10,7 @@ use std::collections::HashSet; -use std::os; +use std::env; use std::old_io::IoError; use syntax::ast; @@ -51,7 +51,7 @@ pub fn get_rpath_flags<F, G>(config: RPathConfig<F, G>) -> Vec<String> where fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> { let mut ret = Vec::new(); - for rpath in rpaths.iter() { + for rpath in rpaths { ret.push(format!("-Wl,-rpath,{}", &(*rpath)[])); } return ret; @@ -63,7 +63,7 @@ fn get_rpaths<F, G>(mut config: RPathConfig<F, G>, libs: &[Path]) -> Vec<String> { debug!("output: {:?}", config.out_filename.display()); debug!("libs:"); - for libpath in libs.iter() { + for libpath in libs { debug!(" {:?}", libpath.display()); } @@ -77,7 +77,7 @@ fn get_rpaths<F, G>(mut config: RPathConfig<F, G>, libs: &[Path]) -> Vec<String> fn log_rpaths(desc: &str, rpaths: &[String]) { debug!("{} rpaths:", desc); - for rpath in rpaths.iter() { + for rpath in rpaths { debug!(" {}", *rpath); } } @@ -105,8 +105,6 @@ fn get_rpath_relative_to_output<F, G>(config: &mut RPathConfig<F, G>, lib: &Path F: FnOnce() -> Path, G: FnMut(&Path) -> Result<Path, IoError>, { - use std::os; - // Mac doesn't appear to support $ORIGIN let prefix = if config.is_like_osx { "@loader_path" @@ -114,9 +112,10 @@ fn get_rpath_relative_to_output<F, G>(config: &mut RPathConfig<F, G>, lib: &Path "$ORIGIN" }; - let mut lib = (config.realpath)(&os::make_absolute(lib).unwrap()).unwrap(); + let cwd = env::current_dir().unwrap(); + let mut lib = (config.realpath)(&cwd.join(lib)).unwrap(); lib.pop(); - let mut output = (config.realpath)(&os::make_absolute(&config.out_filename).unwrap()).unwrap(); + let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap(); output.pop(); let relative = lib.path_relative_from(&output); let relative = relative.expect("could not create rpath relative to output"); @@ -131,7 +130,7 @@ fn get_install_prefix_rpath<F, G>(config: RPathConfig<F, G>) -> String where G: FnMut(&Path) -> Result<Path, IoError>, { let path = (config.get_install_prefix_lib_path)(); - let path = os::make_absolute(&path).unwrap(); + let path = env::current_dir().unwrap().join(&path); // FIXME (#9639): This needs to handle non-utf8 paths path.as_str().expect("non-utf8 component in rpath").to_string() } @@ -139,7 +138,7 @@ fn get_install_prefix_rpath<F, G>(config: RPathConfig<F, G>) -> String where fn minimize_rpaths(rpaths: &[String]) -> Vec<String> { let mut set = HashSet::new(); let mut minimized = Vec::new(); - for rpath in rpaths.iter() { + for rpath in rpaths { if set.insert(&rpath[]) { minimized.push(rpath.clone()); } @@ -214,7 +213,9 @@ mod test { } #[test] - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(any(target_os = "freebsd", + target_os = "dragonfly", + target_os = "openbsd"))] fn test_rpath_relative() { let config = &mut RPathConfig { used_crates: Vec::new(), diff --git a/src/librustc_back/sha2.rs b/src/librustc_back/sha2.rs index d99ce8b64b0..c15b4114aa7 100644 --- a/src/librustc_back/sha2.rs +++ b/src/librustc_back/sha2.rs @@ -557,7 +557,7 @@ mod tests { fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once - for t in tests.iter() { + for t in tests { sh.reset(); sh.input_str(t.input.as_slice()); let out_str = sh.result_str(); @@ -565,7 +565,7 @@ mod tests { } // Test that it works when accepting the message in pieces - for t in tests.iter() { + for t in tests { sh.reset(); let len = t.input.len(); let mut left = len; diff --git a/src/librustc_back/svh.rs b/src/librustc_back/svh.rs index 3d7adc9934f..a14f4775ec1 100644 --- a/src/librustc_back/svh.rs +++ b/src/librustc_back/svh.rs @@ -79,7 +79,7 @@ impl Svh { // avoid collisions. let mut state = SipHasher::new(); - for data in metadata.iter() { + for data in metadata { data.hash(&mut state); } @@ -97,7 +97,7 @@ impl Svh { // // We hash only the MetaItems instead of the entire Attribute // to avoid hashing the AttrId - for attr in krate.attrs.iter() { + for attr in &krate.attrs { attr.node.value.hash(&mut state); } diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index 16adccfba57..4b3833b687c 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -56,6 +56,7 @@ mod apple_base; mod apple_ios_base; mod freebsd_base; mod dragonfly_base; +mod openbsd_base; mod armv7_apple_ios; mod armv7s_apple_ios; @@ -80,6 +81,7 @@ mod x86_64_pc_windows_gnu; mod x86_64_unknown_freebsd; mod x86_64_unknown_dragonfly; mod x86_64_unknown_linux_gnu; +mod x86_64_unknown_openbsd; /// Everything `rustc` knows about how to compile for a specific target. /// @@ -301,7 +303,8 @@ impl Target { /// The error string could come from any of the APIs called, including filesystem access and /// JSON decoding. pub fn search(target: &str) -> Result<Target, String> { - use std::os; + use std::env; + use std::ffi::OsString; use std::old_io::File; use std::path::Path; use serialize::json; @@ -352,6 +355,8 @@ impl Target { i686_unknown_dragonfly, x86_64_unknown_dragonfly, + x86_64_unknown_openbsd, + x86_64_apple_darwin, i686_apple_darwin, @@ -379,12 +384,12 @@ impl Target { Path::new(target) }; - let target_path = os::getenv("RUST_TARGET_PATH").unwrap_or(String::new()); + let target_path = env::var("RUST_TARGET_PATH") + .unwrap_or(OsString::from_str("")); - let paths = os::split_paths(&target_path[]); // FIXME 16351: add a sane default search path? - for dir in paths.iter() { + for dir in env::split_paths(&target_path) { let p = dir.join(path.clone()); if p.is_file() { return load_file(&p); diff --git a/src/librustc_back/target/openbsd_base.rs b/src/librustc_back/target/openbsd_base.rs new file mode 100644 index 00000000000..42220a87bd4 --- /dev/null +++ b/src/librustc_back/target/openbsd_base.rs @@ -0,0 +1,28 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use target::TargetOptions; +use std::default::Default; + +pub fn opts() -> TargetOptions { + TargetOptions { + linker: "cc".to_string(), + dynamic_linking: true, + executables: true, + morestack: false, + linker_is_gnu: true, + has_rpath: true, + pre_link_args: vec!( + ), + position_independent_executables: true, + .. Default::default() + } +} + diff --git a/src/librustc_back/target/x86_64_unknown_openbsd.rs b/src/librustc_back/target/x86_64_unknown_openbsd.rs new file mode 100644 index 00000000000..d2667dcd1dd --- /dev/null +++ b/src/librustc_back/target/x86_64_unknown_openbsd.rs @@ -0,0 +1,28 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use target::Target; + +pub fn target() -> Target { + let mut base = super::openbsd_base::opts(); + base.pre_link_args.push("-m64".to_string()); + + Target { + data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\ + f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\ + s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(), + llvm_target: "x86_64-unknown-openbsd".to_string(), + target_endian: "little".to_string(), + target_pointer_width: "64".to_string(), + arch: "x86_64".to_string(), + target_os: "openbsd".to_string(), + options: base, + } +} diff --git a/src/librustc_back/x86.rs b/src/librustc_back/x86.rs index 52c07165900..9d1b7347d06 100644 --- a/src/librustc_back/x86.rs +++ b/src/librustc_back/x86.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -51,6 +51,9 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) abi::OsDragonfly => { "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string() } + abi::OsOpenbsd => { + "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string() + } }, diff --git a/src/librustc_back/x86_64.rs b/src/librustc_back/x86_64.rs index cbb288a533d..2f13bb31581 100644 --- a/src/librustc_back/x86_64.rs +++ b/src/librustc_back/x86_64.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -57,6 +57,11 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\ s0:64:64-f80:128:128-n8:16:32:64-S128".to_string() } + abi::OsOpenbsd => { + "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\ + f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\ + s0:64:64-f80:128:128-n8:16:32:64-S128".to_string() + } }, diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs index b66419420e9..b8d736ab9ca 100644 --- a/src/librustc_borrowck/borrowck/check_loans.rs +++ b/src/librustc_borrowck/borrowck/check_loans.rs @@ -279,7 +279,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { let loan_path = owned_ptr_base_path(loan_path); let cont = self.each_in_scope_loan(scope, |loan| { let mut ret = true; - for restr_path in loan.restricted_paths.iter() { + for restr_path in &loan.restricted_paths { if **restr_path == *loan_path { if !op(loan) { ret = false; @@ -361,7 +361,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { debug!("new_loan_indices = {:?}", new_loan_indices); self.each_issued_loan(scope, |issued_loan| { - for &new_loan_index in new_loan_indices.iter() { + for &new_loan_index in &new_loan_indices { let new_loan = &self.all_loans[new_loan_index]; self.report_error_if_loans_conflict(issued_loan, new_loan); } @@ -370,7 +370,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { for (i, &x) in new_loan_indices.iter().enumerate() { let old_loan = &self.all_loans[x]; - for &y in new_loan_indices[(i+1) ..].iter() { + for &y in &new_loan_indices[(i+1) ..] { let new_loan = &self.all_loans[y]; self.report_error_if_loans_conflict(old_loan, new_loan); } @@ -416,7 +416,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { } let loan2_base_path = owned_ptr_base_path_rc(&loan2.loan_path); - for restr_path in loan1.restricted_paths.iter() { + for restr_path in &loan1.restricted_paths { if *restr_path != loan2_base_path { continue; } // If new_loan is something like `x.a`, and old_loan is something like `x.b`, we would diff --git a/src/librustc_borrowck/borrowck/fragments.rs b/src/librustc_borrowck/borrowck/fragments.rs index 6e71da198e3..6f51ba31182 100644 --- a/src/librustc_borrowck/borrowck/fragments.rs +++ b/src/librustc_borrowck/borrowck/fragments.rs @@ -204,14 +204,14 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { debug!("fragments 1 assigned: {:?}", path_lps(&assigned[])); // Second, build parents from the moved and assigned. - for m in moved.iter() { + for m in &moved { let mut p = this.path_parent(*m); while p != InvalidMovePathIndex { parents.push(p); p = this.path_parent(p); } } - for a in assigned.iter() { + for a in &assigned { let mut p = this.path_parent(*a); while p != InvalidMovePathIndex { parents.push(p); @@ -231,15 +231,15 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { debug!("fragments 3 assigned: {:?}", path_lps(&assigned[])); // Fourth, build the leftover from the moved, assigned, and parents. - for m in moved.iter() { + for m in &moved { let lp = this.path_loan_path(*m); add_fragment_siblings(this, tcx, &mut unmoved, lp, None); } - for a in assigned.iter() { + for a in &assigned { let lp = this.path_loan_path(*a); add_fragment_siblings(this, tcx, &mut unmoved, lp, None); } - for p in parents.iter() { + for p in &parents { let lp = this.path_loan_path(*p); add_fragment_siblings(this, tcx, &mut unmoved, lp, None); } @@ -369,7 +369,7 @@ fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>, let fields = ty::lookup_struct_fields(tcx, def_id); match *origin_field_name { mc::NamedField(ast_name) => { - for f in fields.iter() { + for f in &fields { if f.name == ast_name { continue; } @@ -407,7 +407,7 @@ fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>, match *origin_field_name { mc::NamedField(ast_name) => { let variant_arg_names = variant_info.arg_names.as_ref().unwrap(); - for variant_arg_ident in variant_arg_names.iter() { + for variant_arg_ident in variant_arg_names { if variant_arg_ident.name == ast_name { continue; } diff --git a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs index 28d02161eeb..d9e86bd4b6d 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs @@ -67,10 +67,10 @@ pub struct GroupedMoveErrors<'tcx> { fn report_move_errors<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, errors: &Vec<MoveError<'tcx>>) { let grouped_errors = group_errors_with_same_origin(errors); - for error in grouped_errors.iter() { + for error in &grouped_errors { report_cannot_move_out_of(bccx, error.move_from.clone()); let mut is_first_note = true; - for move_to in error.move_to_places.iter() { + for move_to in &error.move_to_places { note_move_destination(bccx, move_to.span, &move_to.ident, is_first_note); is_first_note = false; @@ -81,7 +81,7 @@ fn report_move_errors<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, fn group_errors_with_same_origin<'tcx>(errors: &Vec<MoveError<'tcx>>) -> Vec<GroupedMoveErrors<'tcx>> { let mut grouped_errors = Vec::new(); - for error in errors.iter() { + for error in errors { append_to_grouped_errors(&mut grouped_errors, error) } return grouped_errors; @@ -95,7 +95,7 @@ fn group_errors_with_same_origin<'tcx>(errors: &Vec<MoveError<'tcx>>) } else { Vec::new() }; - for ge in grouped_errors.iter_mut() { + for ge in &mut *grouped_errors { if move_from_id == ge.move_from.id && error.move_to.is_some() { debug!("appending move_to to list"); ge.move_to_places.extend(move_to.into_iter()); diff --git a/src/librustc_borrowck/borrowck/move_data.rs b/src/librustc_borrowck/borrowck/move_data.rs index ece9d61d7f2..76c431fa4c5 100644 --- a/src/librustc_borrowck/borrowck/move_data.rs +++ b/src/librustc_borrowck/borrowck/move_data.rs @@ -475,13 +475,13 @@ impl<'tcx> MoveData<'tcx> { self.kill_moves(assignment.path, assignment.id, dfcx_moves); } - for assignment in self.path_assignments.borrow().iter() { + for assignment in &*self.path_assignments.borrow() { self.kill_moves(assignment.path, assignment.id, dfcx_moves); } // Kill all moves related to a variable `x` when // it goes out of scope: - for path in self.paths.borrow().iter() { + for path in &*self.paths.borrow() { match path.loan_path.kind { LpVar(..) | LpUpvar(..) | LpDowncast(..) => { let kill_scope = path.loan_path.kill_scope(tcx); @@ -633,11 +633,11 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> { //! Returns the kind of a move of `loan_path` by `id`, if one exists. let mut ret = None; - for loan_path_index in self.move_data.path_map.borrow().get(&*loan_path).iter() { + if let Some(loan_path_index) = self.move_data.path_map.borrow().get(&*loan_path) { self.dfcx_moves.each_gen_bit(id, |move_index| { let the_move = self.move_data.moves.borrow(); let the_move = (*the_move)[move_index]; - if the_move.path == **loan_path_index { + if the_move.path == *loan_path_index { ret = Some(the_move.kind); false } else { @@ -688,7 +688,7 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> { ret = false; } } else { - for &loan_path_index in opt_loan_path_index.iter() { + if let Some(loan_path_index) = opt_loan_path_index { let cont = self.move_data.each_base_path(moved_path, |p| { if p == loan_path_index { // Scenario 3: some extension of `loan_path` @@ -699,7 +699,7 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> { true } }); - if !cont { ret = false; break } + if !cont { ret = false; } } } ret diff --git a/src/librustc_borrowck/graphviz.rs b/src/librustc_borrowck/graphviz.rs index 150e616b36c..8b1b156691a 100644 --- a/src/librustc_borrowck/graphviz.rs +++ b/src/librustc_borrowck/graphviz.rs @@ -56,7 +56,7 @@ impl<'a, 'tcx> DataflowLabeller<'a, 'tcx> { debug!("dataflow_for({:?}, id={}) {:?}", e, id, self.variants); let mut sets = "".to_string(); let mut seen_one = false; - for &variant in self.variants.iter() { + for &variant in &self.variants { if seen_one { sets.push_str(" "); } else { seen_one = true; } sets.push_str(variant.short_name()); sets.push_str(": "); diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 9e00844b7ee..9b9cc14c476 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -30,9 +30,10 @@ use rustc_privacy; use serialize::json; -use std::old_io; +use std::env; +use std::ffi::OsString; use std::old_io::fs; -use std::os; +use std::old_io; use syntax::ast; use syntax::ast_map; use syntax::attr; @@ -424,7 +425,7 @@ pub fn phase_2_configure_and_expand(sess: &Session, diagnostics::plugin::expand_build_diagnostic_array); } - for registrar in registrars.into_iter() { + for registrar in registrars { registry.args_hidden = Some(registrar.args); (registrar.fun)(&mut registry); } @@ -434,11 +435,11 @@ pub fn phase_2_configure_and_expand(sess: &Session, { let mut ls = sess.lint_store.borrow_mut(); - for pass in lint_passes.into_iter() { + for pass in lint_passes { ls.register_pass(Some(sess), true, pass); } - for (name, to) in lint_groups.into_iter() { + for (name, to) in lint_groups { ls.register_group(Some(sess), true, name, to); } } @@ -460,12 +461,12 @@ pub fn phase_2_configure_and_expand(sess: &Session, // dependent dlls. Note that this uses cfg!(windows) as opposed to // targ_cfg because syntax extensions are always loaded for the host // compiler, not for the target. - let mut _old_path = String::new(); + let mut _old_path = OsString::from_str(""); if cfg!(windows) { - _old_path = os::getenv("PATH").unwrap_or(_old_path); + _old_path = env::var("PATH").unwrap_or(_old_path); let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths(); - new_path.extend(os::split_paths(&_old_path[]).into_iter()); - os::setenv("PATH", os::join_paths(&new_path[]).unwrap()); + new_path.extend(env::split_paths(&_old_path)); + env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap()); } let cfg = syntax::ext::expand::ExpansionConfig { crate_name: crate_name.to_string(), @@ -478,7 +479,7 @@ pub fn phase_2_configure_and_expand(sess: &Session, syntax_exts, krate); if cfg!(windows) { - os::setenv("PATH", _old_path); + env::set_var("PATH", &_old_path); } ret } @@ -734,10 +735,10 @@ pub fn phase_5_run_llvm_passes(sess: &Session, pub fn phase_6_link_output(sess: &Session, trans: &trans::CrateTranslation, outputs: &OutputFilenames) { - let old_path = os::getenv("PATH").unwrap_or_else(||String::new()); + let old_path = env::var("PATH").unwrap_or(OsString::from_str("")); let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(); - new_path.extend(os::split_paths(&old_path[]).into_iter()); - os::setenv("PATH", os::join_paths(&new_path[]).unwrap()); + new_path.extend(env::split_paths(&old_path)); + env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap()); time(sess.time_passes(), "linking", (), |_| link::link_binary(sess, @@ -745,7 +746,7 @@ pub fn phase_6_link_output(sess: &Session, outputs, &trans.link.crate_name[])); - os::setenv("PATH", old_path); + env::set_var("PATH", &old_path); } fn escape_dep_filename(filename: &str) -> String { @@ -760,11 +761,11 @@ fn write_out_deps(sess: &Session, id: &str) { let mut out_filenames = Vec::new(); - for output_type in sess.opts.output_types.iter() { + for output_type in &sess.opts.output_types { let file = outputs.path(*output_type); match *output_type { config::OutputTypeExe => { - for output in sess.crate_types.borrow().iter() { + for output in &*sess.crate_types.borrow() { let p = link::filename_for_input(sess, *output, id, &file); out_filenames.push(p); @@ -800,7 +801,7 @@ fn write_out_deps(sess: &Session, .map(|fmap| escape_dep_filename(&fmap.name[])) .collect(); let mut file = try!(old_io::File::create(&deps_filename)); - for path in out_filenames.iter() { + for path in &out_filenames { try!(write!(&mut file as &mut Writer, "{}: {}\n\n", path.display(), files.connect(" "))); } diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 2eada1ff174..d71e85e6a55 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -26,6 +26,7 @@ #![feature(box_syntax)] #![feature(collections)] #![feature(core)] +#![feature(env)] #![feature(int_uint)] #![feature(io)] #![feature(libc)] @@ -74,7 +75,7 @@ use rustc::util::common::time; use std::cmp::Ordering::Equal; use std::old_io; use std::iter::repeat; -use std::os; +use std::env; use std::sync::mpsc::channel; use std::thread; @@ -252,7 +253,7 @@ pub fn get_unstable_features_setting() -> UnstableFeatures { // subverting the unstable features lints let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY"); // The matching key to the above, only known by the build system - let bootstrap_provided_key = os::getenv("RUSTC_BOOTSTRAP_KEY"); + let bootstrap_provided_key = env::var_string("RUSTC_BOOTSTRAP_KEY").ok(); match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) { (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat, (true, _, _) => UnstableFeatures::Disallow, @@ -373,7 +374,7 @@ Available lint options: println!(" {} {:7.7} {}", padded("----"), "-------", "-------"); let print_lints = |&: lints: Vec<&Lint>| { - for lint in lints.into_iter() { + for lint in lints { let name = lint.name_lower().replace("_", "-"); println!(" {} {:7.7} {}", padded(&name[]), lint.default_level.as_str(), lint.desc); @@ -400,7 +401,7 @@ Available lint options: println!(" {} {}", padded("----"), "---------"); let print_lint_groups = |&: lints: Vec<(&'static str, Vec<lint::LintId>)>| { - for (name, to) in lints.into_iter() { + for (name, to) in lints { let name = name.chars().map(|x| x.to_lowercase()) .collect::<String>().replace("_", "-"); let desc = to.into_iter().map(|x| x.as_str().replace("_", "-")) @@ -435,7 +436,7 @@ Available lint options: fn describe_debug_flags() { println!("\nAvailable debug options:\n"); - for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS.iter() { + for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS { let (width, extra) = match opt_type_desc { Some(..) => (21, "=val"), None => (25, "") @@ -447,7 +448,7 @@ fn describe_debug_flags() { fn describe_codegen_flags() { println!("\nAvailable codegen options:\n"); - for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS.iter() { + for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS { let (width, extra) = match opt_type_desc { Some(..) => (21, "=val"), None => (25, "") @@ -542,7 +543,7 @@ fn print_crate_info(sess: &Session, if sess.opts.prints.len() == 0 { return false } let attrs = input.map(|input| parse_crate_attrs(sess, input)); - for req in sess.opts.prints.iter() { + for req in &sess.opts.prints { match *req { PrintRequest::Sysroot => println!("{}", sess.sysroot().display()), PrintRequest::FileNames | @@ -566,7 +567,7 @@ fn print_crate_info(sess: &Session, let crate_types = driver::collect_crate_types(sess, attrs); let metadata = driver::collect_crate_metadata(sess, attrs); *sess.crate_metadata.borrow_mut() = metadata; - for &style in crate_types.iter() { + for &style in &crate_types { let fname = link::filename_for_input(sess, style, id.as_slice(), &t_outputs.with_extension("")); @@ -618,7 +619,7 @@ pub fn monitor<F:FnOnce()+Send>(f: F) { // FIXME: Hacks on hacks. If the env is trying to override the stack size // then *don't* set it explicitly. - if os::getenv("RUST_MIN_STACK").is_none() { + if env::var("RUST_MIN_STACK").is_none() { cfg = cfg.stack_size(STACK_SIZE); } @@ -645,7 +646,7 @@ pub fn monitor<F:FnOnce()+Send>(f: F) { BUG_REPORT_URL), "run with `RUST_BACKTRACE=1` for a backtrace".to_string(), ]; - for note in xs.iter() { + for note in &xs { emitter.emit(None, ¬e[], None, diagnostic::Note) } @@ -682,8 +683,8 @@ pub fn diagnostics_registry() -> diagnostics::registry::Registry { } pub fn main() { - let args = std::os::args(); - let result = run(args); - std::os::set_exit_status(result); + let args = env::args().map(|s| s.into_string().unwrap()); + let result = run(args.collect()); + std::env::set_exit_status(result as i32); } diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 45ff1c4537c..20bf77190be 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -147,7 +147,7 @@ impl<'a, 'tcx> Env<'a, 'tcx> { } pub fn create_region_hierarchy(&self, rh: &RH) { - for child_rh in rh.sub.iter() { + for child_rh in rh.sub { self.create_region_hierarchy(child_rh); self.infcx.tcx.region_maps.record_encl_scope( CodeExtent::from_node_id(child_rh.id), @@ -181,7 +181,7 @@ impl<'a, 'tcx> Env<'a, 'tcx> { names: &[String]) -> Option<ast::NodeId> { assert!(idx < names.len()); - for item in m.items.iter() { + for item in &m.items { if item.ident.user_string(this.infcx.tcx) == names[idx] { return search(this, &**item, idx+1, names); } diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index a24bc6eaec3..a1532c044e3 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -63,8 +63,9 @@ use libc::{c_uint, c_ushort, uint64_t, c_int, size_t, c_char}; use libc::{c_longlong, c_ulonglong, c_void}; use debuginfo::{DIBuilderRef, DIDescriptor, DIFile, DILexicalBlock, DISubprogram, DIType, - DIBasicType, DIDerivedType, DICompositeType, - DIVariable, DIGlobalVariable, DIArray, DISubrange}; + DIBasicType, DIDerivedType, DICompositeType, DIScope, + DIVariable, DIGlobalVariable, DIArray, DISubrange, + DITemplateTypeParameter, DIEnumerator, DINameSpace}; pub mod archive_ro; pub mod diagnostic; @@ -261,13 +262,13 @@ impl AttrBuilder { } pub fn apply_llfn(&self, llfn: ValueRef) { - for &(idx, ref attr) in self.attrs.iter() { + for &(idx, ref attr) in &self.attrs { attr.apply_llfn(idx as c_uint, llfn); } } pub fn apply_callsite(&self, callsite: ValueRef) { - for &(idx, ref attr) in self.attrs.iter() { + for &(idx, ref attr) in &self.attrs { attr.apply_callsite(idx as c_uint, callsite); } } @@ -442,6 +443,9 @@ pub type TypeRef = *mut Type_opaque; pub enum Value_opaque {} pub type ValueRef = *mut Value_opaque; #[allow(missing_copy_implementations)] +pub enum Metadata_opaque {} +pub type MetadataRef = *mut Metadata_opaque; +#[allow(missing_copy_implementations)] pub enum BasicBlock_opaque {} pub type BasicBlockRef = *mut BasicBlock_opaque; #[allow(missing_copy_implementations)] @@ -501,18 +505,19 @@ pub type InlineAsmDiagHandler = unsafe extern "C" fn(SMDiagnosticRef, *const c_v pub mod debuginfo { pub use self::DIDescriptorFlags::*; - use super::{ValueRef}; + use super::{MetadataRef}; #[allow(missing_copy_implementations)] pub enum DIBuilder_opaque {} pub type DIBuilderRef = *mut DIBuilder_opaque; - pub type DIDescriptor = ValueRef; + pub type DIDescriptor = MetadataRef; pub type DIScope = DIDescriptor; pub type DILocation = DIDescriptor; pub type DIFile = DIScope; pub type DILexicalBlock = DIScope; pub type DISubprogram = DIScope; + pub type DINameSpace = DIScope; pub type DIType = DIDescriptor; pub type DIBasicType = DIType; pub type DIDerivedType = DIType; @@ -521,6 +526,8 @@ pub mod debuginfo { pub type DIGlobalVariable = DIDescriptor; pub type DIArray = DIDescriptor; pub type DISubrange = DIDescriptor; + pub type DIEnumerator = DIDescriptor; + pub type DITemplateTypeParameter = DIDescriptor; #[derive(Copy)] pub enum DIDescriptorFlags { @@ -1778,8 +1785,8 @@ extern { Flags: c_uint, isOptimized: bool, Fn: ValueRef, - TParam: ValueRef, - Decl: ValueRef) + TParam: DIArray, + Decl: DIDescriptor) -> DISubprogram; pub fn LLVMDIBuilderCreateBasicType(Builder: DIBuilderRef, @@ -1807,7 +1814,7 @@ extern { DerivedFrom: DIType, Elements: DIArray, RunTimeLang: c_uint, - VTableHolder: ValueRef, + VTableHolder: DIType, UniqueId: *const c_char) -> DICompositeType; @@ -1824,14 +1831,14 @@ extern { -> DIDerivedType; pub fn LLVMDIBuilderCreateLexicalBlock(Builder: DIBuilderRef, - Scope: DIDescriptor, + Scope: DIScope, File: DIFile, Line: c_uint, Col: c_uint) -> DILexicalBlock; pub fn LLVMDIBuilderCreateStaticVariable(Builder: DIBuilderRef, - Context: DIDescriptor, + Context: DIScope, Name: *const c_char, LinkageName: *const c_char, File: DIFile, @@ -1839,10 +1846,10 @@ extern { Ty: DIType, isLocalToUnit: bool, Val: ValueRef, - Decl: ValueRef) + Decl: DIDescriptor) -> DIGlobalVariable; - pub fn LLVMDIBuilderCreateLocalVariable(Builder: DIBuilderRef, + pub fn LLVMDIBuilderCreateVariable(Builder: DIBuilderRef, Tag: c_uint, Scope: DIDescriptor, Name: *const c_char, @@ -1851,6 +1858,8 @@ extern { Ty: DIType, AlwaysPreserve: bool, Flags: c_uint, + AddrOps: *const i64, + AddrOpsCount: c_uint, ArgNo: c_uint) -> DIVariable; @@ -1881,79 +1890,80 @@ extern { pub fn LLVMDIBuilderInsertDeclareAtEnd(Builder: DIBuilderRef, Val: ValueRef, VarInfo: DIVariable, + AddrOps: *const i64, + AddrOpsCount: c_uint, InsertAtEnd: BasicBlockRef) -> ValueRef; pub fn LLVMDIBuilderInsertDeclareBefore(Builder: DIBuilderRef, Val: ValueRef, VarInfo: DIVariable, + AddrOps: *const i64, + AddrOpsCount: c_uint, InsertBefore: ValueRef) -> ValueRef; pub fn LLVMDIBuilderCreateEnumerator(Builder: DIBuilderRef, Name: *const c_char, Val: c_ulonglong) - -> ValueRef; + -> DIEnumerator; pub fn LLVMDIBuilderCreateEnumerationType(Builder: DIBuilderRef, - Scope: ValueRef, + Scope: DIScope, Name: *const c_char, - File: ValueRef, + File: DIFile, LineNumber: c_uint, SizeInBits: c_ulonglong, AlignInBits: c_ulonglong, - Elements: ValueRef, - ClassType: ValueRef) - -> ValueRef; + Elements: DIArray, + ClassType: DIType) + -> DIType; pub fn LLVMDIBuilderCreateUnionType(Builder: DIBuilderRef, - Scope: ValueRef, + Scope: DIScope, Name: *const c_char, - File: ValueRef, + File: DIFile, LineNumber: c_uint, SizeInBits: c_ulonglong, AlignInBits: c_ulonglong, Flags: c_uint, - Elements: ValueRef, + Elements: DIArray, RunTimeLang: c_uint, UniqueId: *const c_char) - -> ValueRef; + -> DIType; pub fn LLVMSetUnnamedAddr(GlobalVar: ValueRef, UnnamedAddr: Bool); pub fn LLVMDIBuilderCreateTemplateTypeParameter(Builder: DIBuilderRef, - Scope: ValueRef, + Scope: DIScope, Name: *const c_char, - Ty: ValueRef, - File: ValueRef, + Ty: DIType, + File: DIFile, LineNo: c_uint, ColumnNo: c_uint) - -> ValueRef; - - pub fn LLVMDIBuilderCreateOpDeref(IntType: TypeRef) -> ValueRef; + -> DITemplateTypeParameter; - pub fn LLVMDIBuilderCreateOpPlus(IntType: TypeRef) -> ValueRef; + pub fn LLVMDIBuilderCreateOpDeref() -> i64; - pub fn LLVMDIBuilderCreateComplexVariable(Builder: DIBuilderRef, - Tag: c_uint, - Scope: ValueRef, - Name: *const c_char, - File: ValueRef, - LineNo: c_uint, - Ty: ValueRef, - AddrOps: *const ValueRef, - AddrOpsCount: c_uint, - ArgNo: c_uint) - -> ValueRef; + pub fn LLVMDIBuilderCreateOpPlus() -> i64; pub fn LLVMDIBuilderCreateNameSpace(Builder: DIBuilderRef, - Scope: ValueRef, + Scope: DIScope, Name: *const c_char, - File: ValueRef, + File: DIFile, LineNo: c_uint) - -> ValueRef; + -> DINameSpace; + + pub fn LLVMDIBuilderCreateDebugLocation(Context: ContextRef, + Line: c_uint, + Column: c_uint, + Scope: DIScope, + InlinedAt: MetadataRef) + -> ValueRef; - pub fn LLVMDICompositeTypeSetTypeArray(CompositeType: ValueRef, TypeArray: ValueRef); + pub fn LLVMDICompositeTypeSetTypeArray(Builder: DIBuilderRef, + CompositeType: DIType, + TypeArray: DIArray); pub fn LLVMWriteTypeToString(Type: TypeRef, s: RustStringRef); pub fn LLVMWriteValueToString(value_ref: ValueRef, s: RustStringRef); diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 14e80c6c8ef..c398ff72f50 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -79,7 +79,7 @@ impl<'v> Visitor<'v> for ParentVisitor { // Enum variants are parented to the enum definition itself because // they inherit privacy ast::ItemEnum(ref def, _) => { - for variant in def.variants.iter() { + for variant in &def.variants { // The parent is considered the enclosing enum because the // enum will dictate the privacy visibility of this variant // instead. @@ -93,7 +93,7 @@ impl<'v> Visitor<'v> for ParentVisitor { // parent all the methods to the trait to indicate that they're // private. ast::ItemTrait(_, _, _, ref methods) if item.vis != ast::Public => { - for m in methods.iter() { + for m in methods { match *m { ast::ProvidedMethod(ref m) => { self.parents.insert(m.id, item.id); @@ -139,7 +139,7 @@ impl<'v> Visitor<'v> for ParentVisitor { // While we have the id of the struct definition, go ahead and parent // all the fields. - for field in s.fields.iter() { + for field in &s.fields { self.parents.insert(field.node.id, self.curparent); } visit::walk_struct_def(self, s) @@ -233,7 +233,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { // Enum variants inherit from their parent, so if the enum is // public all variants are public unless they're explicitly priv ast::ItemEnum(ref def, _) if public_first => { - for variant in def.variants.iter() { + for variant in &def.variants { self.exported_items.insert(variant.node.id); } } @@ -278,7 +278,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { }); if public_ty || public_trait { - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref method) => { let meth_public = @@ -299,7 +299,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { // Default methods on traits are all public so long as the trait // is public ast::ItemTrait(_, _, _, ref methods) if public_first => { - for method in methods.iter() { + for method in methods { match *method { ast::ProvidedMethod(ref m) => { debug!("provided {}", m.id); @@ -359,7 +359,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { // crate module gets processed as well. if self.prev_exported { assert!(self.export_map.contains_key(&id), "wut {}", id); - for export in self.export_map[id].iter() { + for export in &self.export_map[id] { if is_local(export.def_id) { self.reexports.insert(export.def_id.node); } @@ -837,7 +837,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> { match vpath.node { ast::ViewPathSimple(..) | ast::ViewPathGlob(..) => {} ast::ViewPathList(ref prefix, ref list) => { - for pid in list.iter() { + for pid in list { match pid.node { ast::PathListIdent { id, name } => { debug!("privacy - ident item {}", id); @@ -898,7 +898,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> { ast::ExprStruct(_, ref fields, _) => { match ty::expr_ty(self.tcx, expr).sty { ty::ty_struct(id, _) => { - for field in (*fields).iter() { + for field in &(*fields) { self.check_field(expr.span, id, NamedField(field.ident.node)); } @@ -906,7 +906,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> { ty::ty_enum(_, _) => { match self.tcx.def_map.borrow()[expr.id].clone() { def::DefVariant(_, variant_id, _) => { - for field in fields.iter() { + for field in fields { self.check_field(expr.span, variant_id, NamedField(field.ident.node)); } @@ -971,7 +971,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> { ast::PatStruct(_, ref fields, _) => { match ty::pat_ty(self.tcx, pattern).sty { ty::ty_struct(id, _) => { - for field in fields.iter() { + for field in fields { self.check_field(pattern.span, id, NamedField(field.node.ident)); } @@ -979,7 +979,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> { ty::ty_enum(_, _) => { match self.tcx.def_map.borrow().get(&pattern.id) { Some(&def::DefVariant(_, variant_id, _)) => { - for field in fields.iter() { + for field in fields { self.check_field(pattern.span, variant_id, NamedField(field.node.ident)); } @@ -1091,7 +1091,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { check_inherited(item.span, item.vis, "visibility qualifiers have no effect on trait \ impls"); - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref m) => { check_inherited(m.span, m.pe_vis(), ""); @@ -1112,7 +1112,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { } ast::ItemEnum(ref def, _) => { - for v in def.variants.iter() { + for v in &def.variants { match v.node.vis { ast::Public => { if item.vis == ast::Public { @@ -1126,7 +1126,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { } ast::ItemTrait(_, _, _, ref methods) => { - for m in methods.iter() { + for m in methods { match *m { ast::ProvidedMethod(ref m) => { check_inherited(m.span, m.pe_vis(), @@ -1157,7 +1157,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { } } let check_struct = |&: def: &ast::StructDef| { - for f in def.fields.iter() { + for f in &def.fields { match f.node.kind { ast::NamedField(_, p) => check_inherited(tcx, f.span, p), ast::UnnamedField(..) => {} @@ -1167,7 +1167,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { check_inherited(tcx, item.span, item.vis); match item.node { ast::ItemImpl(_, _, _, _, _, ref impl_items) => { - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref m) => { check_inherited(tcx, m.span, m.pe_vis()); @@ -1177,12 +1177,12 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { } } ast::ItemForeignMod(ref fm) => { - for i in fm.items.iter() { + for i in &fm.items { check_inherited(tcx, i.span, i.vis); } } ast::ItemEnum(ref def, _) => { - for v in def.variants.iter() { + for v in &def.variants { check_inherited(tcx, v.span, v.node.vis); } } @@ -1190,7 +1190,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { ast::ItemStruct(ref def, _) => check_struct(&**def), ast::ItemTrait(_, _, _, ref methods) => { - for m in methods.iter() { + for m in methods { match *m { ast::RequiredMethod(..) => {} ast::ProvidedMethod(ref m) => check_inherited(tcx, m.span, @@ -1302,7 +1302,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> { return } - for bound in bounds.iter() { + for bound in &**bounds { self.check_ty_param_bound(bound) } } @@ -1371,7 +1371,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> { match *trait_ref { None => { - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref method) => { visit::walk_method_helper(self, &**method) @@ -1400,7 +1400,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> { // impl Public<Private> { ... }. Any public static // methods will be visible as `Public::foo`. let mut found_pub_static = false; - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref method) => { if method.pe_explicit_self().node == @@ -1439,15 +1439,15 @@ impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> { } fn visit_generics(&mut self, generics: &ast::Generics) { - for ty_param in generics.ty_params.iter() { - for bound in ty_param.bounds.iter() { + for ty_param in &*generics.ty_params { + for bound in &*ty_param.bounds { self.check_ty_param_bound(bound) } } - for predicate in generics.where_clause.predicates.iter() { + for predicate in &generics.where_clause.predicates { match predicate { &ast::WherePredicate::BoundPredicate(ref bound_pred) => { - for bound in bound_pred.bounds.iter() { + for bound in &*bound_pred.bounds { self.check_ty_param_bound(bound) } } diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 65bd83d7937..a503398d484 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -223,8 +223,8 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { token::get_name(name))[]); { let r = child.span_for_namespace(ns); - for sp in r.iter() { - self.session.span_note(*sp, + if let Some(sp) = r { + self.session.span_note(sp, &format!("first definition of {} `{}` here", namespace_error_to_string(duplicate_type), token::get_name(name))[]); @@ -238,7 +238,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { fn block_needs_anonymous_module(&mut self, block: &Block) -> bool { // Check each statement. - for statement in block.stmts.iter() { + for statement in &block.stmts { match statement.node { StmtDecl(ref declaration, _) => { match declaration.node { @@ -338,7 +338,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { } } - for source_item in source_items.iter() { + for source_item in source_items { let (module_path, name) = match source_item.node { PathListIdent { name, .. } => (module_path.clone(), name.name), @@ -477,7 +477,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { let module = name_bindings.get_module(); - for variant in (*enum_definition).variants.iter() { + for variant in &(*enum_definition).variants { self.build_reduced_graph_for_variant( &**variant, local_def(item.id), @@ -591,7 +591,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { }; // For each implementation item... - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { MethodImplItem(ref method) => { // Add the method to the module. @@ -675,7 +675,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { let def_id = local_def(item.id); // Add the names of all the items to the trait info. - for trait_item in items.iter() { + for trait_item in items { let (name, kind) = match *trait_item { ast::RequiredMethod(_) | ast::ProvidedMethod(_) => { @@ -926,7 +926,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { let trait_item_def_ids = csearch::get_trait_item_def_ids(&self.session.cstore, def_id); - for trait_item_def_id in trait_item_def_ids.iter() { + for trait_item_def_id in &trait_item_def_ids { let (trait_item_name, trait_item_kind) = csearch::get_trait_item_name_and_kind( &self.session.cstore, @@ -1082,7 +1082,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { // Add each static method to the module. let new_parent = type_module; - for method_info in methods.iter() { + for method_info in methods { let name = method_info.name; debug!("(building reduced graph for \ external crate) creating \ diff --git a/src/librustc_resolve/check_unused.rs b/src/librustc_resolve/check_unused.rs index 97370112ab4..a239c73c110 100644 --- a/src/librustc_resolve/check_unused.rs +++ b/src/librustc_resolve/check_unused.rs @@ -136,7 +136,7 @@ impl<'a, 'b, 'v, 'tcx> Visitor<'v> for UnusedImportCheckVisitor<'a, 'b, 'tcx> { } ViewPathList(_, ref list) => { - for i in list.iter() { + for i in list { self.finalize_import(i.node.id(), i.span); } } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index f0711903579..a5fb57eadc4 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1031,7 +1031,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { self.current_module = orig_module; build_reduced_graph::populate_module_if_necessary(self, &module_); - for (_, child_node) in module_.children.borrow().iter() { + for (_, child_node) in &*module_.children.borrow() { match child_node.get_module_if_available() { None => { // Nothing to do. @@ -1042,7 +1042,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } } - for (_, child_module) in module_.anonymous_children.borrow().iter() { + for (_, child_module) in &*module_.anonymous_children.borrow() { self.resolve_imports_for_module_subtree(child_module.clone()); } } @@ -1087,7 +1087,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { fn names_to_string(&self, names: &[Name]) -> String { let mut first = true; let mut result = String::new(); - for name in names.iter() { + for name in names { if first { first = false } else { @@ -1596,7 +1596,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // Add all resolved imports from the containing module. let import_resolutions = containing_module.import_resolutions.borrow(); - for (ident, target_import_resolution) in import_resolutions.iter() { + for (ident, target_import_resolution) in &*import_resolutions { debug!("(resolving glob import) writing module resolution \ {} into `{}`", token::get_name(*ident), @@ -1657,7 +1657,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // Add all children from the containing module. build_reduced_graph::populate_module_if_necessary(self, &containing_module); - for (&name, name_bindings) in containing_module.children.borrow().iter() { + for (&name, name_bindings) in &*containing_module.children.borrow() { self.merge_import_resolution(module_, containing_module.clone(), import_directive, @@ -1667,7 +1667,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } // Add external module children from the containing module. - for (&name, module) in containing_module.external_module_children.borrow().iter() { + for (&name, module) in &*containing_module.external_module_children.borrow() { let name_bindings = Rc::new(Resolver::create_name_bindings_from_module(module.clone())); self.merge_import_resolution(module_, @@ -2519,7 +2519,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // Descend into children and anonymous children. build_reduced_graph::populate_module_if_necessary(self, &module_); - for (_, child_node) in module_.children.borrow().iter() { + for (_, child_node) in &*module_.children.borrow() { match child_node.get_module_if_available() { None => { // Continue. @@ -2530,7 +2530,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } } - for (_, module_) in module_.anonymous_children.borrow().iter() { + for (_, module_) in &*module_.anonymous_children.borrow() { self.report_unresolved_imports(module_.clone()); } } @@ -2609,7 +2609,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { DlDef(d @ DefLocal(_)) => { let node_id = d.def_id().node; let mut def = d; - for rib in ribs.iter() { + for rib in ribs { match rib.kind { NormalRibKind => { // Nothing to do. Continue. @@ -2680,7 +2680,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } DlDef(def @ DefTyParam(..)) | DlDef(def @ DefSelfTy(..)) => { - for rib in ribs.iter() { + for rib in ribs { match rib.kind { NormalRibKind | ClosureRibKind(..) => { // Nothing to do. Continue. @@ -2795,8 +2795,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // enum item: resolve all the variants' discrs, // then resolve the ty params ItemEnum(ref enum_def, ref generics) => { - for variant in (*enum_def).variants.iter() { - for dis_expr in variant.node.disr_expr.iter() { + for variant in &(*enum_def).variants { + if let Some(ref dis_expr) = variant.node.disr_expr { // resolve the discriminator expr // as a constant self.with_constant_rib(|this| { @@ -2863,7 +2863,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { this.resolve_type_parameter_bounds(item.id, bounds, TraitDerivation); - for trait_item in (*trait_items).iter() { + for trait_item in &(*trait_items) { // Create a new rib for the trait_item-specific type // parameters. // @@ -2885,7 +2885,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { this.resolve_where_clause(&ty_m.generics .where_clause); - for argument in ty_m.decl.inputs.iter() { + for argument in &ty_m.decl.inputs { this.resolve_type(&*argument.ty); } @@ -2929,7 +2929,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ItemForeignMod(ref foreign_module) => { self.with_scope(Some(name), |this| { - for foreign_item in foreign_module.items.iter() { + for foreign_item in &foreign_module.items { match foreign_item.node { ForeignItemFn(_, ref generics) => { this.with_type_parameter_rib( @@ -3075,7 +3075,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } Some(declaration) => { let mut bindings_list = HashMap::new(); - for argument in declaration.inputs.iter() { + for argument in &declaration.inputs { this.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list); @@ -3103,14 +3103,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { fn resolve_type_parameters(&mut self, type_parameters: &OwnedSlice<TyParam>) { - for type_parameter in type_parameters.iter() { + for type_parameter in &**type_parameters { self.resolve_type_parameter(type_parameter); } } fn resolve_type_parameter(&mut self, type_parameter: &TyParam) { - for bound in type_parameter.bounds.iter() { + for bound in &*type_parameter.bounds { self.resolve_type_parameter_bound(type_parameter.id, bound, TraitBoundingTypeParameter); } @@ -3124,7 +3124,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { id: NodeId, type_parameter_bounds: &OwnedSlice<TyParamBound>, reference_type: TraitReferenceType) { - for type_parameter_bound in type_parameter_bounds.iter() { + for type_parameter_bound in &**type_parameter_bounds { self.resolve_type_parameter_bound(id, type_parameter_bound, reference_type); } @@ -3193,12 +3193,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) { - for predicate in where_clause.predicates.iter() { + for predicate in &where_clause.predicates { match predicate { &ast::WherePredicate::BoundPredicate(ref bound_pred) => { self.resolve_type(&*bound_pred.bounded_ty); - for bound in bound_pred.bounds.iter() { + for bound in &*bound_pred.bounds { self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound, TraitBoundingTypeParameter); } @@ -3236,7 +3236,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { this.resolve_where_clause(&generics.where_clause); // Resolve fields. - for field in fields.iter() { + for field in fields { this.resolve_type(&*field.node.ty); } }); @@ -3320,7 +3320,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { this.resolve_type(self_type); this.with_current_self_type(self_type, |this| { - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { MethodImplItem(ref method) => { // If this is a trait impl, ensure the method @@ -3375,7 +3375,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { fn check_trait_item(&self, name: Name, span: Span) { // If there is a TraitRef in scope for an impl, then the method must be in the trait. - for &(did, ref trait_ref) in self.current_trait_ref.iter() { + if let Some((did, ref trait_ref)) = self.current_trait_ref { if self.trait_item_map.get(&(name, did)).is_none() { let path_str = self.path_names_to_string(&trait_ref.path); self.resolve_error(span, @@ -3442,7 +3442,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { for (i, p) in arm.pats.iter().enumerate() { let map_i = self.binding_mode_map(&**p); - for (&key, &binding_0) in map_0.iter() { + for (&key, &binding_0) in &map_0 { match map_i.get(&key) { None => { self.resolve_error( @@ -3465,7 +3465,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } } - for (&key, &binding) in map_i.iter() { + for (&key, &binding) in &map_i { if !map_0.contains_key(&key) { self.resolve_error( binding.span, @@ -3482,7 +3482,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { self.value_ribs.push(Rib::new(NormalRibKind)); let mut bindings_list = HashMap::new(); - for pattern in arm.pats.iter() { + for pattern in &arm.pats { self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list); } @@ -3513,7 +3513,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // Check for imports appearing after non-item statements. let mut found_non_item = false; - for statement in block.stmts.iter() { + for statement in &block.stmts { if let ast::StmtDecl(ref declaration, _) = statement.node { if let ast::DeclItem(ref i) = declaration.node { match i.node { @@ -3607,10 +3607,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { TyQPath(ref qpath) => { self.resolve_type(&*qpath.self_type); self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath); - for ty in qpath.item_path.parameters.types().into_iter() { + for ty in qpath.item_path.parameters.types() { self.resolve_type(&**ty); } - for binding in qpath.item_path.parameters.bindings().into_iter() { + for binding in qpath.item_path.parameters.bindings() { self.resolve_type(&*binding.ty); } } @@ -4365,7 +4365,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let mut values: Vec<uint> = Vec::new(); for rib in this.value_ribs.iter().rev() { - for (&k, _) in rib.bindings.iter() { + for (&k, _) in &rib.bindings { maybes.push(token::get_name(k)); values.push(uint::MAX); } @@ -4640,7 +4640,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { build_reduced_graph::populate_module_if_necessary(self, &search_module); { - for (_, child_names) in search_module.children.borrow().iter() { + for (_, child_names) in &*search_module.children.borrow() { let def = match child_names.def_for_namespace(TypeNS) { Some(def) => def, None => continue @@ -4656,7 +4656,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } // Look for imports. - for (_, import) in search_module.import_resolutions.borrow().iter() { + for (_, import) in &*search_module.import_resolutions.borrow() { let target = match import.target_for_namespace(TypeNS) { None => continue, Some(target) => target, @@ -4766,13 +4766,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { debug!("Children:"); build_reduced_graph::populate_module_if_necessary(self, &module_); - for (&name, _) in module_.children.borrow().iter() { + for (&name, _) in &*module_.children.borrow() { debug!("* {}", token::get_name(name)); } debug!("Import resolutions:"); let import_resolutions = module_.import_resolutions.borrow(); - for (&name, import_resolution) in import_resolutions.iter() { + for (&name, import_resolution) in &*import_resolutions { let value_repr; match import_resolution.target_for_namespace(ValueNS) { None => { value_repr = "".to_string(); } diff --git a/src/librustc_resolve/record_exports.rs b/src/librustc_resolve/record_exports.rs index 67bcf152eb7..5d025f40d32 100644 --- a/src/librustc_resolve/record_exports.rs +++ b/src/librustc_resolve/record_exports.rs @@ -80,7 +80,7 @@ impl<'a, 'b, 'tcx> ExportRecorder<'a, 'b, 'tcx> { self.record_exports_for_module(&*module_); build_reduced_graph::populate_module_if_necessary(self.resolver, &module_); - for (_, child_name_bindings) in module_.children.borrow().iter() { + for (_, child_name_bindings) in &*module_.children.borrow() { match child_name_bindings.get_module_if_available() { None => { // Nothing to do. @@ -91,7 +91,7 @@ impl<'a, 'b, 'tcx> ExportRecorder<'a, 'b, 'tcx> { } } - for (_, child_module) in module_.anonymous_children.borrow().iter() { + for (_, child_module) in &*module_.anonymous_children.borrow() { self.record_exports_for_module_subtree(child_module.clone()); } } @@ -133,12 +133,12 @@ impl<'a, 'b, 'tcx> ExportRecorder<'a, 'b, 'tcx> { fn add_exports_for_module(&mut self, exports: &mut Vec<Export>, module_: &Module) { - for (name, importresolution) in module_.import_resolutions.borrow().iter() { + for (name, importresolution) in &*module_.import_resolutions.borrow() { if !importresolution.is_public { continue } let xs = [TypeNS, ValueNS]; - for &ns in xs.iter() { + for &ns in &xs { match importresolution.target_for_namespace(ns) { Some(target) => { debug!("(computing exports) maybe export '{}'", diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index c97d9090441..be55ab9fda3 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -194,7 +194,7 @@ fn symbol_hash<'tcx>(tcx: &ty::ctxt<'tcx>, symbol_hasher.input_str(&link_meta.crate_name[]); symbol_hasher.input_str("-"); symbol_hasher.input_str(link_meta.crate_hash.as_str()); - for meta in tcx.sess.crate_metadata.borrow().iter() { + for meta in &*tcx.sess.crate_metadata.borrow() { symbol_hasher.input_str(&meta[]); } symbol_hasher.input_str("-"); @@ -265,7 +265,7 @@ pub fn sanitize(s: &str) -> String { return result; } -pub fn mangle<PI: Iterator<Item=PathElem>>(mut path: PI, +pub fn mangle<PI: Iterator<Item=PathElem>>(path: PI, hash: Option<&str>) -> String { // Follow C++ namespace-mangling style, see // http://en.wikipedia.org/wiki/Name_mangling for more info. @@ -370,7 +370,7 @@ pub fn link_binary(sess: &Session, outputs: &OutputFilenames, crate_name: &str) -> Vec<Path> { let mut out_filenames = Vec::new(); - for &crate_type in sess.crate_types.borrow().iter() { + for &crate_type in &*sess.crate_types.borrow() { if invalid_output_for_target(sess, crate_type) { sess.bug(&format!("invalid output type `{:?}` for target os `{}`", crate_type, sess.opts.target_triple)[]); @@ -535,7 +535,7 @@ fn link_rlib<'a>(sess: &'a Session, let mut ab = ArchiveBuilder::create(config); ab.add_file(obj_filename).unwrap(); - for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() { + for &(ref l, kind) in &*sess.cstore.get_used_libraries().borrow() { match kind { cstore::NativeStatic => { ab.add_native_library(&l[]).unwrap(); @@ -721,7 +721,7 @@ fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) { let crates = sess.cstore.get_used_crates(cstore::RequireStatic); let mut all_native_libs = vec![]; - for &(cnum, ref path) in crates.iter() { + for &(cnum, ref path) in &crates { let ref name = sess.cstore.get_crate_data(cnum).name; let p = match *path { Some(ref p) => p.clone(), None => { @@ -740,13 +740,13 @@ fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) { let _ = ab.build(); if !all_native_libs.is_empty() { - sess.warn("link against the following native artifacts when linking against \ + sess.note("link against the following native artifacts when linking against \ this static library"); sess.note("the order and any duplication can be significant on some platforms, \ and so may need to be preserved"); } - for &(kind, ref lib) in all_native_libs.iter() { + for &(kind, ref lib) in &all_native_libs { let name = match kind { cstore::NativeStatic => "static library", cstore::NativeUnknown => "library", @@ -1055,10 +1055,10 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) { let libs = sess.cstore.get_used_libraries(); let libs = libs.borrow(); - let mut staticlibs = libs.iter().filter_map(|&(ref l, kind)| { + let staticlibs = libs.iter().filter_map(|&(ref l, kind)| { if kind == cstore::NativeStatic {Some(l)} else {None} }); - let mut others = libs.iter().filter(|&&(_, kind)| { + let others = libs.iter().filter(|&&(_, kind)| { kind != cstore::NativeStatic }); @@ -1133,7 +1133,7 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, // crates. let deps = sess.cstore.get_used_crates(cstore::RequireDynamic); - for &(cnum, _) in deps.iter() { + for &(cnum, _) in &deps { // We may not pass all crates through to the linker. Some crates may // appear statically in an existing dylib, meaning we'll pick up all the // symbols from the dylib. @@ -1275,9 +1275,9 @@ fn add_upstream_native_libraries(cmd: &mut Command, sess: &Session) { // we're just getting an ordering of crate numbers, we're not worried about // the paths. let crates = sess.cstore.get_used_crates(cstore::RequireStatic); - for (cnum, _) in crates.into_iter() { + for (cnum, _) in crates { let libs = csearch::get_native_libraries(&sess.cstore, cnum); - for &(kind, ref lib) in libs.iter() { + for &(kind, ref lib) in &libs { match kind { cstore::NativeUnknown => { cmd.arg(format!("-l{}", *lib)); diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index 5fcf0be4c67..38c68bc9fa4 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -34,7 +34,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, } // Make sure we actually can run LTO - for crate_type in sess.crate_types.borrow().iter() { + for crate_type in &*sess.crate_types.borrow() { match *crate_type { config::CrateTypeExecutable | config::CrateTypeStaticlib => {} _ => { @@ -48,7 +48,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, // load the bitcode from the archive. Then merge it into the current LLVM // module that we've got. let crates = sess.cstore.get_used_crates(cstore::RequireStatic); - for (cnum, path) in crates.into_iter() { + for (cnum, path) in crates { let name = sess.cstore.get_crate_data(cnum).name.clone(); let path = match path { Some(p) => p, diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 9b195486d5d..5312d2ca1dd 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -100,7 +100,7 @@ impl SharedEmitter { fn dump(&mut self, handler: &Handler) { let mut buffer = self.buffer.lock().unwrap(); - for diag in buffer.iter() { + for diag in &*buffer { match diag.code { Some(ref code) => { handler.emit_with_code(None, @@ -452,7 +452,7 @@ unsafe fn optimize_and_codegen(cgcx: &CodegenContext, config.no_builtins); } - for pass in config.passes.iter() { + for pass in &config.passes { let pass = CString::from_slice(pass.as_bytes()); if !llvm::LLVMRustAddPass(mpm, pass.as_ptr()) { cgcx.handler.warn(format!("unknown pass {:?}, ignoring", @@ -597,7 +597,7 @@ pub fn run_passes(sess: &Session, modules_config.emit_bc = true; } - for output_type in output_types.iter() { + for output_type in output_types { match *output_type { config::OutputTypeBitcode => { modules_config.emit_bc = true; }, config::OutputTypeLlvmAssembly => { modules_config.emit_ir = true; }, @@ -761,7 +761,7 @@ pub fn run_passes(sess: &Session, // Otherwise, we produced it only as a temporary output, and will need // to get rid of it. let mut user_wants_bitcode = false; - for output_type in output_types.iter() { + for output_type in output_types { match *output_type { config::OutputTypeBitcode => { user_wants_bitcode = true; @@ -941,7 +941,7 @@ fn run_work_multithreaded(sess: &Session, } let mut panicked = false; - for rx in futures.into_iter() { + for rx in futures { match rx.recv() { Ok(()) => {}, Err(_) => { @@ -1015,7 +1015,7 @@ unsafe fn configure_llvm(sess: &Session) { // FIXME #21627 disable faulty FastISel on AArch64 (even for -O0) if sess.target.target.arch.as_slice() == "aarch64" { add("-fast-isel=0"); } - for arg in sess.opts.cg.llvm_args.iter() { + for arg in &sess.opts.cg.llvm_args { add(&(*arg)[]); } } diff --git a/src/librustc_trans/lib.rs b/src/librustc_trans/lib.rs index c46c2b7e6dd..94a1d4dd5b2 100644 --- a/src/librustc_trans/lib.rs +++ b/src/librustc_trans/lib.rs @@ -23,8 +23,6 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap - #![feature(alloc)] #![feature(box_syntax)] #![feature(collections)] @@ -32,8 +30,8 @@ #![feature(hash)] #![feature(int_uint)] #![feature(io)] +#![feature(env)] #![feature(libc)] -#![feature(os)] #![feature(path)] #![feature(quote)] #![feature(rustc_diagnostic_macros)] diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index fbeaae1d1df..7758039e40a 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -34,7 +34,7 @@ use middle::ty::{self, Ty}; use std::cell::Cell; use std::old_io::{self, File, fs}; -use std::os; +use std::env; use syntax::ast_util::{self, PostExpansionMethod}; use syntax::ast::{self, NodeId, DefId}; @@ -113,7 +113,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { error!("Mis-calculated spans for path '{}'. \ Found {} spans, expected {}. Found spans:", path_to_string(path), spans.len(), path.segments.len()); - for s in spans.iter() { + for s in &spans { let loc = self.sess.codemap().lookup_char_pos(s.lo); error!(" '{}' in {}, line {}", self.span.snippet(*s), loc.file.name, loc.line); @@ -204,7 +204,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { return; } let sub_paths = &sub_paths[..len-2]; - for &(ref span, ref qualname) in sub_paths.iter() { + for &(ref span, ref qualname) in sub_paths { self.fmt.sub_mod_ref_str(path.span, *span, &qualname[], @@ -264,13 +264,13 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) { - for arg in formals.iter() { + for arg in formals { assert!(self.collected_paths.len() == 0 && !self.collecting); self.collecting = true; self.visit_pat(&*arg.pat); self.collecting = false; let span_utils = self.span.clone(); - for &(id, ref p, _, _) in self.collected_paths.iter() { + for &(id, ref p, _, _) in &self.collected_paths { let typ = ppaux::ty_to_string(&self.analysis.ty_cx, (*self.analysis.ty_cx.node_types.borrow())[id]); // get the span only for the name of the variable (I hope the path is only ever a @@ -389,7 +389,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.process_formals(&method.pe_fn_decl().inputs, qualname); // walk arg and return types - for arg in method.pe_fn_decl().inputs.iter() { + for arg in &method.pe_fn_decl().inputs { self.visit_ty(&*arg.ty); } @@ -493,7 +493,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.process_formals(&decl.inputs, &qualname[]); // walk arg and return types - for arg in decl.inputs.iter() { + for arg in &decl.inputs { self.visit_ty(&*arg.ty); } @@ -580,7 +580,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { &val[]); // fields - for field in def.fields.iter() { + for field in &def.fields { self.process_struct_field_def(field, &qualname[], item.id); self.visit_ty(&*field.node.ty); } @@ -605,7 +605,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { &format!("Could not find subspan for enum {}", enum_name)[]), } - for variant in enum_definition.variants.iter() { + for variant in &enum_definition.variants { let name = get_ident(variant.node.name); let name = name.get(); let mut qualname = enum_name.clone(); @@ -623,7 +623,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { &enum_name[], &val[], item.id); - for arg in args.iter() { + for arg in args { self.visit_ty(&*arg.ty); } } @@ -642,7 +642,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { &val[], item.id); - for field in struct_def.fields.iter() { + for field in &struct_def.fields { self.process_struct_field_def(field, qualname.as_slice(), variant.node.id); self.visit_ty(&*field.node.ty); } @@ -701,7 +701,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } self.process_generic_params(type_parameters, item.span, "", item.id); - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref method) => { visit::walk_method_helper(self, &**method) @@ -729,7 +729,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { &val[]); // super-traits - for super_bound in trait_refs.iter() { + for super_bound in &**trait_refs { let trait_ref = match *super_bound { ast::TraitTyParamBound(ref trait_ref, _) => { trait_ref @@ -759,7 +759,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { // walk generics and methods self.process_generic_params(generics, item.span, &qualname[], item.id); - for method in methods.iter() { + for method in methods { self.visit_trait_item(method) } } @@ -912,11 +912,11 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { _ => None }; - for field in fields.iter() { + for field in fields { match struct_def { Some(struct_def) => { let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def); - for f in fields.iter() { + for f in &fields { if generated_code(field.ident.span) { continue; } @@ -1010,10 +1010,10 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.span.snippet(p.span))[]); } }; - for &Spanned { node: ref field, span } in fields.iter() { + for &Spanned { node: ref field, span } in fields { let sub_span = self.span.span_for_first_ident(span); let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def); - for f in fields.iter() { + for f in fields { if f.name == field.ident.name { self.fmt.ref_str(recorder::VarRef, span, @@ -1104,7 +1104,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { let glob_map = &self.analysis.glob_map; let glob_map = glob_map.as_ref().unwrap(); if glob_map.contains_key(&item.id) { - for n in glob_map[item.id].iter() { + for n in &glob_map[item.id] { if name_string.len() > 0 { name_string.push_str(", "); } @@ -1122,7 +1122,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { self.write_sub_paths(path, true); } ast::ViewPathList(ref path, ref list) => { - for plid in list.iter() { + for plid in list { match plid.node { ast::PathListIdent { id, .. } => { match self.lookup_type_ref(id) { @@ -1208,8 +1208,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { } fn visit_generics(&mut self, generics: &ast::Generics) { - for param in generics.ty_params.iter() { - for bound in param.bounds.iter() { + for param in &*generics.ty_params { + for bound in &*param.bounds { if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { self.process_trait_ref(&trait_ref.trait_ref); } @@ -1270,7 +1270,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { scope_id); // walk arg and return types - for arg in method_type.decl.inputs.iter() { + for arg in &method_type.decl.inputs { self.visit_ty(&*arg.ty); } @@ -1349,7 +1349,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { match *ty { ty::ty_struct(def_id, _) => { let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id); - for f in fields.iter() { + for f in &fields { if f.name == ident.node.name { let sub_span = self.span.span_for_last_ident(ex.span); self.fmt.ref_str(recorder::VarRef, @@ -1404,7 +1404,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { self.process_formals(&decl.inputs, &id[]); // walk arg and return types - for arg in decl.inputs.iter() { + for arg in &decl.inputs { self.visit_ty(&*arg.ty); } @@ -1435,7 +1435,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { fn visit_arm(&mut self, arm: &ast::Arm) { assert!(self.collected_paths.len() == 0 && !self.collecting); self.collecting = true; - for pattern in arm.pats.iter() { + for pattern in &arm.pats { // collect paths from the arm's patterns self.visit_pat(&**pattern); } @@ -1443,7 +1443,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { // This is to get around borrow checking, because we need mut self to call process_path. let mut paths_to_process = vec![]; // process collected paths - for &(id, ref p, ref immut, ref_kind) in self.collected_paths.iter() { + for &(id, ref p, ref immut, ref_kind) in &self.collected_paths { let def_map = self.analysis.ty_cx.def_map.borrow(); if !def_map.contains_key(&id) { self.sess.span_bug(p.span, @@ -1477,7 +1477,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { *def) } } - for &(id, ref path, ref_kind) in paths_to_process.iter() { + for &(id, ref path, ref_kind) in &paths_to_process { self.process_path(id, path.span, path, ref_kind); } self.collecting = false; @@ -1508,7 +1508,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { let value = self.span.snippet(l.span); - for &(id, ref p, ref immut, _) in self.collected_paths.iter() { + for &(id, ref p, ref immut, _) in &self.collected_paths { let value = if *immut { value.to_string() } else { "<mutable>".to_string() }; let types = self.analysis.ty_cx.node_types.borrow(); let typ = ppaux::ty_to_string(&self.analysis.ty_cx, (*types)[id]); @@ -1551,9 +1551,9 @@ pub fn process_crate(sess: &Session, info!("Dumping crate {}", cratename); // find a path to dump our data to - let mut root_path = match os::getenv("DXR_RUST_TEMP_FOLDER") { - Some(val) => Path::new(val), - None => match odir { + let mut root_path = match env::var_string("DXR_RUST_TEMP_FOLDER") { + Ok(val) => Path::new(val), + Err(..) => match odir { Some(val) => val.join("dxr"), None => Path::new("dxr-temp"), }, diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index b66e2770815..52fe8797592 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -366,7 +366,7 @@ impl<'a, 'p, 'blk, 'tcx> Repr<'tcx> for Match<'a, 'p, 'blk, 'tcx> { } fn has_nested_bindings(m: &[Match], col: uint) -> bool { - for br in m.iter() { + for br in m { match br.pats[col].node { ast::PatIdent(_, _, Some(_)) => return true, _ => () @@ -561,7 +561,7 @@ fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let tcx = bcx.tcx(); let mut found: Vec<Opt> = vec![]; - for br in m.iter() { + for br in m { let cur = br.pats[col]; let opt = match cur.node { ast::PatLit(ref l) => ConstantValue(ConstantExpr(&**l)), @@ -827,7 +827,7 @@ fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, bindings_map: &BindingsMap<'tcx>, cs: Option<cleanup::ScopeId>) -> Block<'blk, 'tcx> { - for (&ident, &binding_info) in bindings_map.iter() { + for (&ident, &binding_info) in bindings_map { let llval = match binding_info.trmode { // By value mut binding for a copy type: load from the ptr // into the matched value and copy to our alloca @@ -883,7 +883,7 @@ fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr)); let val = val.to_llbool(bcx); - for (_, &binding_info) in data.bindings_map.iter() { + for (_, &binding_info) in &data.bindings_map { if let TrByCopy(llbinding) = binding_info.trmode { call_lifetime_end(bcx, llbinding); } @@ -891,7 +891,7 @@ fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, with_cond(bcx, Not(bcx, val, guard_expr.debug_loc()), |bcx| { // Guard does not match: remove all bindings from the lllocals table - for (_, &binding_info) in data.bindings_map.iter() { + for (_, &binding_info) in &data.bindings_map { call_lifetime_end(bcx, binding_info.llmatch); bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id); } @@ -949,7 +949,7 @@ fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } None => { let data = &m[0].data; - for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() { + for &(ref ident, ref value_ptr) in &m[0].bound_ptrs { let llmatch = data.bindings_map[*ident].llmatch; call_lifetime_start(bcx, llmatch); Store(bcx, *value_ptr, llmatch); @@ -1055,7 +1055,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, Variant(_, ref repr, _) => { let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val); kind = the_kind; - for &tval in val_opt.iter() { test_val = tval; } + if let Some(tval) = val_opt { test_val = tval; } } SliceLengthEqual(_) | SliceLengthGreaterOrEqual(_, _) => { let (_, len) = tvec::get_base_and_len(bcx, val, left_ty); @@ -1064,7 +1064,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, } } } - for o in opts.iter() { + for o in &opts { match *o { ConstantRange(_, _) => { kind = Compare; break }, SliceLengthGreaterOrEqual(_, _) => { kind = CompareSliceLength; break }, @@ -1410,7 +1410,7 @@ fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>, compile_submatch(bcx, &matches[], &[discr_datum.val], &chk, has_default); let mut arm_cxs = Vec::new(); - for arm_data in arm_datas.iter() { + for arm_data in &arm_datas { let mut bcx = arm_data.bodycx; // insert bindings into the lllocals map and add cleanups @@ -1623,7 +1623,7 @@ fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, }); } - for inner_pat in inner.iter() { + if let Some(ref inner_pat) = *inner { bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope); } } @@ -1639,7 +1639,7 @@ fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, &*repr, vinfo.disr_val, val); - for sub_pat in sub_pats.iter() { + if let Some(ref sub_pat) = *sub_pats { for (i, &argval) in args.vals.iter().enumerate() { bcx = bind_irrefutable_pat(bcx, &*sub_pat[i], argval, cleanup_scope); @@ -1673,7 +1673,7 @@ fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let pat_ty = node_id_type(bcx, pat.id); let pat_repr = adt::represent_type(bcx.ccx(), pat_ty); expr::with_field_tys(tcx, pat_ty, Some(pat.id), |discr, field_tys| { - for f in fields.iter() { + for f in fields { let ix = ty::field_idx_strict(tcx, f.node.ident.name, field_tys); let fldptr = adt::trans_field_ptr(bcx, &*pat_repr, val, discr, ix); diff --git a/src/librustc_trans/trans/adt.rs b/src/librustc_trans/trans/adt.rs index 1deb07e1ba0..b99622ce911 100644 --- a/src/librustc_trans/trans/adt.rs +++ b/src/librustc_trans/trans/adt.rs @@ -285,7 +285,7 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, // alignment of the type. let (_, align) = union_size_and_align(fields.as_slice()); let mut use_align = true; - for st in fields.iter() { + for st in &fields { // Get the first non-zero-sized field let field = st.fields.iter().skip(1).filter(|ty| { let t = type_of::sizing_type_of(cx, **ty); @@ -519,7 +519,7 @@ fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntTyp cx.tcx().sess.bug("range_to_inttype: found ReprPacked on an enum"); } } - for &ity in attempts.iter() { + for &ity in attempts { if bounds_usable(cx, ity, bounds) { return ity; } @@ -563,7 +563,7 @@ fn ensure_struct_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, packed: bool, scapegoat: Ty<'tcx>) { let mut offset = 0; - for &llty in fields.iter() { + for &llty in fields { // Invariant: offset < ccx.obj_size_bound() <= 1<<61 if !packed { let type_align = machine::llalign_of_min(ccx, llty); @@ -1097,7 +1097,7 @@ fn compute_struct_field_offsets<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let mut offsets = vec!(); let mut offset = 0; - for &ty in st.fields.iter() { + for &ty in &st.fields { let llty = type_of::sizing_type_of(ccx, ty); if !st.packed { let type_align = type_of::align_of(ccx, ty); diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index a7afa17ab72..9e561fc883b 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -350,7 +350,7 @@ pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId, // don't do this then linker errors can be generated where the linker // complains that one object files has a thread local version of the // symbol and another one doesn't. - for attr in ty::get_attrs(ccx.tcx(), did).iter() { + for attr in &*ty::get_attrs(ccx.tcx(), did) { if attr.check_name("thread_local") { llvm::set_thread_local(c, true); } @@ -442,7 +442,7 @@ pub fn set_llvm_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: Val InlineNone => { /* fallthrough */ } } - for attr in attrs.iter() { + for attr in attrs { let mut used = true; match attr.name().get() { "no_stack_check" => unset_split_stack(llfn), @@ -765,7 +765,7 @@ pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>, n_variants); let next_cx = fcx.new_temp_block("enum-iter-next"); - for variant in (*variants).iter() { + for variant in &(*variants) { let variant_cx = fcx.new_temp_block( &format!("enum-iter-variant-{}", @@ -970,7 +970,7 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, if need_invoke(bcx) { debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb); - for &llarg in llargs.iter() { + for &llarg in llargs { debug!("arg: {}", bcx.val_to_string(llarg)); } let normal_bcx = bcx.fcx.new_temp_block("normal-return"); @@ -986,7 +986,7 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, return (llresult, normal_bcx); } else { debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb); - for &llarg in llargs.iter() { + for &llarg in llargs { debug!("arg: {}", bcx.val_to_string(llarg)); } @@ -1830,7 +1830,7 @@ pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>, vec![ty::mk_tup(ccx.tcx(), monomorphized_arg_types)] } }; - for monomorphized_arg_type in monomorphized_arg_types.iter() { + for monomorphized_arg_type in &monomorphized_arg_types { debug!("trans_closure: monomorphized_arg_type: {}", ty_to_string(ccx.tcx(), *monomorphized_arg_type)); } @@ -1908,7 +1908,7 @@ pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>, // This somewhat improves single-stepping experience in debugger. unsafe { let llreturn = fcx.llreturn.get(); - for &llreturn in llreturn.iter() { + if let Some(llreturn) = llreturn { llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb); } } @@ -2019,7 +2019,11 @@ pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, let bcx = match dest { expr::SaveIn(_) => bcx, expr::Ignore => { - glue::drop_ty(bcx, llresult, result_ty, debug_loc) + let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc); + if !type_is_zero_size(ccx, result_ty) { + call_lifetime_end(bcx, llresult); + } + bcx } }; @@ -2109,7 +2113,7 @@ fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, let avar = adt::represent_type(ccx, ty); match *avar { adt::General(_, ref variants, _) => { - for var in variants.iter() { + for var in variants { let mut size = 0; for field in var.fields.iter().skip(1) { // skip the discriminant @@ -2382,7 +2386,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { // and control visibility. pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) { let _icx = push_ctxt("trans_mod"); - for item in m.items.iter() { + for item in &m.items { trans_item(ccx, &**item); } } @@ -3161,7 +3165,7 @@ pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>) stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| { insns_b.cmp(&insns_a) }); - for tuple in stats.fn_stats.borrow().iter() { + for tuple in &*stats.fn_stats.borrow() { match *tuple { (ref name, insns) => { println!("{} insns, {}", insns, *name); @@ -3170,7 +3174,7 @@ pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>) } } if shared_ccx.sess().count_llvm_insns() { - for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() { + for (k, v) in &*shared_ccx.stats().llvm_insns.borrow() { println!("{:7} {}", *v, *k); } } diff --git a/src/librustc_trans/trans/basic_block.rs b/src/librustc_trans/trans/basic_block.rs index d3ff432b5e4..f11c3154274 100644 --- a/src/librustc_trans/trans/basic_block.rs +++ b/src/librustc_trans/trans/basic_block.rs @@ -16,12 +16,7 @@ use std::iter::{Filter, Map}; #[derive(Copy)] pub struct BasicBlock(pub BasicBlockRef); -pub type Preds = Map< - Value, - BasicBlock, - Filter<Value, Users, fn(&Value) -> bool>, - fn(Value) -> BasicBlock, ->; +pub type Preds = Map<Filter<Users, fn(&Value) -> bool>, fn(Value) -> BasicBlock>; /// Wrapper for LLVM BasicBlockRef impl BasicBlock { diff --git a/src/librustc_trans/trans/cabi_aarch64.rs b/src/librustc_trans/trans/cabi_aarch64.rs index ce1cf54919c..5d1e6d2c9e8 100644 --- a/src/librustc_trans/trans/cabi_aarch64.rs +++ b/src/librustc_trans/trans/cabi_aarch64.rs @@ -150,7 +150,7 @@ pub fn compute_abi_info(ccx: &CrateContext, rty: Type, ret_def: bool) -> FnType { let mut arg_tys = Vec::new(); - for &aty in atys.iter() { + for &aty in atys { let ty = classify_arg_ty(ccx, aty); arg_tys.push(ty); } diff --git a/src/librustc_trans/trans/cabi_arm.rs b/src/librustc_trans/trans/cabi_arm.rs index ac32ce49511..50014230df6 100644 --- a/src/librustc_trans/trans/cabi_arm.rs +++ b/src/librustc_trans/trans/cabi_arm.rs @@ -186,7 +186,7 @@ pub fn compute_abi_info(ccx: &CrateContext, }; let mut arg_tys = Vec::new(); - for &aty in atys.iter() { + for &aty in atys { let ty = classify_arg_ty(ccx, aty, align_fn); arg_tys.push(ty); } diff --git a/src/librustc_trans/trans/cabi_mips.rs b/src/librustc_trans/trans/cabi_mips.rs index af7956b46be..fecd1a9013b 100644 --- a/src/librustc_trans/trans/cabi_mips.rs +++ b/src/librustc_trans/trans/cabi_mips.rs @@ -176,7 +176,7 @@ pub fn compute_abi_info(ccx: &CrateContext, let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; - for aty in atys.iter() { + for aty in atys { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; diff --git a/src/librustc_trans/trans/cabi_powerpc.rs b/src/librustc_trans/trans/cabi_powerpc.rs index c3b0026de98..9583158a0e2 100644 --- a/src/librustc_trans/trans/cabi_powerpc.rs +++ b/src/librustc_trans/trans/cabi_powerpc.rs @@ -171,7 +171,7 @@ pub fn compute_abi_info(ccx: &CrateContext, let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; - for aty in atys.iter() { + for aty in atys { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; diff --git a/src/librustc_trans/trans/cabi_x86.rs b/src/librustc_trans/trans/cabi_x86.rs index 32f6eb060c0..028d20f3084 100644 --- a/src/librustc_trans/trans/cabi_x86.rs +++ b/src/librustc_trans/trans/cabi_x86.rs @@ -60,7 +60,7 @@ pub fn compute_abi_info(ccx: &CrateContext, ret_ty = ArgType::direct(rty, None, None, attr); } - for &t in atys.iter() { + for &t in atys { let ty = match t.kind() { Struct => { let size = llsize_of_alloc(ccx, t); diff --git a/src/librustc_trans/trans/cabi_x86_64.rs b/src/librustc_trans/trans/cabi_x86_64.rs index c0ab0d24dab..2484e74e193 100644 --- a/src/librustc_trans/trans/cabi_x86_64.rs +++ b/src/librustc_trans/trans/cabi_x86_64.rs @@ -151,7 +151,7 @@ fn classify_ty(ty: Type) -> Vec<RegClass> { } fn all_mem(cls: &mut [RegClass]) { - for elt in cls.iter_mut() { + for elt in cls { *elt = Memory; } } @@ -195,7 +195,7 @@ fn classify_ty(ty: Type) -> Vec<RegClass> { off: uint, packed: bool) { let mut field_off = off; - for ty in tys.iter() { + for ty in tys { if !packed { field_off = align(field_off, *ty); } @@ -333,7 +333,7 @@ fn classify_ty(ty: Type) -> Vec<RegClass> { fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type { fn llvec_len(cls: &[RegClass]) -> uint { let mut len = 1; - for c in cls.iter() { + for c in cls { if *c != SSEUp { break; } @@ -413,7 +413,7 @@ pub fn compute_abi_info(ccx: &CrateContext, } let mut arg_tys = Vec::new(); - for t in atys.iter() { + for t in atys { let ty = x86_64_ty(ccx, *t, |cls| cls.is_pass_byval(), ByValAttribute); arg_tys.push(ty); } diff --git a/src/librustc_trans/trans/cabi_x86_win64.rs b/src/librustc_trans/trans/cabi_x86_win64.rs index 79e309dacaa..9b34c3bf262 100644 --- a/src/librustc_trans/trans/cabi_x86_win64.rs +++ b/src/librustc_trans/trans/cabi_x86_win64.rs @@ -38,7 +38,7 @@ pub fn compute_abi_info(ccx: &CrateContext, ret_ty = ArgType::direct(rty, None, None, attr); } - for &t in atys.iter() { + for &t in atys { let ty = match t.kind() { Struct => { match llsize_of_alloc(ccx, t) { diff --git a/src/librustc_trans/trans/callee.rs b/src/librustc_trans/trans/callee.rs index 5f3cb01d762..5f383d54a68 100644 --- a/src/librustc_trans/trans/callee.rs +++ b/src/librustc_trans/trans/callee.rs @@ -1045,7 +1045,7 @@ pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>, })); assert_eq!(arg_tys.len(), 1 + rhs.len()); - for (rhs, rhs_id) in rhs.into_iter() { + for (rhs, rhs_id) in rhs { llargs.push(unpack_result!(bcx, { trans_arg_datum(bcx, arg_tys[1], rhs, arg_cleanup_scope, diff --git a/src/librustc_trans/trans/cleanup.rs b/src/librustc_trans/trans/cleanup.rs index 096ea22eaac..ac76b52598d 100644 --- a/src/librustc_trans/trans/cleanup.rs +++ b/src/librustc_trans/trans/cleanup.rs @@ -72,7 +72,7 @@ impl<'blk, 'tcx: 'blk> fmt::Debug for CleanupScopeKind<'blk, 'tcx> { AstScopeKind(nid) => write!(f, "AstScopeKind({})", nid), LoopScopeKind(nid, ref blks) => { try!(write!(f, "LoopScopeKind({}, [", nid)); - for blk in blks.iter() { + for blk in blks { try!(write!(f, "{:p}, ", blk)); } write!(f, "])") diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index 5782b3987cb..b65d50095b3 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -515,7 +515,7 @@ impl<'a, 'tcx> FunctionContext<'a, 'tcx> { -> Block<'a, 'tcx> { let out = self.new_id_block("join", id); let mut reachable = false; - for bcx in in_cxs.iter() { + for bcx in in_cxs { if !bcx.unreachable.get() { build::Br(*bcx, out.llbb, DebugLoc::None); reachable = true; @@ -778,10 +778,6 @@ pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef { C_integral(Type::i32(ccx), i as u64, true) } -pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef { - C_integral(Type::i64(ccx), i as u64, true) -} - pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef { C_integral(Type::i64(ccx), i, false) } diff --git a/src/librustc_trans/trans/controlflow.rs b/src/librustc_trans/trans/controlflow.rs index c4388603145..651058a5674 100644 --- a/src/librustc_trans/trans/controlflow.rs +++ b/src/librustc_trans/trans/controlflow.rs @@ -96,7 +96,7 @@ pub fn trans_block<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(), b.id, b.span, true); fcx.push_ast_cleanup_scope(cleanup_debug_loc); - for s in b.stmts.iter() { + for s in &b.stmts { bcx = trans_stmt(bcx, &**s); } diff --git a/src/librustc_trans/trans/datum.rs b/src/librustc_trans/trans/datum.rs index dd4ef97b88d..39d17f45ffa 100644 --- a/src/librustc_trans/trans/datum.rs +++ b/src/librustc_trans/trans/datum.rs @@ -199,6 +199,9 @@ impl KindOps for Rvalue { -> Block<'blk, 'tcx> { // No cleanup is scheduled for an rvalue, so we don't have // to do anything after a move to cancel or duplicate it. + if self.is_by_ref() { + call_lifetime_end(bcx, _val); + } bcx } @@ -320,6 +323,7 @@ impl<'tcx> Datum<'tcx, Rvalue> { ByValue => DatumBlock::new(bcx, self), ByRef => { let llval = load_ty(bcx, self.val, self.ty); + call_lifetime_end(bcx, self.val); DatumBlock::new(bcx, Datum::new(llval, self.ty, Rvalue::new(ByValue))) } } diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index 258a6fb958d..66bb299273d 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -197,7 +197,7 @@ use metadata::csearch; use middle::subst::{self, Substs}; use trans::{self, adt, machine, type_of}; use trans::common::{self, NodeIdAndSpan, CrateContext, FunctionContext, Block, - C_bytes, C_i32, C_i64, NormalizingClosureTyper}; + C_bytes, NormalizingClosureTyper}; use trans::_match::{BindingInfo, TrByCopy, TrByMove, TrByRef}; use trans::monomorphize; use trans::type_::Type; @@ -375,7 +375,7 @@ impl<'tcx> TypeMap<'tcx> { }, ty::ty_tup(ref component_types) => { unique_type_id.push_str("tuple "); - for &component_type in component_types.iter() { + for &component_type in component_types { let component_type_id = self.get_unique_type_id_of_type(cx, component_type); let component_type_id = @@ -447,7 +447,7 @@ impl<'tcx> TypeMap<'tcx> { let sig = ty::erase_late_bound_regions(cx.tcx(), sig); - for ¶meter_type in sig.inputs.iter() { + for ¶meter_type in &sig.inputs { let parameter_type_id = self.get_unique_type_id_of_type(cx, parameter_type); let parameter_type_id = @@ -533,7 +533,7 @@ impl<'tcx> TypeMap<'tcx> { if tps.len() > 0 { output.push('<'); - for &type_parameter in tps.iter() { + for &type_parameter in tps { let param_type_id = type_map.get_unique_type_id_of_type(cx, type_parameter); let param_type_id = @@ -563,7 +563,7 @@ impl<'tcx> TypeMap<'tcx> { let sig = ty::erase_late_bound_regions(cx.tcx(), sig); - for ¶meter_type in sig.inputs.iter() { + for ¶meter_type in &sig.inputs { let parameter_type_id = self.get_unique_type_id_of_type(cx, parameter_type); let parameter_type_id = @@ -702,7 +702,7 @@ enum VariableAccess<'a> { DirectVariable { alloca: ValueRef }, // The llptr given is an alloca containing the start of some pointer chain // leading to the variable's content. - IndirectVariable { alloca: ValueRef, address_operations: &'a [ValueRef] } + IndirectVariable { alloca: ValueRef, address_operations: &'a [i64] } } enum VariableKind { @@ -928,10 +928,10 @@ pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, env_index); let address_operations = unsafe { - [llvm::LLVMDIBuilderCreateOpDeref(Type::i64(cx).to_ref()), - llvm::LLVMDIBuilderCreateOpPlus(Type::i64(cx).to_ref()), - C_i64(cx, byte_offset_of_var_in_env as i64), - llvm::LLVMDIBuilderCreateOpDeref(Type::i64(cx).to_ref())] + [llvm::LLVMDIBuilderCreateOpDeref(), + llvm::LLVMDIBuilderCreateOpPlus(), + byte_offset_of_var_in_env as i64, + llvm::LLVMDIBuilderCreateOpDeref()] }; let address_op_count = if captured_by_ref { @@ -969,7 +969,7 @@ pub fn create_match_binding_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let scope_metadata = scope_metadata(bcx.fcx, binding.id, binding.span); let aops = unsafe { - [llvm::LLVMDIBuilderCreateOpDeref(bcx.ccx().int_type().to_ref())] + [llvm::LLVMDIBuilderCreateOpDeref()] }; // Regardless of the actual type (`T`) we're always passed the stack slot (alloca) // for the binding. For ByRef bindings that's a `T*` but for ByMove bindings we @@ -1440,7 +1440,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, } // Arguments types - for arg in fn_decl.inputs.iter() { + for arg in &fn_decl.inputs { assert_type_for_node_id(cx, arg.pat.id, arg.pat.span); let arg_type = ty::node_id_to_type(cx.tcx(), arg.pat.id); let arg_type = monomorphize::apply_param_substs(cx.tcx(), @@ -1657,11 +1657,11 @@ fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, }; let name = CString::from_slice(name.get().as_bytes()); - let (var_alloca, var_metadata) = match variable_access { - DirectVariable { alloca } => ( - alloca, - unsafe { - llvm::LLVMDIBuilderCreateLocalVariable( + match (variable_access, [].as_slice()) { + (DirectVariable { alloca }, address_operations) | + (IndirectVariable {alloca, address_operations}, _) => { + let metadata = unsafe { + llvm::LLVMDIBuilderCreateVariable( DIB(cx), dwarf_tag, scope_metadata, @@ -1671,38 +1671,25 @@ fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, type_metadata, cx.sess().opts.optimize != config::No, 0, - argument_index) - } - ), - IndirectVariable { alloca, address_operations } => ( - alloca, - unsafe { - llvm::LLVMDIBuilderCreateComplexVariable( - DIB(cx), - dwarf_tag, - scope_metadata, - name.as_ptr(), - file_metadata, - loc.line as c_uint, - type_metadata, address_operations.as_ptr(), address_operations.len() as c_uint, argument_index) - } - ) - }; - - set_debug_location(cx, InternalDebugLocation::new(scope_metadata, + }; + set_debug_location(cx, InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize())); - unsafe { - let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd( - DIB(cx), - var_alloca, - var_metadata, - bcx.llbb); + unsafe { + let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd( + DIB(cx), + alloca, + metadata, + address_operations.as_ptr(), + address_operations.len() as c_uint, + bcx.llbb); - llvm::LLVMSetInstDebugLocation(trans::build::B(bcx).llbuilder, instr); + llvm::LLVMSetInstDebugLocation(trans::build::B(bcx).llbuilder, instr); + } + } } match variable_kind { @@ -2050,7 +2037,7 @@ fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, // The `Ty` values returned by `ty::struct_fields` can still contain // `ty_projection` variants, so normalize those away. - for field in fields.iter_mut() { + for field in &mut fields { field.mt.ty = monomorphize::normalize_associated_type(cx.tcx(), &field.mt.ty); } @@ -2674,7 +2661,7 @@ fn set_members_of_composite_type(cx: &CrateContext, unsafe { let type_array = create_DIArray(DIB(cx), &member_metadata[]); - llvm::LLVMDICompositeTypeSetTypeArray(composite_type_metadata, type_array); + llvm::LLVMDICompositeTypeSetTypeArray(DIB(cx), composite_type_metadata, type_array); } } @@ -2838,7 +2825,7 @@ fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, }); // regular arguments - for &argument_type in signature.inputs.iter() { + for &argument_type in &signature.inputs { signature_metadata.push(type_metadata(cx, argument_type, span)); } @@ -3108,12 +3095,14 @@ fn set_debug_location(cx: &CrateContext, debug_location: InternalDebugLocation) // Always set the column to zero like Clang and GCC let col = UNKNOWN_COLUMN_NUMBER; debug!("setting debug location to {} {}", line, col); - let elements = [C_i32(cx, line as i32), C_i32(cx, col as i32), - scope, ptr::null_mut()]; + unsafe { - metadata_node = llvm::LLVMMDNodeInContext(debug_context(cx).llcontext, - elements.as_ptr(), - elements.len() as c_uint); + metadata_node = llvm::LLVMDIBuilderCreateDebugLocation( + debug_context(cx).llcontext, + line as c_uint, + col as c_uint, + scope, + ptr::null_mut()); } } UnknownLocation => { @@ -3226,7 +3215,7 @@ fn create_scope_map(cx: &CrateContext, // Push argument identifiers onto the stack so arguments integrate nicely // with variable shadowing. - for arg in args.iter() { + for arg in args { pat_util::pat_bindings(def_map, &*arg.pat, |_, node_id, _, path1| { scope_stack.push(ScopeStackEntry { scope_metadata: fn_metadata, ident: Some(path1.node) }); @@ -3292,7 +3281,7 @@ fn create_scope_map(cx: &CrateContext, scope_map.insert(block.id, scope_stack.last().unwrap().scope_metadata); // The interesting things here are statements and the concluding expression. - for statement in block.stmts.iter() { + for statement in &block.stmts { scope_map.insert(ast_util::stmt_id(&**statement), scope_stack.last().unwrap().scope_metadata); @@ -3306,7 +3295,7 @@ fn create_scope_map(cx: &CrateContext, } } - for exp in block.expr.iter() { + if let Some(ref exp) = block.expr { walk_expr(cx, &**exp, scope_stack, scope_map); } } @@ -3321,7 +3310,7 @@ fn create_scope_map(cx: &CrateContext, walk_pattern(cx, &*local.pat, scope_stack, scope_map); - for exp in local.init.iter() { + if let Some(ref exp) = local.init { walk_expr(cx, &**exp, scope_stack, scope_map); } } @@ -3407,7 +3396,7 @@ fn create_scope_map(cx: &CrateContext, scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata); - for sub_pat in sub_pat_opt.iter() { + if let Some(ref sub_pat) = *sub_pat_opt { walk_pattern(cx, &**sub_pat, scope_stack, scope_map); } } @@ -3419,8 +3408,8 @@ fn create_scope_map(cx: &CrateContext, ast::PatEnum(_, ref sub_pats_opt) => { scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata); - for sub_pats in sub_pats_opt.iter() { - for p in sub_pats.iter() { + if let Some(ref sub_pats) = *sub_pats_opt { + for p in sub_pats { walk_pattern(cx, &**p, scope_stack, scope_map); } } @@ -3440,7 +3429,7 @@ fn create_scope_map(cx: &CrateContext, ast::PatTup(ref sub_pats) => { scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata); - for sub_pat in sub_pats.iter() { + for sub_pat in sub_pats { walk_pattern(cx, &**sub_pat, scope_stack, scope_map); } } @@ -3464,15 +3453,15 @@ fn create_scope_map(cx: &CrateContext, ast::PatVec(ref front_sub_pats, ref middle_sub_pats, ref back_sub_pats) => { scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata); - for sub_pat in front_sub_pats.iter() { + for sub_pat in front_sub_pats { walk_pattern(cx, &**sub_pat, scope_stack, scope_map); } - for sub_pat in middle_sub_pats.iter() { + if let Some(ref sub_pat) = *middle_sub_pats { walk_pattern(cx, &**sub_pat, scope_stack, scope_map); } - for sub_pat in back_sub_pats.iter() { + for sub_pat in back_sub_pats { walk_pattern(cx, &**sub_pat, scope_stack, scope_map); } } @@ -3534,7 +3523,7 @@ fn create_scope_map(cx: &CrateContext, ast::ExprVec(ref init_expressions) | ast::ExprTup(ref init_expressions) => { - for ie in init_expressions.iter() { + for ie in init_expressions { walk_expr(cx, &**ie, scope_stack, scope_map); } } @@ -3612,7 +3601,7 @@ fn create_scope_map(cx: &CrateContext, scope_stack, scope_map, |cx, scope_stack, scope_map| { - for &ast::Arg { pat: ref pattern, .. } in decl.inputs.iter() { + for &ast::Arg { pat: ref pattern, .. } in &decl.inputs { walk_pattern(cx, &**pattern, scope_stack, scope_map); } @@ -3623,13 +3612,13 @@ fn create_scope_map(cx: &CrateContext, ast::ExprCall(ref fn_exp, ref args) => { walk_expr(cx, &**fn_exp, scope_stack, scope_map); - for arg_exp in args.iter() { + for arg_exp in args { walk_expr(cx, &**arg_exp, scope_stack, scope_map); } } ast::ExprMethodCall(_, _, ref args) => { - for arg_exp in args.iter() { + for arg_exp in args { walk_expr(cx, &**arg_exp, scope_stack, scope_map); } } @@ -3642,7 +3631,7 @@ fn create_scope_map(cx: &CrateContext, // walk only one pattern per arm, as they all must contain the // same binding names. - for arm_ref in arms.iter() { + for arm_ref in arms { let arm_span = arm_ref.pats[0].span; with_new_scope(cx, @@ -3650,11 +3639,11 @@ fn create_scope_map(cx: &CrateContext, scope_stack, scope_map, |cx, scope_stack, scope_map| { - for pat in arm_ref.pats.iter() { + for pat in &arm_ref.pats { walk_pattern(cx, &**pat, scope_stack, scope_map); } - for guard_exp in arm_ref.guard.iter() { + if let Some(ref guard_exp) = arm_ref.guard { walk_expr(cx, &**guard_exp, scope_stack, scope_map) } @@ -3664,7 +3653,7 @@ fn create_scope_map(cx: &CrateContext, } ast::ExprStruct(_, ref fields, ref base_exp) => { - for &ast::Field { expr: ref exp, .. } in fields.iter() { + for &ast::Field { expr: ref exp, .. } in fields { walk_expr(cx, &**exp, scope_stack, scope_map); } @@ -3678,11 +3667,11 @@ fn create_scope_map(cx: &CrateContext, ref outputs, .. }) => { // inputs, outputs: Vec<(String, P<Expr>)> - for &(_, ref exp) in inputs.iter() { + for &(_, ref exp) in inputs { walk_expr(cx, &**exp, scope_stack, scope_map); } - for &(_, ref exp, _) in outputs.iter() { + for &(_, ref exp, _) in outputs { walk_expr(cx, &**exp, scope_stack, scope_map); } } @@ -3737,7 +3726,7 @@ fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, }, ty::ty_tup(ref component_types) => { output.push('('); - for &component_type in component_types.iter() { + for &component_type in component_types { push_debuginfo_type_name(cx, component_type, true, output); output.push_str(", "); } @@ -3802,7 +3791,7 @@ fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let sig = ty::erase_late_bound_regions(cx.tcx(), sig); if sig.inputs.len() > 0 { - for ¶meter_type in sig.inputs.iter() { + for ¶meter_type in &sig.inputs { push_debuginfo_type_name(cx, parameter_type, true, output); output.push_str(", "); } @@ -3848,7 +3837,7 @@ fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, def_id: ast::DefId, qualified: bool, output: &mut String) { - ty::with_path(cx.tcx(), def_id, |mut path| { + ty::with_path(cx.tcx(), def_id, |path| { if qualified { if def_id.krate == ast::LOCAL_CRATE { output.push_str(crate_root_namespace(cx)); diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index cf85389cd5b..bed43a5c838 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -1451,7 +1451,7 @@ pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, let custom_cleanup_scope = fcx.push_custom_cleanup_scope(); // First we trans the base, if we have one, to the dest - for base in optbase.iter() { + if let Some(base) = optbase { assert_eq!(discr, 0); match ty::expr_kind(bcx.tcx(), &*base.expr) { @@ -1461,7 +1461,7 @@ pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, ty::RvalueStmtExpr => bcx.tcx().sess.bug("unexpected expr kind for struct base expr"), _ => { let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base")); - for &(i, t) in base.fields.iter() { + for &(i, t) in &base.fields { let datum = base_datum.get_element( bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i)); assert!(type_is_sized(bcx.tcx(), datum.ty)); @@ -1485,7 +1485,7 @@ pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, // (i.e. avoid GEPi and `store`s to an alloca) . let mut vec_val = C_undef(llty); - for &(i, ref e) in fields.iter() { + for &(i, ref e) in fields { let block_datum = trans(bcx, &**e); bcx = block_datum.bcx; let position = C_uint(bcx.ccx(), i); @@ -1495,7 +1495,7 @@ pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, Store(bcx, vec_val, addr); } else { // Now, we just overwrite the fields we've explicitly specified - for &(i, ref e) in fields.iter() { + for &(i, ref e) in fields { let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i); let e_ty = expr_ty_adjusted(bcx, &**e); bcx = trans_into(bcx, &**e, SaveIn(dest)); diff --git a/src/librustc_trans/trans/foreign.rs b/src/librustc_trans/trans/foreign.rs index 6c017866ef0..00bb3036546 100644 --- a/src/librustc_trans/trans/foreign.rs +++ b/src/librustc_trans/trans/foreign.rs @@ -352,7 +352,7 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } arg_idx += 1; - for arg_ty in fn_type.arg_tys.iter() { + for arg_ty in &fn_type.arg_tys { if arg_ty.is_ignore() { continue; } @@ -453,7 +453,7 @@ fn gate_simd_ffi(tcx: &ty::ctxt, decl: &ast::FnDecl, ty: &ty::BareFnTy) { pub fn trans_foreign_mod(ccx: &CrateContext, foreign_mod: &ast::ForeignMod) { let _icx = push_ctxt("foreign::trans_foreign_mod"); - for foreign_item in foreign_mod.items.iter() { + for foreign_item in &foreign_mod.items { let lname = link_name(&**foreign_item); if let ast::ForeignItemFn(ref decl, _) = foreign_item.node { @@ -936,7 +936,7 @@ fn lltype_for_fn_from_foreign_types(ccx: &CrateContext, tys: &ForeignTypes) -> T } }; - for &arg_ty in tys.fn_ty.arg_tys.iter() { + for &arg_ty in &tys.fn_ty.arg_tys { if arg_ty.is_ignore() { continue; } @@ -987,7 +987,7 @@ fn add_argument_attributes(tys: &ForeignTypes, i += 1; - for &arg_ty in tys.fn_ty.arg_tys.iter() { + for &arg_ty in &tys.fn_ty.arg_tys { if arg_ty.is_ignore() { continue; } diff --git a/src/librustc_trans/trans/glue.rs b/src/librustc_trans/trans/glue.rs index 497237da38c..5d26daab5cd 100644 --- a/src/librustc_trans/trans/glue.rs +++ b/src/librustc_trans/trans/glue.rs @@ -572,7 +572,7 @@ pub fn emit_tydescs(ccx: &CrateContext) { // As of this point, allow no more tydescs to be created. ccx.finished_tydescs().set(true); let glue_fn_ty = Type::generic_glue_fn(ccx).ptr_to(); - for (_, ti) in ccx.tydescs().borrow().iter() { + for (_, ti) in &*ccx.tydescs().borrow() { // Each of the glue functions needs to be cast to a generic type // before being put into the tydesc because we only have a singleton // tydesc type. Then we'll recast each function to its real type when diff --git a/src/librustc_trans/trans/intrinsic.rs b/src/librustc_trans/trans/intrinsic.rs index 9bee2c5bbc6..6228043eeb1 100644 --- a/src/librustc_trans/trans/intrinsic.rs +++ b/src/librustc_trans/trans/intrinsic.rs @@ -92,7 +92,7 @@ pub fn get_simple_intrinsic(ccx: &CrateContext, item: &ast::ForeignItem) -> Opti /// the only intrinsic that needs such verification is `transmute`. pub fn check_intrinsics(ccx: &CrateContext) { let mut last_failing_id = None; - for transmute_restriction in ccx.tcx().transmute_restrictions.borrow().iter() { + for transmute_restriction in &*ccx.tcx().transmute_restrictions.borrow() { // Sometimes, a single call to transmute will push multiple // type pairs to test in order to exhaustively test the // possibility around a type parameter. If one of those fails, @@ -243,7 +243,8 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, dest }; - fcx.pop_custom_cleanup_scope(cleanup_scope); + fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean(); + fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope); return match dest { expr::SaveIn(d) => Result::new(bcx, d), @@ -268,7 +269,7 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, false, RustIntrinsic); - fcx.pop_custom_cleanup_scope(cleanup_scope); + fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean(); let call_debug_location = DebugLoc::At(call_info.id, call_info.span); @@ -276,9 +277,11 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, if name.get() == "abort" { let llfn = ccx.get_intrinsic(&("llvm.trap")); Call(bcx, llfn, &[], None, call_debug_location); + fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope); Unreachable(bcx); return Result::new(bcx, C_undef(Type::nil(ccx).ptr_to())); } else if name.get() == "unreachable" { + fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope); Unreachable(bcx); return Result::new(bcx, C_nil(ccx)); } @@ -765,6 +768,8 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, expr::SaveIn(_) => {} } + fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope); + Result::new(bcx, llresult) } diff --git a/src/librustc_trans/trans/meth.rs b/src/librustc_trans/trans/meth.rs index 335c639df90..f522024c2e7 100644 --- a/src/librustc_trans/trans/meth.rs +++ b/src/librustc_trans/trans/meth.rs @@ -65,7 +65,7 @@ pub fn trans_impl(ccx: &CrateContext, // items that we need to translate. if !generics.ty_params.is_empty() { let mut v = TransItemVisitor{ ccx: ccx }; - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref method) => { visit::walk_method_helper(&mut v, &**method); @@ -75,7 +75,7 @@ pub fn trans_impl(ccx: &CrateContext, } return; } - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref method) => { if method.pe_generics().ty_params.len() == 0 { diff --git a/src/librustc_trans/trans/monomorphize.rs b/src/librustc_trans/trans/monomorphize.rs index cc0d76efcf0..b3d388b0f02 100644 --- a/src/librustc_trans/trans/monomorphize.rs +++ b/src/librustc_trans/trans/monomorphize.rs @@ -333,7 +333,7 @@ pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T obligations.repr(tcx)); let mut fulfill_cx = traits::FulfillmentContext::new(); - for obligation in obligations.into_iter() { + for obligation in obligations { fulfill_cx.register_predicate_obligation(&infcx, obligation); } let result = drain_fulfillment_cx(DUMMY_SP, &infcx, &mut fulfill_cx, &result); diff --git a/src/librustc_trans/trans/tvec.rs b/src/librustc_trans/trans/tvec.rs index 844795b667b..66f603cbe07 100644 --- a/src/librustc_trans/trans/tvec.rs +++ b/src/librustc_trans/trans/tvec.rs @@ -263,7 +263,7 @@ pub fn write_content<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ast::ExprVec(ref elements) => { match dest { Ignore => { - for element in elements.iter() { + for element in elements { bcx = expr::trans_into(bcx, &**element, Ignore); } } diff --git a/src/librustc_trans/trans/type_of.rs b/src/librustc_trans/trans/type_of.rs index 6b6ca600a88..2243982c20d 100644 --- a/src/librustc_trans/trans/type_of.rs +++ b/src/librustc_trans/trans/type_of.rs @@ -84,7 +84,7 @@ pub fn untuple_arguments_if_necessary<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, match inputs[inputs.len() - 1].sty { ty::ty_tup(ref tupled_arguments) => { debug!("untuple_arguments_if_necessary(): untupling arguments"); - for &tupled_argument in tupled_arguments.iter() { + for &tupled_argument in tupled_arguments { result.push(tupled_argument); } } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 350227c6662..8809931cd80 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -373,7 +373,7 @@ fn create_substs_for_ast_path<'tcx>( } } - for param in ty_param_defs[supplied_ty_param_count..].iter() { + for param in &ty_param_defs[supplied_ty_param_count..] { match param.default { Some(default) => { // This is a default type parameter. @@ -537,7 +537,7 @@ pub fn instantiate_poly_trait_ref<'tcx>( instantiate_trait_ref(this, &shifted_rscope, &ast_trait_ref.trait_ref, self_ty, Some(&mut projections)); - for projection in projections.into_iter() { + for projection in projections { poly_projections.push(ty::Binder(projection)); } @@ -659,7 +659,7 @@ fn ast_path_to_trait_ref<'a,'tcx>( prohibit_projections(this.tcx(), assoc_bindings.as_slice()); } Some(ref mut v) => { - for binding in assoc_bindings.iter() { + for binding in &assoc_bindings { match ast_type_binding_to_projection_predicate(this, trait_ref.clone(), self_ty, binding) { Ok(pp) => { v.push(pp); } @@ -733,7 +733,7 @@ fn ast_type_binding_to_projection_predicate<'tcx>( // If converting for an object type, then remove the dummy-ty from `Self` now. // Yuckety yuck. if self_ty.is_none() { - for candidate in candidates.iter_mut() { + for candidate in &mut candidates { let mut dummy_substs = candidate.0.substs.clone(); assert!(dummy_substs.self_ty() == Some(dummy_self_ty)); dummy_substs.types.pop(SelfSpace); @@ -979,7 +979,7 @@ fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>, token::get_name(assoc_name), token::get_name(ty_param_name)); - for suitable_bound in suitable_bounds.iter() { + for suitable_bound in &suitable_bounds { span_note!(this.tcx().sess, ast_ty.span, "associated type `{}` could derive from `{}`", token::get_name(ty_param_name), @@ -1710,7 +1710,7 @@ pub fn partition_bounds<'a>(tcx: &ty::ctxt, let mut region_bounds = Vec::new(); let mut trait_bounds = Vec::new(); let mut trait_def_ids = DefIdMap(); - for ast_bound in ast_bounds.iter() { + for ast_bound in ast_bounds { match *ast_bound { ast::TraitTyParamBound(ref b, ast::TraitBoundModifier::None) => { match ::lookup_def_tcx(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) { diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index c4b7ffb8729..174a9029534 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -240,7 +240,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, // below for details. demand::eqtype(fcx, pat.span, expected, pat_ty); - for elt in before.iter() { + for elt in before { check_pat(pcx, &**elt, inner_ty); } if let Some(ref slice) = *slice { @@ -254,7 +254,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, }); check_pat(pcx, &**slice, slice_ty); } - for elt in after.iter() { + for elt in after { check_pat(pcx, &**elt, inner_ty); } } @@ -348,12 +348,12 @@ pub fn check_match<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // Typecheck the patterns first, so that we get types for all the // bindings. - for arm in arms.iter() { + for arm in arms { let mut pcx = pat_ctxt { fcx: fcx, map: pat_id_map(&tcx.def_map, &*arm.pats[0]), }; - for p in arm.pats.iter() { + for p in &arm.pats { check_pat(&mut pcx, &**p, discrim_ty); } } @@ -439,7 +439,7 @@ pub fn check_pat_struct<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, pat: &'tcx ast::Pat, "use of trait `{}` in a struct pattern", name); fcx.write_error(pat.id); - for field in fields.iter() { + for field in fields { check_pat(pcx, &*field.node.pat, tcx.types.err); } return; @@ -458,7 +458,7 @@ pub fn check_pat_struct<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, pat: &'tcx ast::Pat, "`{}` does not name a struct or a struct variant", name); fcx.write_error(pat.id); - for field in fields.iter() { + for field in fields { check_pat(pcx, &*field.node.pat, tcx.types.err); } return; @@ -540,7 +540,7 @@ pub fn check_pat_enum<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, fcx.write_error(pat.id); if let Some(subpats) = subpats { - for pat in subpats.iter() { + for pat in subpats { check_pat(pcx, &**pat, tcx.types.err); } } @@ -558,7 +558,7 @@ pub fn check_pat_enum<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, "this pattern has {} field{}, but the corresponding {} has no fields", subpats.len(), if subpats.len() == 1 {""} else {"s"}, kind_name); - for pat in subpats.iter() { + for pat in subpats { check_pat(pcx, &**pat, tcx.types.err); } } else { @@ -568,7 +568,7 @@ pub fn check_pat_enum<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, kind_name, arg_tys.len(), if arg_tys.len() == 1 {""} else {"s"}); - for pat in subpats.iter() { + for pat in subpats { check_pat(pcx, &**pat, tcx.types.err); } } @@ -598,7 +598,7 @@ pub fn check_struct_pat_fields<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, let mut used_fields = FnvHashMap(); // Typecheck each field. - for &Spanned { node: ref field, span } in fields.iter() { + for &Spanned { node: ref field, span } in fields { let field_type = match used_fields.entry(field.ident.name) { Occupied(occupied) => { span_err!(tcx.sess, span, E0025, diff --git a/src/librustc_typeck/check/assoc.rs b/src/librustc_typeck/check/assoc.rs index 0e0a9294640..377af080526 100644 --- a/src/librustc_typeck/check/assoc.rs +++ b/src/librustc_typeck/check/assoc.rs @@ -33,7 +33,7 @@ pub fn normalize_associated_types_in<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, debug!("normalize_associated_types_in: result={} predicates={}", result.repr(infcx.tcx), obligations.repr(infcx.tcx)); - for obligation in obligations.into_iter() { + for obligation in obligations { fulfillment_cx.register_predicate_obligation(infcx, obligation); } result diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index 8bac89ac184..04a3f423dce 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -353,7 +353,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { assert!(ty_substs_a.len() == ty_substs_b.len()); let mut result = None; - let mut tps = ty_substs_a.iter().zip(ty_substs_b.iter()).enumerate(); + let tps = ty_substs_a.iter().zip(ty_substs_b.iter()).enumerate(); for (i, (tp_a, tp_b)) in tps { if self.fcx.infcx().try(|_| self.subtype(*tp_a, *tp_b)).is_ok() { continue; diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 31b14ea3f3d..dc4d7d46647 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -248,7 +248,7 @@ pub fn compare_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>, let mut selcx = traits::SelectionContext::new(&infcx, &trait_param_env); - for predicate in impl_pred.fns.into_iter() { + for predicate in impl_pred.fns { let traits::Normalized { value: predicate, .. } = traits::normalize(&mut selcx, normalize_cause.clone(), &predicate); diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index e9ea0921bc9..a988fb4cc6e 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -134,7 +134,7 @@ pub fn probe<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // Create a list of simplified self types, if we can. let mut simplified_steps = Vec::new(); - for step in steps.iter() { + for step in &steps { match fast_reject::simplify_type(fcx.tcx(), step.self_ty, true) { None => { break; } Some(simplified_type) => { simplified_steps.push(simplified_type); } @@ -236,7 +236,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { fn assemble_inherent_candidates(&mut self) { let steps = self.steps.clone(); - for step in steps.iter() { + for step in &*steps { self.assemble_probe(step.self_ty); } } @@ -268,8 +268,8 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { // metadata if necessary. ty::populate_implementations_for_type_if_necessary(self.tcx(), def_id); - for impl_infos in self.tcx().inherent_impls.borrow().get(&def_id).iter() { - for &impl_def_id in impl_infos.iter() { + if let Some(impl_infos) = self.tcx().inherent_impls.borrow().get(&def_id) { + for &impl_def_id in &***impl_infos { self.assemble_inherent_impl_probe(impl_def_id); } } @@ -448,8 +448,8 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { { let mut duplicates = HashSet::new(); let opt_applicable_traits = self.fcx.ccx.trait_map.get(&expr_id); - for applicable_traits in opt_applicable_traits.into_iter() { - for &trait_did in applicable_traits.iter() { + if let Some(applicable_traits) = opt_applicable_traits { + for &trait_did in applicable_traits { if duplicates.insert(trait_did) { try!(self.assemble_extension_candidates_for_trait(trait_did)); } @@ -530,7 +530,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { Some(impls) => impls, }; - for &impl_def_id in impl_def_ids.borrow().iter() { + for &impl_def_id in &*impl_def_ids.borrow() { debug!("assemble_extension_candidates_for_trait_impl: trait_def_id={} impl_def_id={}", trait_def_id.repr(self.tcx()), impl_def_id.repr(self.tcx())); @@ -601,7 +601,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { // Check if there is an unboxed-closure self-type in the list of receivers. // If so, add "synthetic impls". let steps = self.steps.clone(); - for step in steps.iter() { + for step in &*steps { let (closure_def_id, _, _) = match step.self_ty.sty { ty::ty_closure(a, b, ref c) => (a, b, c), _ => continue, @@ -653,7 +653,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { method.repr(self.tcx()), method_index); - for step in self.steps.iter() { + for step in &*self.steps { debug!("assemble_projection_candidates: step={}", step.repr(self.tcx())); diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index c193e1ef483..70e5d44ca67 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -735,7 +735,7 @@ pub fn check_item<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx ast::Item) { None => { } } - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref m) => { check_method_body(ccx, &impl_pty.generics, &**m); @@ -750,7 +750,7 @@ pub fn check_item<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx ast::Item) { ast::ItemTrait(_, ref generics, _, ref trait_methods) => { check_trait_on_unimplemented(ccx, generics, it); let trait_def = ty::lookup_trait_def(ccx.tcx, local_def(it.id)); - for trait_method in trait_methods.iter() { + for trait_method in trait_methods { match *trait_method { RequiredMethod(..) => { // Nothing to do, since required methods don't have @@ -774,11 +774,11 @@ pub fn check_item<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx ast::Item) { } ast::ItemForeignMod(ref m) => { if m.abi == abi::RustIntrinsic { - for item in m.items.iter() { + for item in &m.items { check_intrinsic_type(ccx, &**item); } } else { - for item in m.items.iter() { + for item in &m.items { let pty = ty::lookup_item_type(ccx.tcx, local_def(item.id)); if !pty.generics.types.is_empty() { span_err!(ccx.tcx.sess, item.span, E0044, @@ -805,7 +805,7 @@ fn check_trait_on_unimplemented<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, a.check_name("rustc_on_unimplemented") }) { if let Some(ref istring) = attr.value_str() { - let mut parser = Parser::new(istring.get()); + let parser = Parser::new(istring.get()); let types = generics.ty_params.as_slice(); for token in parser { match token { @@ -879,7 +879,7 @@ fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // Check existing impl methods to see if they are both present in trait // and compatible with trait signature - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref impl_method) => { let impl_method_def_id = local_def(impl_method.id); @@ -969,7 +969,7 @@ fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // Check for missing items from trait let provided_methods = ty::provided_trait_methods(tcx, impl_trait_ref.def_id); let mut missing_methods = Vec::new(); - for trait_item in trait_items.iter() { + for trait_item in &*trait_items { match *trait_item { ty::MethodTraitItem(ref trait_method) => { let is_implemented = @@ -1341,7 +1341,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// ! gets replaced with (), unconstrained ints with i32, and unconstrained floats with f64. pub fn default_type_parameters(&self) { use middle::ty::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat, Neither}; - for (_, &mut ref ty) in self.inh.node_types.borrow_mut().iter_mut() { + for (_, &mut ref ty) in &mut *self.inh.node_types.borrow_mut() { let resolved = self.infcx().resolve_type_vars_if_possible(ty); if self.infcx().type_var_diverges(resolved) { demand::eqtype(self, codemap::DUMMY_SP, *ty, ty::mk_nil(self.tcx())); @@ -2321,7 +2321,7 @@ fn check_argument_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // of arguments when we typecheck the functions. This isn't really the // right way to do this. let xs = [false, true]; - for check_blocks in xs.iter() { + for check_blocks in &xs { let check_blocks = *check_blocks; debug!("check_blocks={}", check_blocks); @@ -2858,11 +2858,19 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, BinopAssignment => PreferMutLvalue, SimpleBinop => NoPreference }; - check_expr_with_lvalue_pref(fcx, &*lhs, lvalue_pref); + check_expr_with_lvalue_pref(fcx, lhs, lvalue_pref); // Callee does bot / err checking - let lhs_t = structurally_resolved_type(fcx, lhs.span, - fcx.expr_ty(&*lhs)); + let lhs_t = + structurally_resolve_type_or_else(fcx, lhs.span, fcx.expr_ty(lhs), || { + if ast_util::is_symmetric_binop(op.node) { + // Try RHS first + check_expr(fcx, &**rhs); + fcx.expr_ty(&**rhs) + } else { + fcx.tcx().types.err + } + }); if ty::type_is_integral(lhs_t) && ast_util::is_shift_binop(op.node) { // Shift is a special case: rhs must be uint, no matter what lhs is @@ -3101,7 +3109,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, let mut best_dist = name.len(); let fields = ty::lookup_struct_fields(tcx, id); let mut best = None; - for elem in fields.iter() { + for elem in &fields { let n = elem.name.as_str(); // ignore already set fields if skip.iter().any(|&x| x == n) { @@ -3199,14 +3207,14 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, let mut class_field_map = FnvHashMap(); let mut fields_found = 0; - for field in field_types.iter() { + for field in field_types { class_field_map.insert(field.name, (field.id, false)); } let mut error_happened = false; // Typecheck each field. - for field in ast_fields.iter() { + for field in ast_fields { let mut expected_field_type = tcx.types.err; let pair = class_field_map.get(&field.ident.node.name).map(|x| *x); @@ -3273,7 +3281,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, assert!(fields_found <= field_types.len()); if fields_found < field_types.len() { let mut missing_fields = Vec::new(); - for class_field in field_types.iter() { + for class_field in field_types { let name = class_field.name; let (_, seen) = class_field_map[name]; if !seen { @@ -3374,7 +3382,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, // Make sure to still write the types // otherwise we might ICE fcx.write_error(id); - for field in fields.iter() { + for field in fields { check_expr(fcx, &*field.expr); } match *base_expr { @@ -3628,10 +3636,10 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, constrain_path_type_parameters(fcx, expr); } ast::ExprInlineAsm(ref ia) => { - for &(_, ref input) in ia.inputs.iter() { + for &(_, ref input) in &ia.inputs { check_expr(fcx, &**input); } - for &(_, ref out, _) in ia.outputs.iter() { + for &(_, ref out, _) in &ia.outputs { check_expr(fcx, &**out); } fcx.write_nil(id); @@ -3764,14 +3772,14 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, let typ = match uty { Some(uty) => { - for e in args.iter() { + for e in args { check_expr_coercable_to_type(fcx, &**e, uty); } uty } None => { let t: Ty = fcx.infcx().next_ty_var(); - for e in args.iter() { + for e in args { check_expr_has_type(fcx, &**e, t); } t @@ -4270,7 +4278,7 @@ fn check_block_with_expected<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, let mut warned = false; let mut any_diverges = false; let mut any_err = false; - for s in blk.stmts.iter() { + for s in &blk.stmts { check_stmt(fcx, &**s); let s_id = ast_util::stmt_id(&**s); let s_ty = fcx.node_ty(s_id); @@ -4506,7 +4514,7 @@ pub fn check_enum_variants<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, let mut disr_vals: Vec<ty::Disr> = Vec::new(); let mut prev_disr_val: Option<ty::Disr> = None; - for v in vs.iter() { + for v in vs { // If the discriminant value is specified explicitly in the enum check whether the // initialization expression is valid, otherwise use the last value plus one. @@ -4838,7 +4846,7 @@ pub fn instantiate_path<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // variables. If the user provided some types, we may still need // to add defaults. If the user provided *too many* types, that's // a problem. - for &space in ParamSpace::all().iter() { + for &space in &ParamSpace::all() { adjust_type_parameters(fcx, span, space, type_defs, &mut substs); assert_eq!(substs.types.len(space), type_defs.len(space)); @@ -4870,13 +4878,13 @@ pub fn instantiate_path<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, fcx: &FnCtxt, segment: &ast::PathSegment) { - for typ in segment.parameters.types().iter() { + for typ in &segment.parameters.types() { span_err!(fcx.tcx().sess, typ.span, E0085, "type parameters may not appear here"); break; } - for lifetime in segment.parameters.lifetimes().iter() { + for lifetime in &segment.parameters.lifetimes() { span_err!(fcx.tcx().sess, lifetime.span, E0086, "lifetime parameters may not appear here"); break; @@ -5114,28 +5122,45 @@ pub fn instantiate_path<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, } } -// Resolves `typ` by a single level if `typ` is a type variable. If no -// resolution is possible, then an error is reported. -pub fn structurally_resolved_type<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, - sp: Span, - ty: Ty<'tcx>) - -> Ty<'tcx> +fn structurally_resolve_type_or_else<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, + sp: Span, + ty: Ty<'tcx>, + f: F) -> Ty<'tcx> + where F: Fn() -> Ty<'tcx> { let mut ty = fcx.resolve_type_vars_if_possible(ty); - // If not, error. if ty::type_is_ty_var(ty) { - fcx.type_error_message(sp, |_actual| { - "the type of this value must be known in this \ - context".to_string() - }, ty, None); - demand::suptype(fcx, sp, fcx.tcx().types.err, ty); - ty = fcx.tcx().types.err; + let alternative = f(); + + // If not, error. + if ty::type_is_ty_var(alternative) || ty::type_is_error(alternative) { + fcx.type_error_message(sp, |_actual| { + "the type of this value must be known in this context".to_string() + }, ty, None); + demand::suptype(fcx, sp, fcx.tcx().types.err, ty); + ty = fcx.tcx().types.err; + } else { + demand::suptype(fcx, sp, alternative, ty); + ty = alternative; + } } ty } +// Resolves `typ` by a single level if `typ` is a type variable. If no +// resolution is possible, then an error is reported. +pub fn structurally_resolved_type<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, + sp: Span, + ty: Ty<'tcx>) + -> Ty<'tcx> +{ + structurally_resolve_type_or_else(fcx, sp, ty, || { + fcx.tcx().types.err + }) +} + // Returns true if b contains a break that can exit from b pub fn may_break(cx: &ty::ctxt, id: ast::NodeId, b: &ast::Block) -> bool { // First: is there an unlabeled break immediately diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index f8c7055a003..94414d842c9 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -148,7 +148,7 @@ pub fn regionck_ensure_component_tys_wf<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, span: Span, component_tys: &[Ty<'tcx>]) { let mut rcx = Rcx::new(fcx, Repeating(0), SubjectNode::None); - for &component_ty in component_tys.iter() { + for &component_ty in component_tys { // Check that each type outlives the empty region. Since the // empty region is a subregion of all others, this can't fail // unless the type does not meet the well-formedness @@ -298,7 +298,7 @@ impl<'a, 'tcx> Rcx<'a, 'tcx> { .region_obligations(node_id) .to_vec(); - for r_o in region_obligations.iter() { + for r_o in ®ion_obligations { debug!("visit_region_obligations: r_o={}", r_o.repr(self.tcx())); let sup_type = self.resolve_type(r_o.sup_type); @@ -327,7 +327,7 @@ impl<'a, 'tcx> Rcx<'a, 'tcx> { debug!("relate_free_regions >>"); let tcx = self.tcx(); - for &ty in fn_sig_tys.iter() { + for &ty in fn_sig_tys { let ty = self.resolve_type(ty); debug!("relate_free_regions(t={})", ty.repr(tcx)); let body_scope = CodeExtent::from_node_id(body_id); @@ -337,7 +337,7 @@ impl<'a, 'tcx> Rcx<'a, 'tcx> { tcx, ty, body_scope); - for constraint in constraints.iter() { + for constraint in &constraints { debug!("constraint: {}", constraint.repr(tcx)); match *constraint { regionmanip::RegionSubRegionConstraint(_, @@ -424,7 +424,7 @@ fn visit_block(rcx: &mut Rcx, b: &ast::Block) { fn visit_arm(rcx: &mut Rcx, arm: &ast::Arm) { // see above - for p in arm.pats.iter() { + for p in &arm.pats { constrain_bindings_in_pat(&**p, rcx); } @@ -487,13 +487,13 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) { let has_method_map = rcx.fcx.inh.method_map.borrow().contains_key(&method_call); // Check any autoderefs or autorefs that appear. - for &adjustment in rcx.fcx.inh.adjustments.borrow().get(&expr.id).iter() { + if let Some(adjustment) = rcx.fcx.inh.adjustments.borrow().get(&expr.id) { debug!("adjustment={:?}", adjustment); match *adjustment { ty::AdjustDerefRef(ty::AutoDerefRef {autoderefs, autoref: ref opt_autoref}) => { let expr_ty = rcx.resolve_node_type(expr.id); constrain_autoderefs(rcx, expr, autoderefs, expr_ty); - for autoref in opt_autoref.iter() { + if let Some(ref autoref) = *opt_autoref { link_autoref(rcx, expr, autoderefs, autoref); // Require that the resulting region encompasses @@ -753,7 +753,7 @@ fn check_expr_fn_block(rcx: &mut Rcx, debug!("ensure_free_variable_types_outlive_closure_bound({}, {})", bounds.region_bound.repr(tcx), expr.repr(tcx)); - for freevar in freevars.iter() { + for freevar in freevars { let var_node_id = { let def_id = freevar.def.def_id(); assert!(def_id.krate == ast::LOCAL_CRATE); @@ -779,7 +779,7 @@ fn check_expr_fn_block(rcx: &mut Rcx, }; // Check that the type meets the criteria of the existential bounds: - for builtin_bound in bounds.builtin_bounds.iter() { + for builtin_bound in &bounds.builtin_bounds { let code = traits::ClosureCapture(var_node_id, expr.span, builtin_bound); let cause = traits::ObligationCause::new(freevar.span, rcx.fcx.body_id, code); rcx.fcx.register_builtin_bound(var_ty, builtin_bound, cause); @@ -802,7 +802,7 @@ fn check_expr_fn_block(rcx: &mut Rcx, let tcx = rcx.fcx.ccx.tcx; debug!("constrain_captured_variables({}, {})", region_bound.repr(tcx), expr.repr(tcx)); - for freevar in freevars.iter() { + for freevar in freevars { debug!("constrain_captured_variables: freevar.def={:?}", freevar.def); // Identify the variable being closed over and its node-id. @@ -854,7 +854,7 @@ fn constrain_callee(rcx: &mut Rcx, fn constrain_call<'a, I: Iterator<Item=&'a ast::Expr>>(rcx: &mut Rcx, call_expr: &ast::Expr, receiver: Option<&ast::Expr>, - mut arg_exprs: I, + arg_exprs: I, implicitly_ref_args: bool) { //! Invoked on every call site (i.e., normal calls, method calls, //! and overloaded operators). Constrains the regions which appear @@ -897,13 +897,13 @@ fn constrain_call<'a, I: Iterator<Item=&'a ast::Expr>>(rcx: &mut Rcx, } // as loop above, but for receiver - for r in receiver.iter() { + if let Some(r) = receiver { debug!("receiver: {}", r.repr(tcx)); type_of_node_must_outlive( rcx, infer::CallRcvr(r.span), r.id, callee_region); if implicitly_ref_args { - link_by_ref(rcx, &**r, callee_scope); + link_by_ref(rcx, &*r, callee_scope); } } } @@ -1079,8 +1079,8 @@ fn link_match(rcx: &Rcx, discr: &ast::Expr, arms: &[ast::Arm]) { let mc = mc::MemCategorizationContext::new(rcx.fcx); let discr_cmt = ignore_err!(mc.cat_expr(discr)); debug!("discr_cmt={}", discr_cmt.repr(rcx.tcx())); - for arm in arms.iter() { - for root_pat in arm.pats.iter() { + for arm in arms { + for root_pat in &arm.pats { link_pattern(rcx, mc, discr_cmt.clone(), &**root_pat); } } @@ -1092,7 +1092,7 @@ fn link_match(rcx: &Rcx, discr: &ast::Expr, arms: &[ast::Arm]) { fn link_fn_args(rcx: &Rcx, body_scope: CodeExtent, args: &[ast::Arg]) { debug!("regionck::link_fn_args(body_scope={:?})", body_scope); let mc = mc::MemCategorizationContext::new(rcx.fcx); - for arg in args.iter() { + for arg in args { let arg_ty = rcx.fcx.node_ty(arg.id); let re_scope = ty::ReScope(body_scope); let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty); @@ -1418,7 +1418,7 @@ fn type_must_outlive<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>, rcx.tcx(), ty, region); - for constraint in constraints.iter() { + for constraint in &constraints { debug!("constraint: {}", constraint.repr(rcx.tcx())); match *constraint { regionmanip::RegionSubRegionConstraint(None, r_a, r_b) => { @@ -1479,7 +1479,7 @@ fn generic_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, // The problem is that the type of `x` is `&'a A`. To be // well-formed, then, A must be lower-generic by `'a`, but we // don't know that this holds from first principles. - for &(ref r, ref p) in rcx.region_bound_pairs.iter() { + for &(ref r, ref p) in &rcx.region_bound_pairs { debug!("generic={} p={}", generic.repr(rcx.tcx()), p.repr(rcx.tcx())); diff --git a/src/librustc_typeck/check/regionmanip.rs b/src/librustc_typeck/check/regionmanip.rs index cbd51a880ce..4a0e2acc854 100644 --- a/src/librustc_typeck/check/regionmanip.rs +++ b/src/librustc_typeck/check/regionmanip.rs @@ -126,7 +126,7 @@ impl<'a, 'tcx> Wf<'a, 'tcx> { } ty::ty_tup(ref tuptys) => { - for &tupty in tuptys.iter() { + for &tupty in tuptys { self.accumulate_from_ty(tupty); } } @@ -236,7 +236,7 @@ impl<'a, 'tcx> Wf<'a, 'tcx> { // Variance of each type/region parameter. let variances = ty::item_variances(self.tcx, def_id); - for &space in ParamSpace::all().iter() { + for &space in &ParamSpace::all() { let region_params = substs.regions().get_slice(space); let region_variances = variances.regions.get_slice(space); let region_param_defs = generics.regions.get_slice(space); @@ -272,7 +272,7 @@ impl<'a, 'tcx> Wf<'a, 'tcx> { } } - for ®ion_bound in region_param_def.bounds.iter() { + for ®ion_bound in ®ion_param_def.bounds { // The type declared a constraint like // // 'b : 'a @@ -314,7 +314,7 @@ impl<'a, 'tcx> Wf<'a, 'tcx> { // Inspect bounds on this type parameter for any // region bounds. - for &r in type_param_def.bounds.region_bounds.iter() { + for &r in &type_param_def.bounds.region_bounds { self.stack.push((r, Some(ty))); self.accumulate_from_ty(type_param_ty); self.stack.pop().unwrap(); @@ -368,7 +368,7 @@ impl<'a, 'tcx> Wf<'a, 'tcx> { // And then, in turn, to be well-formed, the // `region_bound` that user specified must imply the // region bounds required from all of the trait types: - for &r_d in required_region_bounds.iter() { + for &r_d in &required_region_bounds { // Each of these is an instance of the `'c <= 'b` // constraint above self.out.push(RegionSubRegionConstraint(Some(ty), r_d, r_c)); diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index f7babadd41f..b52e01f9a7a 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -138,7 +138,7 @@ impl<'a,'tcx> SeedBorrowKind<'a,'tcx> { } ty::with_freevars(self.tcx(), expr.id, |freevars| { - for freevar in freevars.iter() { + for freevar in freevars { let var_node_id = freevar.def.local_node_id(); let upvar_id = ty::UpvarId { var_id: var_node_id, closure_expr_id: expr.id }; diff --git a/src/librustc_typeck/check/vtable.rs b/src/librustc_typeck/check/vtable.rs index 5cf71a9be6a..6f66010925e 100644 --- a/src/librustc_typeck/check/vtable.rs +++ b/src/librustc_typeck/check/vtable.rs @@ -142,7 +142,7 @@ pub fn check_object_safety<'tcx>(tcx: &ty::ctxt<'tcx>, ty::item_path_str(tcx, object_trait_ref.def_id())); let violations = traits::object_safety_violations(tcx, object_trait_ref.clone()); - for violation in violations.into_iter() { + for violation in violations { match violation { ObjectSafetyViolation::SizedSelf => { tcx.sess.span_note( @@ -221,7 +221,7 @@ pub fn register_object_cast_obligations<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // bounds attached to the object cast. (In other words, if the // object type is Foo+Send, this would create an obligation // for the Send check.) - for builtin_bound in object_trait.bounds.builtin_bounds.iter() { + for builtin_bound in &object_trait.bounds.builtin_bounds { fcx.register_builtin_bound( referent_ty, builtin_bound, @@ -231,7 +231,7 @@ pub fn register_object_cast_obligations<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // Create obligations for the projection predicates. let projection_bounds = object_trait.projection_bounds_with_self_ty(fcx.tcx(), referent_ty); - for projection_bound in projection_bounds.iter() { + for projection_bound in &projection_bounds { let projection_obligation = Obligation::new(cause.clone(), projection_bound.as_predicate()); fcx.register_predicate(projection_obligation); @@ -263,13 +263,13 @@ fn check_object_type_binds_all_associated_types<'tcx>(tcx: &ty::ctxt<'tcx>, }) .collect(); - for projection_bound in object_trait.bounds.projection_bounds.iter() { + for projection_bound in &object_trait.bounds.projection_bounds { let pair = (projection_bound.0.projection_ty.trait_ref.def_id, projection_bound.0.projection_ty.item_name); associated_types.remove(&pair); } - for (trait_def_id, name) in associated_types.into_iter() { + for (trait_def_id, name) in associated_types { span_err!(tcx.sess, span, E0191, "the value of the associated type `{}` (from the trait `{}`) must be specified", name.user_string(tcx), diff --git a/src/librustc_typeck/check/wf.rs b/src/librustc_typeck/check/wf.rs index db226295cd9..71b495af444 100644 --- a/src/librustc_typeck/check/wf.rs +++ b/src/librustc_typeck/check/wf.rs @@ -147,15 +147,15 @@ impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> { item.span, region::CodeExtent::from_node_id(item.id), Some(&mut this.cache)); - for variant in variants.iter() { - for field in variant.fields.iter() { + for variant in &variants { + for field in &variant.fields { // Regions are checked below. bounds_checker.check_traits_in_ty(field.ty); } // For DST, all intermediate types must be sized. if variant.fields.len() > 0 { - for field in variant.fields.init().iter() { + for field in variant.fields.init() { fcx.register_builtin_bound( field.ty, ty::BoundSized, @@ -268,10 +268,10 @@ impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> { let selcx = &mut traits::SelectionContext::new(fcx.infcx(), fcx); traits::normalize(selcx, cause.clone(), &predicates) }; - for predicate in predicates.value.into_iter() { + for predicate in predicates.value { fcx.register_predicate(traits::Obligation::new(cause.clone(), predicate)); } - for obligation in predicates.obligations.into_iter() { + for obligation in predicates.obligations { fcx.register_predicate(obligation); } }); @@ -323,7 +323,7 @@ fn reject_shadowing_type_parameters<'tcx>(tcx: &ty::ctxt<'tcx>, let impl_params = generics.types.get_slice(subst::TypeSpace).iter() .map(|tp| tp.name).collect::<HashSet<_>>(); - for method_param in generics.types.get_slice(subst::FnSpace).iter() { + for method_param in generics.types.get_slice(subst::FnSpace) { if impl_params.contains(&method_param.name) { span_err!(tcx.sess, span, E0194, "type parameter `{}` shadows another type parameter of the same name", diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index 0eaecf8ac05..52b1eb490cc 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -49,7 +49,7 @@ pub fn resolve_type_vars_in_fn(fcx: &FnCtxt, assert_eq!(fcx.writeback_errors.get(), false); let mut wbcx = WritebackCx::new(fcx); wbcx.visit_block(blk); - for arg in decl.inputs.iter() { + for arg in &decl.inputs { wbcx.visit_node_id(ResolvingPattern(arg.pat.span), arg.id); wbcx.visit_pat(&*arg.pat); @@ -119,7 +119,7 @@ impl<'cx, 'tcx, 'v> Visitor<'v> for WritebackCx<'cx, 'tcx> { match e.node { ast::ExprClosure(_, _, ref decl, _) => { - for input in decl.inputs.iter() { + for input in &decl.inputs { let _ = self.visit_node_id(ResolvingExpr(e.span), input.id); } @@ -182,7 +182,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { return; } - for (upvar_id, upvar_capture) in self.fcx.inh.upvar_capture_map.borrow().iter() { + for (upvar_id, upvar_capture) in &*self.fcx.inh.upvar_capture_map.borrow() { let new_upvar_capture = match *upvar_capture { ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue, ty::UpvarCapture::ByRef(ref upvar_borrow) => { @@ -204,12 +204,12 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { return } - for (def_id, closure_ty) in self.fcx.inh.closure_tys.borrow().iter() { + for (def_id, closure_ty) in &*self.fcx.inh.closure_tys.borrow() { let closure_ty = self.resolve(closure_ty, ResolvingClosure(*def_id)); self.fcx.tcx().closure_tys.borrow_mut().insert(*def_id, closure_ty); } - for (def_id, &closure_kind) in self.fcx.inh.closure_kinds.borrow().iter() { + for (def_id, &closure_kind) in &*self.fcx.inh.closure_kinds.borrow() { self.fcx.tcx().closure_kinds.borrow_mut().insert(*def_id, closure_kind); } } diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index 9760d5f05df..ed340b0882c 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -136,7 +136,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { // the tcx. let mut tcx_inherent_impls = self.crate_context.tcx.inherent_impls.borrow_mut(); - for (k, v) in self.inherent_impls.borrow().iter() { + for (k, v) in &*self.inherent_impls.borrow() { tcx_inherent_impls.insert((*k).clone(), Rc::new((*v.borrow()).clone())); } @@ -167,7 +167,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { let impl_items = self.create_impl_from_item(item); - for associated_trait in associated_traits.iter() { + for associated_trait in associated_traits { let trait_ref = ty::node_id_to_trait_ref(self.crate_context.tcx, associated_trait.ref_id); debug!("(checking implementation) adding impl for trait '{}', item '{}'", @@ -215,7 +215,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { let impl_type_scheme = ty::lookup_item_type(tcx, impl_id); let prov = ty::provided_trait_methods(tcx, trait_ref.def_id); - for trait_method in prov.iter() { + for trait_method in &prov { // Synthesize an ID. let new_id = tcx.sess.next_node_id(); let new_did = local_def(new_id); @@ -303,7 +303,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { } }).collect(); - for trait_ref in trait_refs.iter() { + if let Some(ref trait_ref) = *trait_refs { let ty_trait_ref = ty::node_id_to_trait_ref( self.crate_context.tcx, trait_ref.ref_id); @@ -345,17 +345,17 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { assert!(associated_traits.is_some()); // Record all the trait items. - for trait_ref in associated_traits.iter() { + if let Some(trait_ref) = associated_traits { self.add_trait_impl(trait_ref.def_id, impl_def_id); } // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. - for item_def_id in impl_items.iter() { + for item_def_id in &impl_items { let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id()); match impl_item { ty::MethodTraitItem(ref method) => { - for &source in method.provided_source.iter() { + if let Some(source) = method.provided_source { tcx.provided_method_sources .borrow_mut() .insert(item_def_id.def_id(), source); @@ -398,7 +398,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { Some(found_impls) => found_impls }; - for &impl_did in trait_impls.borrow().iter() { + for &impl_did in &*trait_impls.borrow() { let items = &(*impl_items)[impl_did]; if items.len() < 1 { // We'll error out later. For now, just don't ICE. @@ -465,7 +465,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { // Clone first to avoid a double borrow error. let trait_impls = trait_impls.borrow().clone(); - for &impl_did in trait_impls.iter() { + for &impl_did in &trait_impls { debug!("check_implementations_of_copy: impl_did={}", impl_did.repr(tcx)); @@ -559,7 +559,7 @@ fn subst_receiver_types_in_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, // replace the type parameters declared on the trait with those // from the impl - for &space in [subst::TypeSpace, subst::SelfSpace].iter() { + for &space in &[subst::TypeSpace, subst::SelfSpace] { method_generics.types.replace( space, impl_type_scheme.generics.types.get_slice(space).to_vec()); diff --git a/src/librustc_typeck/coherence/overlap.rs b/src/librustc_typeck/coherence/overlap.rs index a7bad3dc789..403dcf1e25a 100644 --- a/src/librustc_typeck/coherence/overlap.rs +++ b/src/librustc_typeck/coherence/overlap.rs @@ -46,7 +46,7 @@ impl<'cx, 'tcx> OverlapChecker<'cx, 'tcx> { (k, v.borrow().clone()) }).collect(); - for &(trait_def_id, ref impls) in trait_def_ids.iter() { + for &(trait_def_id, ref impls) in &trait_def_ids { self.check_for_overlapping_impls_of_trait(trait_def_id, impls); } } @@ -65,7 +65,7 @@ impl<'cx, 'tcx> OverlapChecker<'cx, 'tcx> { continue; } - for &impl2_def_id in trait_impls[(i+1)..].iter() { + for &impl2_def_id in &trait_impls[(i+1)..] { self.check_if_impls_overlap(trait_def_id, impl1_def_id, impl2_def_id); diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index ed33ddd458a..7dfa5298fb4 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -203,7 +203,7 @@ fn get_enum_variant_types<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, let tcx = ccx.tcx; // Create a set of parameter types shared among all the variants. - for variant in variants.iter() { + for variant in variants { let variant_def_id = local_def(variant.node.id); // Nullary enum constructors get turned into constants; n-ary enum @@ -249,7 +249,7 @@ fn collect_trait_methods<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, if let ast::ItemTrait(_, _, _, ref trait_items) = item.node { // For each method, construct a suitable ty::Method and // store it into the `tcx.impl_or_trait_items` table: - for trait_item in trait_items.iter() { + for trait_item in trait_items { match *trait_item { ast::RequiredMethod(_) | ast::ProvidedMethod(_) => { @@ -439,7 +439,7 @@ fn convert_associated_type<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, fn convert_methods<'a,'tcx,'i,I>(ccx: &CollectCtxt<'a, 'tcx>, container: ImplOrTraitItemContainer, - mut ms: I, + ms: I, untransformed_rcvr_ty: Ty<'tcx>, rcvr_ty_generics: &ty::Generics<'tcx>, rcvr_visibility: ast::Visibility) @@ -527,8 +527,8 @@ fn ensure_no_ty_param_bounds(ccx: &CollectCtxt, thing: &'static str) { let mut warn = false; - for ty_param in generics.ty_params.iter() { - for bound in ty_param.bounds.iter() { + for ty_param in &*generics.ty_params { + for bound in &*ty_param.bounds { match *bound { ast::TraitTyParamBound(..) => { warn = true; @@ -596,7 +596,7 @@ fn convert(ccx: &CollectCtxt, it: &ast::Item) { }; let mut methods = Vec::new(); - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref method) => { let body_id = method.pe_body().id; @@ -644,7 +644,7 @@ fn convert(ccx: &CollectCtxt, it: &ast::Item) { &ty_generics, parent_visibility); - for trait_ref in opt_trait_ref.iter() { + if let Some(ref trait_ref) = *opt_trait_ref { astconv::instantiate_trait_ref(ccx, &ExplicitRscope, trait_ref, @@ -663,7 +663,7 @@ fn convert(ccx: &CollectCtxt, it: &ast::Item) { it.ident.repr(ccx.tcx), trait_def.repr(ccx.tcx)); - for trait_method in trait_methods.iter() { + for trait_method in trait_methods { let self_type = ty::mk_self_type(tcx); match *trait_method { ast::RequiredMethod(ref type_method) => { @@ -1109,7 +1109,7 @@ fn ty_generics_for_trait<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, debug!("ty_generics_for_trait: assoc_predicates={}", assoc_predicates.repr(ccx.tcx)); - for assoc_predicate in assoc_predicates.into_iter() { + for assoc_predicate in assoc_predicates { generics.predicates.push(subst::TypeSpace, assoc_predicate); } @@ -1168,7 +1168,7 @@ fn add_unsized_bound<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, { // Try to find an unbound in bounds. let mut unbound = None; - for ab in ast_bounds.iter() { + for ab in ast_bounds { if let &ast::TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = ab { if unbound.is_none() { assert!(ptr.bound_lifetimes.is_empty()); @@ -1249,12 +1249,12 @@ fn ty_generics<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, create_predicates(ccx.tcx, &mut result, space); // Add the bounds not associated with a type parameter - for predicate in where_clause.predicates.iter() { + for predicate in &where_clause.predicates { match predicate { &ast::WherePredicate::BoundPredicate(ref bound_pred) => { let ty = ast_ty_to_ty(ccx, &ExplicitRscope, &*bound_pred.bounded_ty); - for bound in bound_pred.bounds.iter() { + for bound in &*bound_pred.bounds { match bound { &ast::TyParamBound::TraitTyParamBound(ref poly_trait_ref, _) => { let mut projections = Vec::new(); @@ -1269,7 +1269,7 @@ fn ty_generics<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, result.predicates.push(space, trait_ref.as_predicate()); - for projection in projections.iter() { + for projection in &projections { result.predicates.push(space, projection.as_predicate()); } } @@ -1285,7 +1285,7 @@ fn ty_generics<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, &ast::WherePredicate::RegionPredicate(ref region_pred) => { let r1 = ast_region_to_region(ccx.tcx, ®ion_pred.lifetime); - for bound in region_pred.bounds.iter() { + for bound in ®ion_pred.bounds { let r2 = ast_region_to_region(ccx.tcx, bound); let pred = ty::Binder(ty::OutlivesPredicate(r1, r2)); result.predicates.push(space, ty::Predicate::RegionOutlives(pred)) @@ -1308,16 +1308,16 @@ fn ty_generics<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, result: &mut ty::Generics<'tcx>, space: subst::ParamSpace) { - for type_param_def in result.types.get_slice(space).iter() { + for type_param_def in result.types.get_slice(space) { let param_ty = ty::mk_param_from_def(tcx, type_param_def); - for predicate in ty::predicates(tcx, param_ty, &type_param_def.bounds).into_iter() { + for predicate in ty::predicates(tcx, param_ty, &type_param_def.bounds) { result.predicates.push(space, predicate); } } - for region_param_def in result.regions.get_slice(space).iter() { + for region_param_def in result.regions.get_slice(space) { let region = region_param_def.to_early_bound_region(); - for &bound_region in region_param_def.bounds.iter() { + for &bound_region in ®ion_param_def.bounds { // account for new binder introduced in the predicate below; no need // to shift `region` because it is never a late-bound region let bound_region = ty_fold::shift_region(bound_region, 1); @@ -1480,7 +1480,7 @@ fn ty_of_foreign_fn_decl<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, ast_generics: &ast::Generics, abi: abi::Abi) -> ty::TypeScheme<'tcx> { - for i in decl.inputs.iter() { + for i in &decl.inputs { match (*i).pat.node { ast::PatIdent(_, _, _) => (), ast::PatWild(ast::PatWildSingle) => (), @@ -1655,7 +1655,7 @@ fn enforce_impl_ty_params_are_constrained<'tcx>(tcx: &ty::ctxt<'tcx>, loop { let num_inputs = input_parameters.len(); - let mut projection_predicates = + let projection_predicates = impl_scheme.generics.predicates .iter() .filter_map(|predicate| { diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 68f5ec9c8c2..a07179b31bb 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -73,7 +73,6 @@ This API is completely unstable and subject to change. html_root_url = "http://doc.rust-lang.org/nightly/")] #![allow(non_camel_case_types)] -#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap #![feature(box_syntax)] #![feature(collections)] diff --git a/src/librustc_typeck/rscope.rs b/src/librustc_typeck/rscope.rs index 7aaf56336a8..ddb485d9776 100644 --- a/src/librustc_typeck/rscope.rs +++ b/src/librustc_typeck/rscope.rs @@ -165,7 +165,7 @@ impl<'r> RegionScope for ShiftedRscope<'r> { { match self.base_scope.anon_regions(span, count) { Ok(mut v) => { - for r in v.iter_mut() { + for r in &mut v { *r = ty_fold::shift_region(*r, 1); } Ok(v) diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index 6c5950e4df5..40197ee2c49 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -499,12 +499,12 @@ impl<'a, 'tcx, 'v> Visitor<'v> for ConstraintContext<'a, 'tcx> { // `ty::VariantInfo::from_ast_variant()` ourselves // here, mainly so as to mask the differences between // struct-like enums and so forth. - for ast_variant in enum_definition.variants.iter() { + for ast_variant in &enum_definition.variants { let variant = ty::VariantInfo::from_ast_variant(tcx, &**ast_variant, /*discriminant*/ 0); - for arg_ty in variant.args.iter() { + for arg_ty in &variant.args { self.add_constraints_from_ty(generics, *arg_ty, self.covariant); } } @@ -513,7 +513,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for ConstraintContext<'a, 'tcx> { ast::ItemStruct(..) => { let generics = &ty::lookup_item_type(tcx, did).generics; let struct_fields = ty::lookup_struct_fields(tcx, did); - for field_info in struct_fields.iter() { + for field_info in &struct_fields { assert_eq!(field_info.id.krate, ast::LOCAL_CRATE); let field_ty = ty::node_id_to_type(tcx, field_info.id.node); self.add_constraints_from_ty(generics, field_ty, self.covariant); @@ -522,7 +522,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for ConstraintContext<'a, 'tcx> { ast::ItemTrait(..) => { let trait_items = ty::trait_items(tcx, did); - for trait_item in trait_items.iter() { + for trait_item in &*trait_items { match *trait_item { ty::MethodTraitItem(ref method) => { self.add_constraints_from_sig(&method.generics, @@ -759,7 +759,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { } ty::ty_tup(ref subtys) => { - for &subty in subtys.iter() { + for &subty in subtys { self.add_constraints_from_ty(generics, subty, variance); } } @@ -821,7 +821,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { let projections = data.projection_bounds_with_self_ty(self.tcx(), self.tcx().types.err); - for projection in projections.iter() { + for projection in &projections { self.add_constraints_from_ty(generics, projection.0.ty, self.invariant); } } @@ -866,7 +866,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { variance: VarianceTermPtr<'a>) { debug!("add_constraints_from_substs(def_id={:?})", def_id); - for p in type_param_defs.iter() { + for p in type_param_defs { let variance_decl = self.declared_variance(p.def_id, def_id, TypeParam, p.space, p.index as uint); @@ -875,7 +875,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { self.add_constraints_from_ty(generics, substs_ty, variance_i); } - for p in region_param_defs.iter() { + for p in region_param_defs { let variance_decl = self.declared_variance(p.def_id, def_id, RegionParam, p.space, p.index as uint); @@ -892,7 +892,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { sig: &ty::PolyFnSig<'tcx>, variance: VarianceTermPtr<'a>) { let contra = self.contravariant(variance); - for &input in sig.0.inputs.iter() { + for &input in &sig.0.inputs { self.add_constraints_from_ty(generics, input, contra); } if let ty::FnConverging(result_type) = sig.0.output { @@ -990,7 +990,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { while changed { changed = false; - for constraint in self.constraints.iter() { + for constraint in &self.constraints { let Constraint { inferred, variance: term } = *constraint; let InferredIndex(inferred) = inferred; let variance = self.evaluate(term); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index d5c03879438..07679480bfb 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -166,7 +166,7 @@ impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> { _ => unreachable!(), }; let mut tmp = Vec::new(); - for child in m.items.iter_mut() { + for child in &mut m.items { match child.inner { ModuleItem(..) => {} _ => continue, @@ -254,7 +254,7 @@ impl Item { /// Finds the `doc` attribute as a List and returns the list of attributes /// nested inside. pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> { - for attr in self.attrs.iter() { + for attr in &self.attrs { match *attr { List(ref x, ref list) if "doc" == *x => { return Some(list.as_slice()); @@ -268,7 +268,7 @@ impl Item { /// Finds the `doc` attribute as a NameValue and returns the corresponding /// value found. pub fn doc_value<'a>(&'a self) -> Option<&'a str> { - for attr in self.attrs.iter() { + for attr in &self.attrs { match *attr { NameValue(ref x, ref v) if "doc" == *x => { return Some(v.as_slice()); @@ -281,8 +281,8 @@ impl Item { pub fn is_hidden_from_doc(&self) -> bool { match self.doc_list() { - Some(ref l) => { - for innerattr in l.iter() { + Some(l) => { + for innerattr in l { match *innerattr { Word(ref s) if "hidden" == *s => { return true @@ -508,12 +508,12 @@ impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBound fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) { let mut tp_bounds = vec![]; self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b))); - for bb in self.builtin_bounds.iter() { + for bb in &self.builtin_bounds { tp_bounds.push(bb.clean(cx)); } let mut bindings = vec![]; - for &ty::Binder(ref pb) in self.projection_bounds.iter() { + for &ty::Binder(ref pb) in &self.projection_bounds { bindings.push(TypeBinding { name: pb.projection_ty.item_name.clean(cx), ty: pb.ty.clean(cx) @@ -636,10 +636,10 @@ impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> { // collect any late bound regions let mut late_bounds = vec![]; - for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace).iter() { + for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) { use rustc::middle::ty::{Region, sty}; if let sty::ty_tup(ref ts) = ty_s.sty { - for &ty_s in ts.iter() { + for &ty_s in ts { if let sty::ty_rptr(ref reg, _) = ty_s.sty { if let &Region::ReLateBound(_, _) = *reg { debug!(" hit an ReLateBound {:?}", reg); @@ -662,7 +662,7 @@ impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> { impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> { fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> { let mut v = Vec::new(); - for t in self.trait_bounds.iter() { + for t in &self.trait_bounds { v.push(t.clean(cx)); } for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) { @@ -872,7 +872,7 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>, subst::ParamSpace) { Some(did) => did, None => return false }; - for bound in bounds.iter() { + for bound in bounds { if let TyParamBound::TraitBound(PolyTrait { trait_: Type::ResolvedPath { did, .. }, .. }, TBM::None) = *bound { @@ -915,7 +915,7 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>, subst::ParamSpace) { }).collect::<Vec<_>>(); // Finally, run through the type parameters again and insert a ?Sized unbound for // any we didn't find to be Sized. - for tp in stripped_typarams.iter() { + for tp in &stripped_typarams { if !sized_params.contains(&tp.name) { let mut sized_bound = ty::BuiltinBound::BoundSized.clean(cx); if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound { @@ -1420,12 +1420,12 @@ impl PrimitiveType { } fn find(attrs: &[Attribute]) -> Option<PrimitiveType> { - for attr in attrs.iter() { + for attr in attrs { let list = match *attr { List(ref k, ref l) if *k == "doc" => l, _ => continue, }; - for sub_attr in list.iter() { + for sub_attr in list { let value = match *sub_attr { NameValue(ref k, ref v) if *k == "primitive" => v.as_slice(), @@ -2175,7 +2175,7 @@ impl Clean<Vec<Item>> for doctree::Import { let mut ret = vec![]; let remaining = if !denied { let mut remaining = vec![]; - for path in list.iter() { + for path in list { match inline::try_inline(cx, path.node.id(), None) { Some(items) => { ret.extend(items.into_iter()); diff --git a/src/librustdoc/externalfiles.rs b/src/librustdoc/externalfiles.rs index 79ca24a18d4..84e88158219 100644 --- a/src/librustdoc/externalfiles.rs +++ b/src/librustdoc/externalfiles.rs @@ -62,7 +62,7 @@ macro_rules! load_or_return { pub fn load_external_files(names: &[String]) -> Option<String> { let mut out = String::new(); - for name in names.iter() { + for name in names { out.push_str(load_or_return!(name.as_slice(), None, None).as_slice()); out.push('\n'); } diff --git a/src/librustdoc/flock.rs b/src/librustdoc/flock.rs index ede71d19354..a7cf5eb8918 100644 --- a/src/librustdoc/flock.rs +++ b/src/librustdoc/flock.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -64,7 +64,7 @@ mod imp { pub const F_SETLKW: libc::c_int = 13; } - #[cfg(target_os = "dragonfly")] + #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] mod os { use libc; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index eb7402b67c4..e86c0e39714 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -212,21 +212,21 @@ impl fmt::Display for clean::PathParameters { if lifetimes.len() > 0 || types.len() > 0 || bindings.len() > 0 { try!(f.write_str("<")); let mut comma = false; - for lifetime in lifetimes.iter() { + for lifetime in lifetimes { if comma { try!(f.write_str(", ")); } comma = true; try!(write!(f, "{}", *lifetime)); } - for ty in types.iter() { + for ty in types { if comma { try!(f.write_str(", ")); } comma = true; try!(write!(f, "{}", *ty)); } - for binding in bindings.iter() { + for binding in bindings { if comma { try!(f.write_str(", ")); } @@ -239,7 +239,7 @@ impl fmt::Display for clean::PathParameters { clean::PathParameters::Parenthesized { ref inputs, ref output } => { try!(f.write_str("(")); let mut comma = false; - for ty in inputs.iter() { + for ty in inputs { if comma { try!(f.write_str(", ")); } @@ -332,7 +332,7 @@ fn path<F, G>(w: &mut fmt::Formatter, match rel_root { Some(root) => { let mut root = String::from_str(root.as_slice()); - for seg in path.segments[..amt].iter() { + for seg in &path.segments[..amt] { if "super" == seg.name || "self" == seg.name { try!(write!(w, "{}::", seg.name)); @@ -347,7 +347,7 @@ fn path<F, G>(w: &mut fmt::Formatter, } } None => { - for seg in path.segments[..amt].iter() { + for seg in &path.segments[..amt] { try!(write!(w, "{}::", seg.name)); } } @@ -359,7 +359,7 @@ fn path<F, G>(w: &mut fmt::Formatter, Some((ref fqp, shortty)) if abs_root.is_some() => { let mut url = String::from_str(abs_root.unwrap().as_slice()); let to_link = &fqp[..fqp.len() - 1]; - for component in to_link.iter() { + for component in to_link { url.push_str(component.as_slice()); url.push_str("/"); } @@ -440,7 +440,7 @@ fn tybounds(w: &mut fmt::Formatter, typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result { match *typarams { Some(ref params) => { - for param in params.iter() { + for param in params { try!(write!(w, " + ")); try!(write!(w, "{}", *param)); } @@ -770,7 +770,7 @@ impl fmt::Display for ModuleSummary { (100 * cnt.unmarked) as f64/tot as f64)); try!(write!(f, "</td></tr>")); - for submodule in m.submodules.iter() { + for submodule in &m.submodules { try!(fmt_inner(f, context, submodule)); } context.pop(); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 8a007fb035e..6247c6dad14 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -283,7 +283,7 @@ pub fn run(mut krate: clean::Crate, let default: &[_] = &[]; match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) { Some(attrs) => { - for attr in attrs.iter() { + for attr in attrs { match *attr { clean::NameValue(ref x, ref s) if "html_favicon_url" == *x => { @@ -353,7 +353,7 @@ pub fn run(mut krate: clean::Crate, krate = cache.fold_crate(krate); // Cache where all our extern crates are located - for &(n, ref e) in krate.externs.iter() { + for &(n, ref e) in &krate.externs { cache.extern_locations.insert(n, extern_location(e, &cx.dst)); let did = ast::DefId { krate: n, node: ast::CRATE_NODE_ID }; cache.paths.insert(did, (vec![e.name.to_string()], ItemType::Module)); @@ -364,11 +364,11 @@ pub fn run(mut krate: clean::Crate, // Favor linking to as local extern as possible, so iterate all crates in // reverse topological order. for &(n, ref e) in krate.externs.iter().rev() { - for &prim in e.primitives.iter() { + for &prim in &e.primitives { cache.primitive_locations.insert(prim, n); } } - for &prim in krate.primitives.iter() { + for &prim in &krate.primitives { cache.primitive_locations.insert(prim, ast::LOCAL_CRATE); } @@ -402,7 +402,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> old_io::IoResult<Stri // Attach all orphan methods to the type's definition if the type // has since been learned. - for &(pid, ref item) in orphan_methods.iter() { + for &(pid, ref item) in orphan_methods { let did = ast_util::local_def(pid); match paths.get(&did) { Some(&(ref fqp, _)) => { @@ -420,7 +420,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> old_io::IoResult<Stri // Reduce `NodeId` in paths into smaller sequential numbers, // and prune the paths that do not appear in the index. - for item in search_index.iter() { + for item in &*search_index { match item.parent { Some(nodeid) => { if !nodeid_to_pathid.contains_key(&nodeid) { @@ -542,7 +542,7 @@ fn write_shared(cx: &Context, let mut w = try!(File::create(&dst)); try!(writeln!(&mut w, "var searchIndex = {{}};")); try!(writeln!(&mut w, "{}", search_index)); - for index in all_indexes.iter() { + for index in &all_indexes { try!(writeln!(&mut w, "{}", *index)); } try!(writeln!(&mut w, "initSearch(searchIndex);")); @@ -550,7 +550,7 @@ fn write_shared(cx: &Context, // Update the list of all implementors for traits let dst = cx.dst.join("implementors"); try!(mkdir(&dst)); - for (&did, imps) in cache.implementors.iter() { + for (&did, imps) in &cache.implementors { // Private modules can leak through to this phase of rustdoc, which // could contain implementations for otherwise private types. In some // rare cases we could find an implementation for an item which wasn't @@ -564,7 +564,7 @@ fn write_shared(cx: &Context, }; let mut mydst = dst.clone(); - for part in remote_path[..remote_path.len() - 1].iter() { + for part in &remote_path[..remote_path.len() - 1] { mydst.push(part.as_slice()); try!(mkdir(&mydst)); } @@ -578,12 +578,12 @@ fn write_shared(cx: &Context, let mut f = BufferedWriter::new(try!(File::create(&mydst))); try!(writeln!(&mut f, "(function() {{var implementors = {{}};")); - for implementor in all_implementors.iter() { + for implementor in &all_implementors { try!(write!(&mut f, "{}", *implementor)); } try!(write!(&mut f, r"implementors['{}'] = [", krate.name)); - for imp in imps.iter() { + for imp in imps { // If the trait and implementation are in the same crate, then // there's no need to emit information about it (there's inlining // going on). If they're in different crates then the crate defining @@ -679,10 +679,10 @@ fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation { // Failing that, see if there's an attribute specifying where to find this // external crate - for attr in e.attrs.iter() { + for attr in &e.attrs { match *attr { clean::List(ref x, ref list) if "doc" == *x => { - for attr in list.iter() { + for attr in list { match *attr { clean::NameValue(ref x, ref s) if "html_root_url" == *x => { @@ -1043,7 +1043,7 @@ impl DocFolder for Cache { impl<'a> Cache { fn generics(&mut self, generics: &clean::Generics) { - for typ in generics.type_params.iter() { + for typ in &generics.type_params { self.typarams.insert(typ.did, typ.name.clone()); } } @@ -1190,7 +1190,7 @@ impl Context { .collect::<String>(); match cache().paths.get(&it.def_id) { Some(&(ref names, _)) => { - for name in (&names[..names.len() - 1]).iter() { + for name in &names[..names.len() - 1] { url.push_str(name.as_slice()); url.push_str("/"); } @@ -1231,7 +1231,7 @@ impl Context { _ => unreachable!() }; this.sidebar = this.build_sidebar(&m); - for item in m.items.into_iter() { + for item in m.items { f(this,item); } Ok(()) @@ -1252,7 +1252,7 @@ impl Context { fn build_sidebar(&self, m: &clean::Module) -> HashMap<String, Vec<NameDoc>> { let mut map = HashMap::new(); - for item in m.items.iter() { + for item in &m.items { if self.ignore_private_item(item) { continue } // avoid putting foreign items to the sidebar. @@ -1270,7 +1270,7 @@ impl Context { v.push(NameDoc(myname, Some(shorter_line(item.doc_value())))); } - for (_, items) in map.iter_mut() { + for (_, items) in &mut map { items.sort(); } return map; @@ -1536,7 +1536,7 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, debug!("{:?}", indices); let mut curty = None; - for &idx in indices.iter() { + for &idx in &indices { let myitem = &items[idx]; let myty = Some(shortty(myitem)); @@ -1696,7 +1696,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, try!(write!(w, "{{ }}")); } else { try!(write!(w, "{{\n")); - for t in types.iter() { + for t in &types { try!(write!(w, " ")); try!(render_method(w, t.item())); try!(write!(w, ";\n")); @@ -1704,7 +1704,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, if types.len() > 0 && required.len() > 0 { try!(w.write_str("\n")); } - for m in required.iter() { + for m in &required { try!(write!(w, " ")); try!(render_method(w, m.item())); try!(write!(w, ";\n")); @@ -1712,7 +1712,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, if required.len() > 0 && provided.len() > 0 { try!(w.write_str("\n")); } - for m in provided.iter() { + for m in &provided { try!(write!(w, " ")); try!(render_method(w, m.item())); try!(write!(w, " {{ ... }}\n")); @@ -1741,7 +1741,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, <h2 id='associated-types'>Associated Types</h2> <div class='methods'> ")); - for t in types.iter() { + for t in &types { try!(trait_item(w, *t)); } try!(write!(w, "</div>")); @@ -1753,7 +1753,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, <h2 id='required-methods'>Required Methods</h2> <div class='methods'> ")); - for m in required.iter() { + for m in &required { try!(trait_item(w, *m)); } try!(write!(w, "</div>")); @@ -1763,7 +1763,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, <h2 id='provided-methods'>Provided Methods</h2> <div class='methods'> ")); - for m in provided.iter() { + for m in &provided { try!(trait_item(w, *m)); } try!(write!(w, "</div>")); @@ -1776,7 +1776,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, ")); match cache.implementors.get(&it.def_id) { Some(implementors) => { - for i in implementors.iter() { + for i in implementors { try!(writeln!(w, "<li>{}<code>impl{} {} for {}{}</code></li>", ConciseStability(&i.stability), i.generics, i.trait_, i.for_, WhereClause(&i.generics))); @@ -1890,7 +1890,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item, try!(write!(w, " {{}}")); } else { try!(write!(w, " {{\n")); - for v in e.variants.iter() { + for v in &e.variants { try!(write!(w, " ")); let name = v.name.as_ref().unwrap().as_slice(); match v.inner { @@ -1933,7 +1933,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item, try!(document(w, it)); if e.variants.len() > 0 { try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>")); - for variant in e.variants.iter() { + for variant in &e.variants { try!(write!(w, "<tr><td id='variant.{name}'>{stab}<code>{name}</code></td><td>", stab = ConciseStability(&variant.stability), name = variant.name.as_ref().unwrap().as_slice())); @@ -1996,7 +1996,7 @@ fn render_struct(w: &mut fmt::Formatter, it: &clean::Item, doctree::Plain => { try!(write!(w, " {{\n{}", tab)); let mut fields_stripped = false; - for field in fields.iter() { + for field in fields { match field.inner { clean::StructFieldItem(clean::HiddenStructField) => { fields_stripped = true; @@ -2049,7 +2049,7 @@ fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result { .partition(|i| i.impl_.trait_.is_none()); if non_trait.len() > 0 { try!(write!(w, "<h2 id='methods'>Methods</h2>")); - for i in non_trait.iter() { + for i in &non_trait { try!(render_impl(w, i)); } } @@ -2058,13 +2058,13 @@ fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result { Implementations</h2>")); let (derived, manual): (Vec<_>, _) = traits.into_iter() .partition(|i| i.impl_.derived); - for i in manual.iter() { + for i in &manual { try!(render_impl(w, i)); } if derived.len() > 0 { try!(write!(w, "<h3 id='derived_implementations'>Derived Implementations \ </h3>")); - for i in derived.iter() { + for i in &derived { try!(render_impl(w, i)); } } @@ -2137,14 +2137,14 @@ fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result { } try!(write!(w, "<div class='impl-items'>")); - for trait_item in i.impl_.items.iter() { + for trait_item in &i.impl_.items { try!(doctraititem(w, trait_item, true)); } fn render_default_methods(w: &mut fmt::Formatter, t: &clean::Trait, i: &clean::Impl) -> fmt::Result { - for trait_item in t.items.iter() { + for trait_item in &t.items { let n = trait_item.item().name.clone(); match i.items.iter().find(|m| { m.name == n }) { Some(..) => continue, @@ -2209,7 +2209,7 @@ impl<'a> fmt::Display for Sidebar<'a> { None => return Ok(()) }; try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty)); - for &NameDoc(ref name, ref doc) in items.iter() { + for &NameDoc(ref name, ref doc) in items { let curty = shortty(cur).to_static_str(); let class = if cur.name.as_ref().unwrap() == name && short == curty { "current" } else { "" }; diff --git a/src/librustdoc/html/toc.rs b/src/librustdoc/html/toc.rs index 9143baf9ed9..7790c7d6a50 100644 --- a/src/librustdoc/html/toc.rs +++ b/src/librustdoc/html/toc.rs @@ -185,7 +185,7 @@ impl fmt::Debug for Toc { impl fmt::Display for Toc { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "<ul>")); - for entry in self.entries.iter() { + for entry in &self.entries { // recursively format this table of contents (the // `{children}` is the key). try!(write!(fmt, diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 29e52d627cd..f4b8bbd5f8a 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -21,6 +21,7 @@ #![feature(box_syntax)] #![feature(collections)] #![feature(core)] +#![feature(env)] #![feature(hash)] #![feature(int_uint)] #![feature(io)] @@ -50,6 +51,7 @@ extern crate "serialize" as rustc_serialize; // used by deriving use std::cell::RefCell; use std::collections::HashMap; +use std::env; use std::old_io::File; use std::old_io; use std::rc::Rc; @@ -121,9 +123,10 @@ struct Output { pub fn main() { static STACK_SIZE: uint = 32000000; // 32MB let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || { - main_args(std::os::args().as_slice()) + let s = env::args().map(|s| s.into_string().unwrap()); + main_args(&s.collect::<Vec<_>>()) }).join(); - std::os::set_exit_status(res.ok().unwrap()); + env::set_exit_status(res.ok().unwrap() as i32); } pub fn opts() -> Vec<getopts::OptGroup> { @@ -197,11 +200,11 @@ pub fn main_args(args: &[String]) -> int { if matches.opt_strs("passes") == ["list"] { println!("Available passes for running rustdoc:"); - for &(name, _, description) in PASSES.iter() { + for &(name, _, description) in PASSES { println!("{:>20} - {}", name, description); } println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970 - for &name in DEFAULT_PASSES.iter() { + for &name in DEFAULT_PASSES { println!("{:>20}", name); } return 0; @@ -217,7 +220,7 @@ pub fn main_args(args: &[String]) -> int { let input = matches.free[0].as_slice(); let mut libs = SearchPaths::new(); - for s in matches.opt_strs("L").iter() { + for s in &matches.opt_strs("L") { libs.add_path(s.as_slice()); } let externs = match parse_externs(&matches) { @@ -319,7 +322,7 @@ fn acquire_input(input: &str, /// error message. fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> { let mut externs = HashMap::new(); - for arg in matches.opt_strs("extern").iter() { + for arg in &matches.opt_strs("extern") { let mut parts = arg.splitn(1, '='); let name = match parts.next() { Some(s) => s, @@ -353,7 +356,7 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche // First, parse the crate and extract all relevant information. let mut paths = SearchPaths::new(); - for s in matches.opt_strs("L").iter() { + for s in &matches.opt_strs("L") { paths.add_path(s.as_slice()); } let cfgs = matches.opt_strs("cfg"); @@ -383,7 +386,7 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche // with the passes which we are supposed to run. match krate.module.as_ref().unwrap().doc_list() { Some(nested) => { - for inner in nested.iter() { + for inner in nested { match *inner { clean::Word(ref x) if "no_default_passes" == *x => { @@ -417,7 +420,7 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche let path = matches.opt_str("plugin-path") .unwrap_or("/tmp/rustdoc/plugins".to_string()); let mut pm = plugins::PluginManager::new(Path::new(path)); - for pass in passes.iter() { + for pass in &passes { let plugin = match PASSES.iter() .position(|&(p, _, _)| { p == *pass @@ -431,7 +434,7 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche pm.add_plugin(plugin); } info!("loading plugins..."); - for pname in plugins.into_iter() { + for pname in plugins { pm.load_plugin(pname); } diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index 7f932b6ca21..365fb78cfae 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -47,7 +47,7 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches, output.set_extension("html"); let mut css = String::new(); - for name in matches.opt_strs("markdown-css").iter() { + for name in &matches.opt_strs("markdown-css") { let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name); css.push_str(s.as_slice()) } diff --git a/src/librustdoc/passes.rs b/src/librustdoc/passes.rs index 30b2ad810f1..e1c6bf1f4cf 100644 --- a/src/librustdoc/passes.rs +++ b/src/librustdoc/passes.rs @@ -255,7 +255,7 @@ pub fn unindent_comments(krate: clean::Crate) -> plugins::PluginResult { fn fold_item(&mut self, i: Item) -> Option<Item> { let mut i = i; let mut avec: Vec<clean::Attribute> = Vec::new(); - for attr in i.attrs.iter() { + for attr in &i.attrs { match attr { &clean::NameValue(ref x, ref s) if "doc" == *x => { @@ -280,7 +280,7 @@ pub fn collapse_docs(krate: clean::Crate) -> plugins::PluginResult { fn fold_item(&mut self, i: Item) -> Option<Item> { let mut docstr = String::new(); let mut i = i; - for attr in i.attrs.iter() { + for attr in &i.attrs { match *attr { clean::NameValue(ref x, ref s) if "doc" == *x => { diff --git a/src/librustdoc/plugins.rs b/src/librustdoc/plugins.rs index 2b5595131d0..a2afba091f4 100644 --- a/src/librustdoc/plugins.rs +++ b/src/librustdoc/plugins.rs @@ -64,7 +64,7 @@ impl PluginManager { pub fn run_plugins(&self, krate: clean::Crate) -> (clean::Crate, Vec<PluginJson> ) { let mut out_json = Vec::new(); let mut krate = krate; - for &callback in self.callbacks.iter() { + for &callback in &self.callbacks { let (c, res) = callback(krate); krate = c; out_json.push(res); diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 2f692fe99cd..29abea009e5 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -13,7 +13,7 @@ use std::sync::mpsc::channel; use std::dynamic_lib::DynamicLibrary; use std::old_io::{Command, TempDir}; use std::old_io; -use std::os; +use std::env; use std::str; use std::thread::Thread; use std::thunk::Thunk; @@ -49,7 +49,7 @@ pub fn run(input: &str, let input = config::Input::File(input_path.clone()); let sessopts = config::Options { - maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()), + maybe_sysroot: Some(env::current_exe().unwrap().dir_path().dir_path()), search_paths: libs.clone(), crate_types: vec!(config::CrateTypeDylib), externs: externs.clone(), @@ -119,7 +119,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths, let input = config::Input::Str(test.to_string()); let sessopts = config::Options { - maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()), + maybe_sysroot: Some(env::current_exe().unwrap().dir_path().dir_path()), search_paths: libs, crate_types: vec!(config::CrateTypeExecutable), output_types: vec!(config::OutputTypeExe), diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 848205f589e..5bcda778cbb 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -147,7 +147,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { om.vis = vis; om.stab = self.stability(id); om.id = id; - for i in m.items.iter() { + for i in &m.items { self.visit_item(&**i, None, &mut om); } om @@ -211,7 +211,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { if glob { match it.node { ast::ItemMod(ref m) => { - for i in m.items.iter() { + for i in &m.items { self.visit_item(&**i, None, om); } } diff --git a/src/libserialize/collection_impls.rs b/src/libserialize/collection_impls.rs index 8b39d91ffae..d61d5b68462 100644 --- a/src/libserialize/collection_impls.rs +++ b/src/libserialize/collection_impls.rs @@ -74,7 +74,7 @@ impl< fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_map(self.len(), |e| { let mut i = 0; - for (key, val) in self.iter() { + for (key, val) in self { try!(e.emit_map_elt_key(i, |e| key.encode(e))); try!(e.emit_map_elt_val(i, |e| val.encode(e))); i += 1; @@ -107,7 +107,7 @@ impl< fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_seq(self.len(), |s| { let mut i = 0; - for e in self.iter() { + for e in self { try!(s.emit_seq_elt(i, |s| e.encode(s))); i += 1; } @@ -135,7 +135,7 @@ impl< > Encodable for EnumSet<T> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { let mut bits = 0; - for item in self.iter() { + for item in self { bits |= item.to_uint(); } s.emit_uint(bits) @@ -166,7 +166,7 @@ impl<K, V, S> Encodable for HashMap<K, V, S> fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> { e.emit_map(self.len(), |e| { let mut i = 0; - for (key, val) in self.iter() { + for (key, val) in self { try!(e.emit_map_elt_key(i, |e| key.encode(e))); try!(e.emit_map_elt_val(i, |e| val.encode(e))); i += 1; @@ -204,7 +204,7 @@ impl<T, S> Encodable for HashSet<T, S> fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> { s.emit_seq(self.len(), |s| { let mut i = 0; - for e in self.iter() { + for e in self { try!(s.emit_seq_elt(i, |s| e.encode(s))); i += 1; } diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index c9b6af26ce0..a34ae1087db 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -42,7 +42,7 @@ impl ToHex for [u8] { /// ``` fn to_hex(&self) -> String { let mut v = Vec::with_capacity(self.len() * 2); - for &byte in self.iter() { + for &byte in self { v.push(CHARS[(byte >> 4) as uint]); v.push(CHARS[(byte & 0xf) as uint]); } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 8d8bd32ba77..3bc9e699035 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -1051,7 +1051,7 @@ impl Json { /// Otherwise, it will return the Json value associated with the final key. pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{ let mut target = self; - for key in keys.iter() { + for key in keys { match target.find(*key) { Some(t) => { target = t; }, None => return None @@ -1069,7 +1069,7 @@ impl Json { match map.get(key) { Some(json_value) => Some(json_value), None => { - for (_, v) in map.iter() { + for (_, v) in map { match v.search(key) { x if x.is_some() => return x, _ => () @@ -1367,7 +1367,7 @@ impl Stack { // Used by Parser to insert StackElement::Key elements at the top of the stack. fn push_key(&mut self, key: string::String) { self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16)); - for c in key.as_bytes().iter() { + for c in key.as_bytes() { self.str_buffer.push(*c); } } @@ -2371,7 +2371,7 @@ impl ::Decoder for Decoder { { let obj = try!(expect!(self.pop(), Object)); let len = obj.len(); - for (key, value) in obj.into_iter() { + for (key, value) in obj { self.stack.push(value); self.stack.push(Json::String(key)); } @@ -2497,7 +2497,7 @@ impl<A: ToJson> ToJson for Vec<A> { impl<A: ToJson> ToJson for BTreeMap<string::String, A> { fn to_json(&self) -> Json { let mut d = BTreeMap::new(); - for (key, value) in self.iter() { + for (key, value) in self { d.insert((*key).clone(), value.to_json()); } Json::Object(d) @@ -2507,7 +2507,7 @@ impl<A: ToJson> ToJson for BTreeMap<string::String, A> { impl<A: ToJson> ToJson for HashMap<string::String, A> { fn to_json(&self) -> Json { let mut d = BTreeMap::new(); - for (key, value) in self.iter() { + for (key, value) in self { d.insert((*key).clone(), value.to_json()); } Json::Object(d) @@ -2670,7 +2670,7 @@ mod tests { fn mk_object(items: &[(string::String, Json)]) -> Json { let mut d = BTreeMap::new(); - for item in items.iter() { + for item in items { match *item { (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); }, } @@ -3044,7 +3044,7 @@ mod tests { ("\"\\u12ab\"", "\u{12ab}"), ("\"\\uAB12\"", "\u{AB12}")]; - for &(i, o) in s.iter() { + for &(i, o) in &s { let v: string::String = super::decode(i).unwrap(); assert_eq!(v, o); } diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 9aa38e711e7..274c669d8df 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -134,7 +134,7 @@ impl AsciiExt<Vec<u8>> for [u8] { impl OwnedAsciiExt for Vec<u8> { #[inline] fn into_ascii_uppercase(mut self) -> Vec<u8> { - for byte in self.iter_mut() { + for byte in &mut self { *byte = byte.to_ascii_uppercase(); } self @@ -142,7 +142,7 @@ impl OwnedAsciiExt for Vec<u8> { #[inline] fn into_ascii_lowercase(mut self) -> Vec<u8> { - for byte in self.iter_mut() { + for byte in &mut self { *byte = byte.to_ascii_lowercase(); } self @@ -232,7 +232,7 @@ pub fn escape_default<F>(c: u8, mut f: F) where _ => { f(b'\\'); f(b'x'); - for &offset in [4u, 0u].iter() { + for &offset in &[4u, 0u] { match ((c as i32) >> offset) & 0xf { i @ 0 ... 9 => f(b'0' + (i as u8)), i => f(b'a' + (i as u8 - 10)), diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 3e2c7627dbe..7b3cc434f0c 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -20,7 +20,7 @@ use cmp::{max, Eq, PartialEq}; use default::Default; use fmt::{self, Debug}; use hash::{self, Hash, SipHasher}; -use iter::{self, Iterator, ExactSizeIterator, IteratorExt, FromIterator, Extend, Map}; +use iter::{self, Iterator, ExactSizeIterator, IntoIterator, IteratorExt, FromIterator, Extend, Map}; use marker::Sized; use mem::{self, replace}; use num::{Int, UnsignedInt}; @@ -1300,18 +1300,13 @@ pub struct IterMut<'a, K: 'a, V: 'a> { /// HashMap move iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter<K, V> { - inner: iter::Map< - (SafeHash, K, V), - (K, V), - table::IntoIter<K, V>, - fn((SafeHash, K, V)) -> (K, V), - > + inner: iter::Map<table::IntoIter<K, V>, fn((SafeHash, K, V)) -> (K, V)> } /// HashMap keys iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct Keys<'a, K: 'a, V: 'a> { - inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> + inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> } // FIXME(#19839) Remove in favor of `#[derive(Clone)]` @@ -1326,7 +1321,7 @@ impl<'a, K, V> Clone for Keys<'a, K, V> { /// HashMap values iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct Values<'a, K: 'a, V: 'a> { - inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> + inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> } // FIXME(#19839) Remove in favor of `#[derive(Clone)]` @@ -1342,12 +1337,7 @@ impl<'a, K, V> Clone for Values<'a, K, V> { #[unstable(feature = "std_misc", reason = "matches collection reform specification, waiting for dust to settle")] pub struct Drain<'a, K: 'a, V: 'a> { - inner: iter::Map< - (SafeHash, K, V), - (K, V), - table::Drain<'a, K, V>, - fn((SafeHash, K, V)) -> (K, V), - > + inner: iter::Map<table::Drain<'a, K, V>, fn((SafeHash, K, V)) -> (K, V)> } /// A view into a single occupied location in a HashMap. @@ -1385,6 +1375,42 @@ enum VacantEntryState<K, V, M> { NoElem(EmptyBucket<K, V, M>), } +impl<'a, K, V, S, H> IntoIterator for &'a HashMap<K, V, S> + where K: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ + type Iter = Iter<'a, K, V>; + + fn into_iter(self) -> Iter<'a, K, V> { + self.iter() + } +} + +impl<'a, K, V, S, H> IntoIterator for &'a mut HashMap<K, V, S> + where K: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ + type Iter = IterMut<'a, K, V>; + + fn into_iter(mut self) -> IterMut<'a, K, V> { + self.iter_mut() + } +} + +impl<K, V, S, H> IntoIterator for HashMap<K, V, S> + where K: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ + type Iter = IntoIter<K, V>; + + fn into_iter(self) -> IntoIter<K, V> { + self.into_iter() + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item = (&'a K, &'a V); @@ -1539,7 +1565,7 @@ impl<K, V, S, H> Extend<(K, V)> for HashMap<K, V, S> S: HashState<Hasher=H>, H: hash::Hasher<Output=u64> { - fn extend<T: Iterator<Item=(K, V)>>(&mut self, mut iter: T) { + fn extend<T: Iterator<Item=(K, V)>>(&mut self, iter: T) { for (k, v) in iter { self.insert(k, v); } @@ -1941,7 +1967,7 @@ mod test_map { let mut observed: u32 = 0; - for (k, v) in m.iter() { + for (k, v) in &m { assert_eq!(*v, *k * 2); observed |= 1 << *k; } @@ -2131,7 +2157,7 @@ mod test_map { let map: HashMap<int, int> = xs.iter().map(|&x| x).collect(); - for &(k, v) in xs.iter() { + for &(k, v) in &xs { assert_eq!(map.get(&k), Some(&v)); } } diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index c6dcb0d230f..f5877e1dd99 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -18,7 +18,9 @@ use default::Default; use fmt::Debug; use fmt; use hash::{self, Hash}; -use iter::{Iterator, ExactSizeIterator, IteratorExt, FromIterator, Map, Chain, Extend}; +use iter::{ + Iterator, IntoIterator, ExactSizeIterator, IteratorExt, FromIterator, Map, Chain, Extend, +}; use ops::{BitOr, BitAnd, BitXor, Sub}; use option::Option::{Some, None, self}; @@ -634,7 +636,7 @@ impl<T, S, H> Extend<T> for HashSet<T, S> S: HashState<Hasher=H>, H: hash::Hasher<Output=u64> { - fn extend<I: Iterator<Item=T>>(&mut self, mut iter: I) { + fn extend<I: Iterator<Item=T>>(&mut self, iter: I) { for k in iter { self.insert(k); } @@ -794,13 +796,13 @@ pub struct Iter<'a, K: 'a> { /// HashSet move iterator #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter<K> { - iter: Map<(K, ()), K, map::IntoIter<K, ()>, fn((K, ())) -> K> + iter: Map<map::IntoIter<K, ()>, fn((K, ())) -> K> } /// HashSet drain iterator #[stable(feature = "rust1", since = "1.0.0")] pub struct Drain<'a, K: 'a> { - iter: Map<(K, ()), K, map::Drain<'a, K, ()>, fn((K, ())) -> K>, + iter: Map<map::Drain<'a, K, ()>, fn((K, ())) -> K>, } /// Intersection iterator @@ -833,6 +835,30 @@ pub struct Union<'a, T: 'a, S: 'a> { iter: Chain<Iter<'a, T>, Difference<'a, T, S>> } +impl<'a, T, S, H> IntoIterator for &'a HashSet<T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ + type Iter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl<T, S, H> IntoIterator for HashSet<T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ + type Iter = IntoIter<T>; + + fn into_iter(self) -> IntoIter<T> { + self.into_iter() + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K> Iterator for Iter<'a, K> { type Item = &'a K; @@ -1007,7 +1033,7 @@ mod test_set { assert!(a.insert(i)); } let mut observed: u32 = 0; - for k in a.iter() { + for k in &a { observed |= 1 << *k; } assert_eq!(observed, 0xFFFF_FFFF); @@ -1128,7 +1154,7 @@ mod test_set { let set: HashSet<int> = xs.iter().map(|&x| x).collect(); - for x in xs.iter() { + for x in &xs { assert!(set.contains(x)); } } @@ -1214,7 +1240,7 @@ mod test_set { assert_eq!(last_i, 49); } - for _ in s.iter() { panic!("s should be empty!"); } + for _ in &s { panic!("s should be empty!"); } // reset to try again. s.extend(1..100); diff --git a/src/libstd/dynamic_lib.rs b/src/libstd/dynamic_lib.rs index f35f63143ef..68ae0f7e5b5 100644 --- a/src/libstd/dynamic_lib.rs +++ b/src/libstd/dynamic_lib.rs @@ -1,4 +1,4 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -19,7 +19,7 @@ use prelude::v1::*; use ffi::CString; use mem; -use os; +use env; use str; #[allow(missing_copy_implementations)] @@ -68,8 +68,8 @@ impl DynamicLibrary { let mut search_path = DynamicLibrary::search_path(); search_path.insert(0, path.clone()); let newval = DynamicLibrary::create_path(search_path.as_slice()); - os::setenv(DynamicLibrary::envvar(), - str::from_utf8(newval.as_slice()).unwrap()); + env::set_var(DynamicLibrary::envvar(), + str::from_utf8(newval.as_slice()).unwrap()); } /// From a slice of paths, create a new vector which is suitable to be an @@ -102,18 +102,10 @@ impl DynamicLibrary { /// Returns the current search path for dynamic libraries being used by this /// process pub fn search_path() -> Vec<Path> { - let mut ret = Vec::new(); - match os::getenv_as_bytes(DynamicLibrary::envvar()) { - Some(env) => { - for portion in - env.as_slice() - .split(|a| *a == DynamicLibrary::separator()) { - ret.push(Path::new(portion)); - } - } - None => {} + match env::var(DynamicLibrary::envvar()) { + Some(var) => env::split_paths(&var).collect(), + None => Vec::new(), } - return ret; } /// Access the value at the symbol of the dynamic library @@ -173,7 +165,8 @@ mod test { #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] fn test_errors_do_not_crash() { // Open /dev/null as a library to get an error, and make sure // that only causes an error, and not a crash. @@ -190,7 +183,8 @@ mod test { target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] mod dl { use prelude::v1::*; @@ -254,7 +248,6 @@ mod dl { dlclose(handle as *mut libc::c_void); () } - #[link_name = "dl"] extern { fn dlopen(filename: *const libc::c_char, flag: libc::c_int) -> *mut libc::c_void; diff --git a/src/libstd/env.rs b/src/libstd/env.rs new file mode 100644 index 00000000000..5070f8c547a --- /dev/null +++ b/src/libstd/env.rs @@ -0,0 +1,833 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Inspection and manipulation of the process's environment. +//! +//! This module contains methods to inspect various aspects such as +//! environment varibles, process arguments, the current directory, and various +//! other important directories. + +#![unstable(feature = "env", reason = "recently added via RFC 578")] + +use prelude::v1::*; + +use error::Error; +use ffi::{OsString, AsOsStr}; +use fmt; +use old_io::IoResult; +use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering}; +use sync::{StaticMutex, MUTEX_INIT}; +use sys::os as os_imp; + +/// Returns the current working directory as a `Path`. +/// +/// # Errors +/// +/// Returns an `Err` if the current working directory value is invalid. +/// Possible cases: +/// +/// * Current directory does not exist. +/// * There are insufficient permissions to access the current directory. +/// * The internal buffer is not large enough to hold the path. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// // We assume that we are in a valid directory. +/// let p = env::current_dir().unwrap(); +/// println!("The current directory is {}", p.display()); +/// ``` +pub fn current_dir() -> IoResult<Path> { + os_imp::getcwd() +} + +/// Changes the current working directory to the specified path, returning +/// whether the change was completed successfully or not. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// use std::path::Path; +/// +/// let root = Path::new("/"); +/// assert!(env::set_current_dir(&root).is_ok()); +/// println!("Successfully changed working directory to {}!", root.display()); +/// ``` +pub fn set_current_dir(p: &Path) -> IoResult<()> { + os_imp::chdir(p) +} + +static ENV_LOCK: StaticMutex = MUTEX_INIT; + +/// An iterator over a snapshot of the environment variables of this process. +/// +/// This iterator is created through `std::env::vars()` and yields `(OsString, +/// OsString)` pairs. +pub struct Vars { inner: os_imp::Env } + +/// Returns an iterator of (variable, value) pairs, for all the environment +/// variables of the current process. +/// +/// The returned iterator contains a snapshot of the process's environment +/// variables at the time of this invocation, modifications to environment +/// variables afterwards will not be reflected in the returned iterator. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// // We will iterate through the references to the element returned by +/// // env::vars(); +/// for (key, value) in env::vars() { +/// println!("{:?}: {:?}", key, value); +/// } +/// ``` +pub fn vars() -> Vars { + let _g = ENV_LOCK.lock(); + Vars { inner: os_imp::env() } +} + +impl Iterator for Vars { + type Item = (OsString, OsString); + fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() } + fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } +} + +/// Fetches the environment variable `key` from the current process, returning +/// None if the variable isn't set. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// let key = "HOME"; +/// match env::var(key) { +/// Some(val) => println!("{}: {:?}", key, val), +/// None => println!("{} is not defined in the environment.", key) +/// } +/// ``` +pub fn var<K: ?Sized>(key: &K) -> Option<OsString> where K: AsOsStr { + let _g = ENV_LOCK.lock(); + os_imp::getenv(key.as_os_str()) +} + +/// Fetches the environment variable `key` from the current process. +/// +/// The returned result is `Ok(s)` if the environment variable is present and is +/// valid unicode. If the environment variable is not present, or it is not +/// valid unicode, then `Err` will be returned. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// let key = "HOME"; +/// match env::var_string(key) { +/// Ok(val) => println!("{}: {:?}", key, val), +/// Err(e) => println!("couldn't interpret {}: {}", key, e), +/// } +/// ``` +pub fn var_string<K: ?Sized>(key: &K) -> Result<String, VarError> where K: AsOsStr { + match var(key) { + Some(s) => s.into_string().map_err(VarError::NotUnicode), + None => Err(VarError::NotPresent) + } +} + +/// Possible errors from the `env::var` method. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum VarError { + /// The specified environment variable was not present in the current + /// process's environment. + NotPresent, + + /// The specified environment variable was found, but it did not contain + /// valid unicode data. The found data is returned as a payload of this + /// variant. + NotUnicode(OsString), +} + +impl fmt::Display for VarError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + VarError::NotPresent => write!(f, "environment variable not found"), + VarError::NotUnicode(ref s) => { + write!(f, "environment variable was not valid unicode: {:?}", s) + } + } + } +} + +impl Error for VarError { + fn description(&self) -> &str { + match *self { + VarError::NotPresent => "environment variable not found", + VarError::NotUnicode(..) => "environment variable was not valid unicode", + } + } +} + +/// Sets the environment variable `k` to the value `v` for the currently running +/// process. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// let key = "KEY"; +/// env::set_var(key, "VALUE"); +/// assert_eq!(env::var_string(key), Ok("VALUE".to_string())); +/// ``` +pub fn set_var<K: ?Sized, V: ?Sized>(k: &K, v: &V) + where K: AsOsStr, V: AsOsStr +{ + let _g = ENV_LOCK.lock(); + os_imp::setenv(k.as_os_str(), v.as_os_str()) +} + +/// Remove a variable from the environment entirely. +pub fn remove_var<K: ?Sized>(k: &K) where K: AsOsStr { + let _g = ENV_LOCK.lock(); + os_imp::unsetenv(k.as_os_str()) +} + +/// An iterator over `Path` instances for parsing an environment variable +/// according to platform-specific conventions. +/// +/// This structure is returned from `std::env::split_paths`. +pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> } + +/// Parses input according to platform conventions for the `PATH` +/// environment variable. +/// +/// Returns an iterator over the paths contained in `unparsed`. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// let key = "PATH"; +/// match env::var(key) { +/// Some(paths) => { +/// for path in env::split_paths(&paths) { +/// println!("'{}'", path.display()); +/// } +/// } +/// None => println!("{} is not defined in the environment.", key) +/// } +/// ``` +pub fn split_paths<T: AsOsStr + ?Sized>(unparsed: &T) -> SplitPaths { + SplitPaths { inner: os_imp::split_paths(unparsed.as_os_str()) } +} + +impl<'a> Iterator for SplitPaths<'a> { + type Item = Path; + fn next(&mut self) -> Option<Path> { self.inner.next() } + fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } +} + +/// Error type returned from `std::env::join_paths` when paths fail to be +/// joined. +#[derive(Debug)] +pub struct JoinPathsError { + inner: os_imp::JoinPathsError +} + +/// Joins a collection of `Path`s appropriately for the `PATH` +/// environment variable. +/// +/// Returns an `OsString` on success. +/// +/// Returns an `Err` (containing an error message) if one of the input +/// `Path`s contains an invalid character for constructing the `PATH` +/// variable (a double quote on Windows or a colon on Unix). +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// if let Some(path) = env::var("PATH") { +/// let mut paths = env::split_paths(&path).collect::<Vec<_>>(); +/// paths.push(Path::new("/home/xyz/bin")); +/// let new_path = env::join_paths(paths.iter()).unwrap(); +/// env::set_var("PATH", &new_path); +/// } +/// ``` +pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> + where I: Iterator<Item=T>, T: AsOsStr +{ + os_imp::join_paths(paths).map_err(|e| { + JoinPathsError { inner: e } + }) +} + +impl fmt::Display for JoinPathsError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +impl Error for JoinPathsError { + fn description(&self) -> &str { self.inner.description() } +} + +/// Optionally returns the path to the current user's home directory if known. +/// +/// # Unix +/// +/// Returns the value of the 'HOME' environment variable if it is set +/// and not equal to the empty string. +/// +/// # Windows +/// +/// Returns the value of the 'HOME' environment variable if it is +/// set and not equal to the empty string. Otherwise, returns the value of the +/// 'USERPROFILE' environment variable if it is set and not equal to the empty +/// string. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// match env::home_dir() { +/// Some(ref p) => println!("{}", p.display()), +/// None => println!("Impossible to get your home dir!") +/// } +/// ``` +pub fn home_dir() -> Option<Path> { + os_imp::home_dir() +} + +/// Returns the path to a temporary directory. +/// +/// On Unix, returns the value of the 'TMPDIR' environment variable if it is +/// set, otherwise for non-Android it returns '/tmp'. If Android, since there +/// is no global temporary folder (it is usually allocated per-app), we return +/// '/data/local/tmp'. +/// +/// On Windows, returns the value of, in order, the 'TMP', 'TEMP', +/// 'USERPROFILE' environment variable if any are set and not the empty +/// string. Otherwise, tmpdir returns the path to the Windows directory. +pub fn temp_dir() -> Path { + os_imp::temp_dir() +} + +/// Optionally returns the filesystem path to the current executable which is +/// running but with the executable name. +/// +/// The path returned is not necessarily a "real path" to the executable as +/// there may be intermediate symlinks. +/// +/// # Errors +/// +/// Acquring the path to the current executable is a platform-specific operation +/// that can fail for a good number of reasons. Some errors can include, but not +/// be limited to filesystem operations failing or general syscall failures. +/// +/// # Examples +/// +/// ```rust +/// use std::env; +/// +/// match env::current_exe() { +/// Ok(exe_path) => println!("Path of this executable is: {}", +/// exe_path.display()), +/// Err(e) => println!("failed to get current exe path: {}", e), +/// }; +/// ``` +pub fn current_exe() -> IoResult<Path> { + os_imp::current_exe() +} + +static EXIT_STATUS: AtomicIsize = ATOMIC_ISIZE_INIT; + +/// Sets the process exit code +/// +/// Sets the exit code returned by the process if all supervised tasks +/// terminate successfully (without panicking). If the current root task panics +/// and is supervised by the scheduler then any user-specified exit status is +/// ignored and the process exits with the default panic status. +/// +/// Note that this is not synchronized against modifications of other threads. +pub fn set_exit_status(code: i32) { + EXIT_STATUS.store(code as isize, Ordering::SeqCst) +} + +/// Fetches the process's current exit code. This defaults to 0 and can change +/// by calling `set_exit_status`. +pub fn get_exit_status() -> i32 { + EXIT_STATUS.load(Ordering::SeqCst) as i32 +} + +/// An iterator over the arguments of a process, yielding an `OsString` value +/// for each argument. +/// +/// This structure is created through the `std::env::args` method. +pub struct Args { inner: os_imp::Args } + +/// Returns the arguments which this program was started with (normally passed +/// via the command line). +/// +/// The first element is traditionally the path to the executable, but it can be +/// set to arbitrary text, and it may not even exist, so this property should +/// not be relied upon for security purposes. +/// +/// # Example +/// +/// ```rust +/// use std::env; +/// +/// // Prints each argument on a separate line +/// for argument in env::args() { +/// println!("{:?}", argument); +/// } +/// ``` +pub fn args() -> Args { + Args { inner: os_imp::args() } +} + +impl Iterator for Args { + type Item = OsString; + fn next(&mut self) -> Option<OsString> { self.inner.next() } + fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } +} + +/// Returns the page size of the current architecture in bytes. +pub fn page_size() -> usize { + os_imp::page_size() +} + +/// Constants associated with the current target +#[cfg(target_os = "linux")] +pub mod consts { + pub use super::arch_consts::ARCH; + + pub const FAMILY: &'static str = "unix"; + + /// A string describing the specific operating system in use: in this + /// case, `linux`. + pub const OS: &'static str = "linux"; + + /// Specifies the filename prefix used for shared libraries on this + /// platform: in this case, `lib`. + pub const DLL_PREFIX: &'static str = "lib"; + + /// Specifies the filename suffix used for shared libraries on this + /// platform: in this case, `.so`. + pub const DLL_SUFFIX: &'static str = ".so"; + + /// Specifies the file extension used for shared libraries on this + /// platform that goes after the dot: in this case, `so`. + pub const DLL_EXTENSION: &'static str = "so"; + + /// Specifies the filename suffix used for executable binaries on this + /// platform: in this case, the empty string. + pub const EXE_SUFFIX: &'static str = ""; + + /// Specifies the file extension, if any, used for executable binaries + /// on this platform: in this case, the empty string. + pub const EXE_EXTENSION: &'static str = ""; +} + +/// Constants associated with the current target +#[cfg(target_os = "macos")] +pub mod consts { + pub use super::arch_consts::ARCH; + + pub const FAMILY: &'static str = "unix"; + + /// A string describing the specific operating system in use: in this + /// case, `macos`. + pub const OS: &'static str = "macos"; + + /// Specifies the filename prefix used for shared libraries on this + /// platform: in this case, `lib`. + pub const DLL_PREFIX: &'static str = "lib"; + + /// Specifies the filename suffix used for shared libraries on this + /// platform: in this case, `.dylib`. + pub const DLL_SUFFIX: &'static str = ".dylib"; + + /// Specifies the file extension used for shared libraries on this + /// platform that goes after the dot: in this case, `dylib`. + pub const DLL_EXTENSION: &'static str = "dylib"; + + /// Specifies the filename suffix used for executable binaries on this + /// platform: in this case, the empty string. + pub const EXE_SUFFIX: &'static str = ""; + + /// Specifies the file extension, if any, used for executable binaries + /// on this platform: in this case, the empty string. + pub const EXE_EXTENSION: &'static str = ""; +} + +/// Constants associated with the current target +#[cfg(target_os = "ios")] +pub mod consts { + pub use super::arch_consts::ARCH; + + pub const FAMILY: &'static str = "unix"; + + /// A string describing the specific operating system in use: in this + /// case, `ios`. + pub const OS: &'static str = "ios"; + + /// Specifies the filename suffix used for executable binaries on this + /// platform: in this case, the empty string. + pub const EXE_SUFFIX: &'static str = ""; + + /// Specifies the file extension, if any, used for executable binaries + /// on this platform: in this case, the empty string. + pub const EXE_EXTENSION: &'static str = ""; +} + +/// Constants associated with the current target +#[cfg(target_os = "freebsd")] +pub mod consts { + pub use super::arch_consts::ARCH; + + pub const FAMILY: &'static str = "unix"; + + /// A string describing the specific operating system in use: in this + /// case, `freebsd`. + pub const OS: &'static str = "freebsd"; + + /// Specifies the filename prefix used for shared libraries on this + /// platform: in this case, `lib`. + pub const DLL_PREFIX: &'static str = "lib"; + + /// Specifies the filename suffix used for shared libraries on this + /// platform: in this case, `.so`. + pub const DLL_SUFFIX: &'static str = ".so"; + + /// Specifies the file extension used for shared libraries on this + /// platform that goes after the dot: in this case, `so`. + pub const DLL_EXTENSION: &'static str = "so"; + + /// Specifies the filename suffix used for executable binaries on this + /// platform: in this case, the empty string. + pub const EXE_SUFFIX: &'static str = ""; + + /// Specifies the file extension, if any, used for executable binaries + /// on this platform: in this case, the empty string. + pub const EXE_EXTENSION: &'static str = ""; +} + +/// Constants associated with the current target +#[cfg(target_os = "dragonfly")] +pub mod consts { + pub use super::arch_consts::ARCH; + + pub const FAMILY: &'static str = "unix"; + + /// A string describing the specific operating system in use: in this + /// case, `dragonfly`. + pub const OS: &'static str = "dragonfly"; + + /// Specifies the filename prefix used for shared libraries on this + /// platform: in this case, `lib`. + pub const DLL_PREFIX: &'static str = "lib"; + + /// Specifies the filename suffix used for shared libraries on this + /// platform: in this case, `.so`. + pub const DLL_SUFFIX: &'static str = ".so"; + + /// Specifies the file extension used for shared libraries on this + /// platform that goes after the dot: in this case, `so`. + pub const DLL_EXTENSION: &'static str = "so"; + + /// Specifies the filename suffix used for executable binaries on this + /// platform: in this case, the empty string. + pub const EXE_SUFFIX: &'static str = ""; + + /// Specifies the file extension, if any, used for executable binaries + /// on this platform: in this case, the empty string. + pub const EXE_EXTENSION: &'static str = ""; +} + +/// Constants associated with the current target +#[cfg(target_os = "android")] +pub mod consts { + pub use super::arch_consts::ARCH; + + pub const FAMILY: &'static str = "unix"; + + /// A string describing the specific operating system in use: in this + /// case, `android`. + pub const OS: &'static str = "android"; + + /// Specifies the filename prefix used for shared libraries on this + /// platform: in this case, `lib`. + pub const DLL_PREFIX: &'static str = "lib"; + + /// Specifies the filename suffix used for shared libraries on this + /// platform: in this case, `.so`. + pub const DLL_SUFFIX: &'static str = ".so"; + + /// Specifies the file extension used for shared libraries on this + /// platform that goes after the dot: in this case, `so`. + pub const DLL_EXTENSION: &'static str = "so"; + + /// Specifies the filename suffix used for executable binaries on this + /// platform: in this case, the empty string. + pub const EXE_SUFFIX: &'static str = ""; + + /// Specifies the file extension, if any, used for executable binaries + /// on this platform: in this case, the empty string. + pub const EXE_EXTENSION: &'static str = ""; +} + +/// Constants associated with the current target +#[cfg(target_os = "windows")] +pub mod consts { + pub use super::arch_consts::ARCH; + + pub const FAMILY: &'static str = "windows"; + + /// A string describing the specific operating system in use: in this + /// case, `windows`. + pub const OS: &'static str = "windows"; + + /// Specifies the filename prefix used for shared libraries on this + /// platform: in this case, the empty string. + pub const DLL_PREFIX: &'static str = ""; + + /// Specifies the filename suffix used for shared libraries on this + /// platform: in this case, `.dll`. + pub const DLL_SUFFIX: &'static str = ".dll"; + + /// Specifies the file extension used for shared libraries on this + /// platform that goes after the dot: in this case, `dll`. + pub const DLL_EXTENSION: &'static str = "dll"; + + /// Specifies the filename suffix used for executable binaries on this + /// platform: in this case, `.exe`. + pub const EXE_SUFFIX: &'static str = ".exe"; + + /// Specifies the file extension, if any, used for executable binaries + /// on this platform: in this case, `exe`. + pub const EXE_EXTENSION: &'static str = "exe"; +} + +#[cfg(target_arch = "x86")] +mod arch_consts { + pub const ARCH: &'static str = "x86"; +} + +#[cfg(target_arch = "x86_64")] +mod arch_consts { + pub const ARCH: &'static str = "x86_64"; +} + +#[cfg(target_arch = "arm")] +mod arch_consts { + pub const ARCH: &'static str = "arm"; +} + +#[cfg(target_arch = "aarch64")] +mod arch_consts { + pub const ARCH: &'static str = "aarch64"; +} + +#[cfg(target_arch = "mips")] +mod arch_consts { + pub const ARCH: &'static str = "mips"; +} + +#[cfg(target_arch = "mipsel")] +mod arch_consts { + pub const ARCH: &'static str = "mipsel"; +} + +#[cfg(target_arch = "powerpc")] +mod arch_consts { + pub const ARCH: &'static str = "powerpc"; +} + +#[cfg(test)] +mod tests { + use prelude::v1::*; + use super::*; + use iter::repeat; + use rand::{self, Rng}; + use ffi::{OsString, OsStr}; + + fn make_rand_name() -> OsString { + let mut rng = rand::thread_rng(); + let n = format!("TEST{}", rng.gen_ascii_chars().take(10) + .collect::<String>()); + let n = OsString::from_string(n); + assert!(var(&n).is_none()); + n + } + + fn eq(a: Option<OsString>, b: Option<&str>) { + assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::from_str).map(|s| &*s)); + } + + #[test] + fn test_set_var() { + let n = make_rand_name(); + set_var(&n, "VALUE"); + eq(var(&n), Some("VALUE")); + } + + #[test] + fn test_remove_var() { + let n = make_rand_name(); + set_var(&n, "VALUE"); + remove_var(&n); + eq(var(&n), None); + } + + #[test] + fn test_set_var_overwrite() { + let n = make_rand_name(); + set_var(&n, "1"); + set_var(&n, "2"); + eq(var(&n), Some("2")); + set_var(&n, ""); + eq(var(&n), Some("")); + } + + #[test] + fn test_var_big() { + let mut s = "".to_string(); + let mut i = 0; + while i < 100 { + s.push_str("aaaaaaaaaa"); + i += 1; + } + let n = make_rand_name(); + set_var(&n, s.as_slice()); + eq(var(&n), Some(s.as_slice())); + } + + #[test] + fn test_self_exe_path() { + let path = current_exe(); + assert!(path.is_ok()); + let path = path.unwrap(); + + // Hard to test this function + assert!(path.is_absolute()); + } + + #[test] + fn test_env_set_get_huge() { + let n = make_rand_name(); + let s = repeat("x").take(10000).collect::<String>(); + set_var(&n, &s); + eq(var(&n), Some(s.as_slice())); + remove_var(&n); + eq(var(&n), None); + } + + #[test] + fn test_env_set_var() { + let n = make_rand_name(); + + let mut e = vars(); + set_var(&n, "VALUE"); + assert!(!e.any(|(k, v)| { + &*k == &*n && &*v == "VALUE" + })); + + assert!(vars().any(|(k, v)| { + &*k == &*n && &*v == "VALUE" + })); + } + + #[test] + fn test() { + assert!((!Path::new("test-path").is_absolute())); + + current_dir().unwrap(); + } + + #[test] + #[cfg(windows)] + fn split_paths_windows() { + fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { + split_paths(unparsed).collect::<Vec<_>>() == + parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>() + } + + assert!(check_parse("", &mut [""])); + assert!(check_parse(r#""""#, &mut [""])); + assert!(check_parse(";;", &mut ["", "", ""])); + assert!(check_parse(r"c:\", &mut [r"c:\"])); + assert!(check_parse(r"c:\;", &mut [r"c:\", ""])); + assert!(check_parse(r"c:\;c:\Program Files\", + &mut [r"c:\", r"c:\Program Files\"])); + assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"])); + assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#, + &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"])); + } + + #[test] + #[cfg(unix)] + fn split_paths_unix() { + fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { + split_paths(unparsed).collect::<Vec<_>>() == + parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>() + } + + assert!(check_parse("", &mut [""])); + assert!(check_parse("::", &mut ["", "", ""])); + assert!(check_parse("/", &mut ["/"])); + assert!(check_parse("/:", &mut ["/", ""])); + assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"])); + } + + #[test] + #[cfg(unix)] + fn join_paths_unix() { + fn test_eq(input: &[&str], output: &str) -> bool { + &*join_paths(input.iter().map(|s| *s)).unwrap() == + OsStr::from_str(output) + } + + assert!(test_eq(&[], "")); + assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], + "/bin:/usr/bin:/usr/local/bin")); + assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], + ":/bin:::/usr/bin:")); + assert!(join_paths(["/te:st"].iter().map(|s| *s)).is_err()); + } + + #[test] + #[cfg(windows)] + fn join_paths_windows() { + fn test_eq(input: &[&str], output: &str) -> bool { + &*join_paths(input.iter().map(|s| *s)).unwrap() == + OsStr::from_str(output) + } + + assert!(test_eq(&[], "")); + assert!(test_eq(&[r"c:\windows", r"c:\"], + r"c:\windows;c:\")); + assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], + r";c:\windows;;;c:\;")); + assert!(test_eq(&[r"c:\te;st", r"c:\"], + r#""c:\te;st";c:\"#)); + assert!(join_paths([r#"c:\te"st"#].iter().map(|s| *s)).is_err()); + } + } diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs index 69ada28a4b4..76f925a23f1 100644 --- a/src/libstd/ffi/mod.rs +++ b/src/libstd/ffi/mod.rs @@ -20,7 +20,12 @@ pub use self::c_str::c_str_to_bytes_with_nul; pub use self::os_str::OsString; pub use self::os_str::OsStr; -pub use self::os_str::AsOsStr; mod c_str; mod os_str; + +/// Freely convertible to an `&OsStr` slice. +pub trait AsOsStr { + /// Convert to an `&OsStr` slice. + fn as_os_str(&self) -> &OsStr; +} diff --git a/src/libstd/ffi/os_str.rs b/src/libstd/ffi/os_str.rs index 18e2aa8c098..b8d770e6ad6 100644 --- a/src/libstd/ffi/os_str.rs +++ b/src/libstd/ffi/os_str.rs @@ -41,9 +41,11 @@ use string::{String, CowString}; use ops; use cmp; use hash::{Hash, Hasher, Writer}; +use path::{Path, GenericPath}; use sys::os_str::{Buf, Slice}; use sys_common::{AsInner, IntoInner, FromInner}; +use super::AsOsStr; /// Owned, mutable OS strings. #[derive(Clone)] @@ -69,6 +71,11 @@ impl OsString { OsString { inner: Buf::from_str(s) } } + /// Constructs a new empty `OsString`. + pub fn new() -> OsString { + OsString { inner: Buf::from_string(String::new()) } + } + /// Convert the `OsString` into a `String` if it contains valid Unicode data. /// /// On failure, ownership of the original `OsString` is returned. @@ -82,17 +89,6 @@ impl OsString { } } -#[cfg(stage0)] -impl ops::Index<ops::FullRange> for OsString { - type Output = OsStr; - - #[inline] - fn index(&self, _index: &ops::FullRange) -> &OsStr { - unsafe { mem::transmute(self.inner.as_slice()) } - } -} - -#[cfg(not(stage0))] impl ops::Index<ops::RangeFull> for OsString { type Output = OsStr; @@ -117,6 +113,62 @@ impl Debug for OsString { } } +impl PartialEq for OsString { + fn eq(&self, other: &OsString) -> bool { + &**self == &**other + } +} + +impl PartialEq<str> for OsString { + fn eq(&self, other: &str) -> bool { + &**self == other + } +} + +impl PartialEq<OsString> for str { + fn eq(&self, other: &OsString) -> bool { + &**other == self + } +} + +impl Eq for OsString {} + +impl PartialOrd for OsString { + #[inline] + fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> { + (&**self).partial_cmp(&**other) + } + #[inline] + fn lt(&self, other: &OsString) -> bool { &**self < &**other } + #[inline] + fn le(&self, other: &OsString) -> bool { &**self <= &**other } + #[inline] + fn gt(&self, other: &OsString) -> bool { &**self > &**other } + #[inline] + fn ge(&self, other: &OsString) -> bool { &**self >= &**other } +} + +impl PartialOrd<str> for OsString { + #[inline] + fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> { + (&**self).partial_cmp(other) + } +} + +impl Ord for OsString { + #[inline] + fn cmp(&self, other: &OsString) -> cmp::Ordering { + (&**self).cmp(&**other) + } +} + +impl<'a, S: Hasher + Writer> Hash<S> for OsString { + #[inline] + fn hash(&self, state: &mut S) { + (&**self).hash(state) + } +} + impl OsStr { /// Coerce directly from a `&str` slice to a `&OsStr` slice. pub fn from_str(s: &str) -> &OsStr { @@ -222,10 +274,10 @@ impl ToOwned<OsString> for OsStr { fn to_owned(&self) -> OsString { self.to_os_string() } } -/// Freely convertible to an `&OsStr` slice. -pub trait AsOsStr { - /// Convert to an `&OsStr` slice. - fn as_os_str(&self) -> &OsStr; +impl<'a, T: AsOsStr + ?Sized> AsOsStr for &'a T { + fn as_os_str(&self) -> &OsStr { + (*self).as_os_str() + } } impl AsOsStr for OsStr { @@ -252,6 +304,21 @@ impl AsOsStr for String { } } +#[cfg(unix)] +impl AsOsStr for Path { + fn as_os_str(&self) -> &OsStr { + unsafe { mem::transmute(self.as_vec()) } + } +} + +#[cfg(windows)] +impl AsOsStr for Path { + fn as_os_str(&self) -> &OsStr { + // currently .as_str() is actually infallible on windows + OsStr::from_str(self.as_str().unwrap()) + } +} + impl FromInner<Buf> for OsString { fn from_inner(buf: Buf) -> OsString { OsString { inner: buf } diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index 8e86aa65196..47f5d64e260 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -413,10 +413,6 @@ pub use core::fmt::{LowerExp, UpperExp}; pub use core::fmt::Error; pub use core::fmt::{ArgumentV1, Arguments, write, radix, Radix, RadixFmt}; -#[doc(hidden)] -#[cfg(stage0)] -pub use core::fmt::{argument, argumentuint}; - /// The format function takes a precompiled format string and a list of /// arguments, to return the resulting formatted string. /// diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 96aebb735ef..839983d336d 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -120,14 +120,13 @@ #![feature(staged_api)] #![feature(unboxed_closures)] #![feature(unicode)] -#![cfg_attr(not(stage0), feature(macro_reexport))] +#![feature(macro_reexport)] #![cfg_attr(test, feature(test))] // Don't link to std. We are std. #![no_std] #![deny(missing_docs)] -#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap #[cfg(test)] #[macro_use] @@ -250,6 +249,7 @@ pub mod ffi; pub mod fmt; pub mod old_io; pub mod os; +pub mod env; pub mod path; pub mod rand; pub mod time; diff --git a/src/libstd/old_io/extensions.rs b/src/libstd/old_io/extensions.rs index f429f731b7d..d729c2800ce 100644 --- a/src/libstd/old_io/extensions.rs +++ b/src/libstd/old_io/extensions.rs @@ -406,12 +406,12 @@ mod test { let uints = [0, 1, 2, 42, 10_123, 100_123_456, ::u64::MAX]; let mut writer = Vec::new(); - for i in uints.iter() { + for i in &uints { writer.write_le_u64(*i).unwrap(); } let mut reader = MemReader::new(writer); - for i in uints.iter() { + for i in &uints { assert!(reader.read_le_u64().unwrap() == *i); } } @@ -422,12 +422,12 @@ mod test { let uints = [0, 1, 2, 42, 10_123, 100_123_456, ::u64::MAX]; let mut writer = Vec::new(); - for i in uints.iter() { + for i in &uints { writer.write_be_u64(*i).unwrap(); } let mut reader = MemReader::new(writer); - for i in uints.iter() { + for i in &uints { assert!(reader.read_be_u64().unwrap() == *i); } } @@ -437,12 +437,12 @@ mod test { let ints = [::i32::MIN, -123456, -42, -5, 0, 1, ::i32::MAX]; let mut writer = Vec::new(); - for i in ints.iter() { + for i in &ints { writer.write_be_i32(*i).unwrap(); } let mut reader = MemReader::new(writer); - for i in ints.iter() { + for i in &ints { // this tests that the sign extension is working // (comparing the values as i32 would not test this) assert!(reader.read_be_int_n(4).unwrap() == *i as i64); diff --git a/src/libstd/old_io/fs.rs b/src/libstd/old_io/fs.rs index 0a9aeb849be..abf215988bb 100644 --- a/src/libstd/old_io/fs.rs +++ b/src/libstd/old_io/fs.rs @@ -597,7 +597,7 @@ pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> { return Ok(()) } - let mut comps = path.components(); + let comps = path.components(); let mut curpath = path.root_path().unwrap_or(Path::new(".")); for c in comps { @@ -649,7 +649,7 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { // delete all regular files in the way and push subdirs // on the stack - for child in children.into_iter() { + for child in children { // FIXME(#12795) we should use lstat in all cases let child_type = match cfg!(windows) { true => try!(update_err(stat(&child), path)), @@ -1110,7 +1110,7 @@ mod test { } let files = check!(readdir(dir)); let mut mem = [0u8; 4]; - for f in files.iter() { + for f in &files { { let n = f.filestem_str(); check!(File::open(f).read(&mut mem)); diff --git a/src/libstd/old_io/net/addrinfo.rs b/src/libstd/old_io/net/addrinfo.rs index e37744f3aa3..2b7506b5c34 100644 --- a/src/libstd/old_io/net/addrinfo.rs +++ b/src/libstd/old_io/net/addrinfo.rs @@ -121,7 +121,7 @@ mod test { let ipaddrs = get_host_addresses("localhost").unwrap(); let mut found_local = false; let local_addr = &Ipv4Addr(127, 0, 0, 1); - for addr in ipaddrs.iter() { + for addr in &ipaddrs { found_local = found_local || addr == local_addr; } assert!(found_local); diff --git a/src/libstd/old_io/net/ip.rs b/src/libstd/old_io/net/ip.rs index 565f9d83818..d85251795c8 100644 --- a/src/libstd/old_io/net/ip.rs +++ b/src/libstd/old_io/net/ip.rs @@ -125,7 +125,7 @@ impl<'a> Parser<'a> { // Return result of first successful parser fn read_or<T>(&mut self, parsers: &mut [Box<FnMut(&mut Parser) -> Option<T>>]) -> Option<T> { - for pf in parsers.iter_mut() { + for pf in parsers { match self.read_atomically(|p: &mut Parser| pf.call_mut((p,))) { Some(r) => return Some(r), None => {} diff --git a/src/libstd/old_io/net/mod.rs b/src/libstd/old_io/net/mod.rs index d8394aa8b6a..bbe3a71dcc0 100644 --- a/src/libstd/old_io/net/mod.rs +++ b/src/libstd/old_io/net/mod.rs @@ -36,7 +36,7 @@ fn with_addresses<A, T, F>(addr: A, mut action: F) -> IoResult<T> where let addresses = try!(addr.to_socket_addr_all()); let mut err = DEFAULT_ERROR; - for addr in addresses.into_iter() { + for addr in addresses { match action(addr) { Ok(r) => return Ok(r), Err(e) => err = e diff --git a/src/libstd/old_io/process.rs b/src/libstd/old_io/process.rs index f253f9799e9..61a07bc8208 100644 --- a/src/libstd/old_io/process.rs +++ b/src/libstd/old_io/process.rs @@ -231,6 +231,7 @@ impl Command { self } // Get a mutable borrow of the environment variable map for this `Command`. + #[allow(deprecated)] fn get_env_map<'a>(&'a mut self) -> &'a mut EnvMap { match self.env { Some(ref mut map) => map, @@ -400,7 +401,7 @@ impl fmt::Debug for Command { /// character. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "{:?}", self.program)); - for arg in self.args.iter() { + for arg in &self.args { try!(write!(f, " '{:?}'", arg)); } Ok(()) @@ -1045,7 +1046,7 @@ mod tests { let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap(); let r = os::env(); - for &(ref k, ref v) in r.iter() { + for &(ref k, ref v) in &r { // don't check windows magical empty-named variables assert!(k.is_empty() || output.contains(format!("{}={}", *k, *v).as_slice()), @@ -1063,7 +1064,7 @@ mod tests { let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap(); let r = os::env(); - for &(ref k, ref v) in r.iter() { + for &(ref k, ref v) in &r { // don't check android RANDOM variables if *k != "RANDOM".to_string() { assert!(output.contains(format!("{}={}", diff --git a/src/libstd/old_io/tempfile.rs b/src/libstd/old_io/tempfile.rs index 20cbde5db71..83a42549424 100644 --- a/src/libstd/old_io/tempfile.rs +++ b/src/libstd/old_io/tempfile.rs @@ -10,13 +10,13 @@ //! Temporary files and directories +use env; +use iter::{IteratorExt}; use old_io::{fs, IoError, IoErrorKind, IoResult}; use old_io; -use iter::IteratorExt; use ops::Drop; -use option::Option; use option::Option::{None, Some}; -use os; +use option::Option; use path::{Path, GenericPath}; use rand::{Rng, thread_rng}; use result::Result::{Ok, Err}; @@ -97,8 +97,8 @@ impl TempDir { /// If no directory can be created, `Err` is returned. pub fn new_in(tmpdir: &Path, prefix: &str) -> IoResult<TempDir> { if !tmpdir.is_absolute() { - let abs_tmpdir = try!(os::make_absolute(tmpdir)); - return TempDir::new_in(&abs_tmpdir, prefix); + let cur_dir = try!(env::current_dir()); + return TempDir::new_in(&cur_dir.join(tmpdir), prefix); } let mut rng = thread_rng(); @@ -132,7 +132,7 @@ impl TempDir { /// /// If no directory can be created, `Err` is returned. pub fn new(prefix: &str) -> IoResult<TempDir> { - TempDir::new_in(&os::tmpdir(), prefix) + TempDir::new_in(&env::temp_dir(), prefix) } /// Unwrap the wrapped `std::path::Path` from the `TempDir` wrapper. diff --git a/src/libstd/old_io/test.rs b/src/libstd/old_io/test.rs index f49e2397d42..ee72beccfa8 100644 --- a/src/libstd/old_io/test.rs +++ b/src/libstd/old_io/test.rs @@ -12,8 +12,8 @@ use prelude::v1::*; +use env; use libc; -use os; use std::old_io::net::ip::*; use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; @@ -41,7 +41,7 @@ fn next_test_unix_socket() -> String { pub fn next_test_unix() -> Path { let string = next_test_unix_socket(); if cfg!(unix) { - os::tmpdir().join(string) + env::temp_dir().join(string) } else { Path::new(format!("{}{}", r"\\.\pipe\", string)) } @@ -87,12 +87,12 @@ fn base_port() -> u16 { ]; // FIXME (#9639): This needs to handle non-utf8 paths - let path = os::getcwd().unwrap(); + let path = env::current_dir().unwrap(); let path_s = path.as_str().unwrap(); let mut final_base = base; - for &(dir, base) in bases.iter() { + for &(dir, base) in &bases { if path_s.contains(dir) { final_base = base; break; diff --git a/src/libstd/old_io/util.rs b/src/libstd/old_io/util.rs index 9a55f32c372..f78e3ac1f14 100644 --- a/src/libstd/old_io/util.rs +++ b/src/libstd/old_io/util.rs @@ -144,7 +144,7 @@ impl<W> MultiWriter<W> where W: Writer { impl<W> Writer for MultiWriter<W> where W: Writer { #[inline] fn write_all(&mut self, buf: &[u8]) -> old_io::IoResult<()> { - for writer in self.writers.iter_mut() { + for writer in &mut self.writers { try!(writer.write_all(buf)); } Ok(()) @@ -152,7 +152,7 @@ impl<W> Writer for MultiWriter<W> where W: Writer { #[inline] fn flush(&mut self) -> old_io::IoResult<()> { - for writer in self.writers.iter_mut() { + for writer in &mut self.writers { try!(writer.flush()); } Ok(()) diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 600ca60349a..d92f361af0b 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -34,29 +34,32 @@ use self::MemoryMapKind::*; use self::MapOption::*; use self::MapError::*; +use boxed::Box; use clone::Clone; +use env; use error::{FromError, Error}; +use ffi::{OsString, OsStr}; use fmt; -use old_io::{IoResult, IoError}; use iter::{Iterator, IteratorExt}; -use marker::{Copy, Send}; use libc::{c_void, c_int, c_char}; use libc; -use boxed::Box; +use marker::{Copy, Send}; +use old_io::{IoResult, IoError}; use ops::{Drop, FnOnce}; -use option::Option; use option::Option::{Some, None}; +use option::Option; use path::{Path, GenericPath, BytesContainer}; -use sys; -use sys::os as os_imp; use ptr::PtrExt; use ptr; -use result::Result; use result::Result::{Err, Ok}; +use result::Result; use slice::{AsSlice, SliceExt}; use str::{Str, StrExt}; +use str; use string::{String, ToString}; use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering}; +use sys::os as os_imp; +use sys; use vec::Vec; #[cfg(unix)] use ffi::{self, CString}; @@ -97,23 +100,10 @@ pub const TMPBUF_SZ : uint = 1000u; /// let current_working_directory = os::getcwd().unwrap(); /// println!("The current directory is {:?}", current_working_directory.display()); /// ``` +#[deprecated(since = "1.0.0", reason = "renamed to std::env::current_dir")] +#[unstable(feature = "os")] pub fn getcwd() -> IoResult<Path> { - sys::os::getcwd() -} - -/* -Accessing environment variables is not generally threadsafe. -Serialize access through a global lock. -*/ -fn with_env_lock<T, F>(f: F) -> T where - F: FnOnce() -> T, -{ - use sync::{StaticMutex, MUTEX_INIT}; - - static LOCK: StaticMutex = MUTEX_INIT; - - let _guard = LOCK.lock(); - f() + env::current_dir() } /// Returns a vector of (variable, value) pairs, for all the environment @@ -132,37 +122,22 @@ fn with_env_lock<T, F>(f: F) -> T where /// println!("'{}': '{}'", key, value ); /// } /// ``` +#[deprecated(since = "1.0.0", reason = "use env::vars instead")] +#[unstable(feature = "os")] pub fn env() -> Vec<(String,String)> { - env_as_bytes().into_iter().map(|(k,v)| { - let k = String::from_utf8_lossy(k.as_slice()).into_owned(); - let v = String::from_utf8_lossy(v.as_slice()).into_owned(); - (k,v) + env::vars().map(|(k, v)| { + (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned()) }).collect() } /// Returns a vector of (variable, value) byte-vector pairs for all the /// environment variables of the current process. -pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> { - unsafe { - fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> { - let mut pairs = Vec::new(); - for p in input.iter() { - let mut it = p.splitn(1, |b| *b == b'='); - let key = it.next().unwrap().to_vec(); - let default: &[u8] = &[]; - let val = it.next().unwrap_or(default).to_vec(); - pairs.push((key, val)); - } - pairs - } - with_env_lock(|| { - let unparsed_environ = sys::os::get_env_pairs(); - env_convert(unparsed_environ) - }) - } +#[deprecated(since = "1.0.0", reason = "use env::vars instead")] +#[unstable(feature = "os")] +pub fn env_as_bytes() -> Vec<(Vec<u8>, Vec<u8>)> { + env::vars().map(|(k, v)| (byteify(k), byteify(v))).collect() } -#[cfg(unix)] /// Fetches the environment variable `n` from the current process, returning /// None if the variable isn't set. /// @@ -184,52 +159,32 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> { /// None => println!("{} is not defined in the environment.", key) /// } /// ``` +#[deprecated(since = "1.0.0", reason = "use env::var or env::var_string instead")] +#[unstable(feature = "os")] pub fn getenv(n: &str) -> Option<String> { - getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_owned()) + env::var_string(n).ok() } -#[cfg(unix)] /// Fetches the environment variable `n` byte vector from the current process, /// returning None if the variable isn't set. /// /// # Panics /// /// Panics if `n` has any interior NULs. +#[deprecated(since = "1.0.0", reason = "use env::var instead")] +#[unstable(feature = "os")] pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> { - unsafe { - with_env_lock(|| { - let s = CString::from_slice(n.as_bytes()); - let s = libc::getenv(s.as_ptr()) as *const _; - if s.is_null() { - None - } else { - Some(ffi::c_str_to_bytes(&s).to_vec()) - } - }) - } + env::var(n).map(byteify) } -#[cfg(windows)] -/// Fetches the environment variable `n` from the current process, returning -/// None if the variable isn't set. -pub fn getenv(n: &str) -> Option<String> { - unsafe { - with_env_lock(|| { - use sys::os::fill_utf16_buf_and_decode; - let mut n: Vec<u16> = n.utf16_units().collect(); - n.push(0); - fill_utf16_buf_and_decode(|buf, sz| { - libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz) - }) - }) - } +#[cfg(unix)] +fn byteify(s: OsString) -> Vec<u8> { + use os::unix::*; + s.into_vec() } - #[cfg(windows)] -/// Fetches the environment variable `n` byte vector from the current process, -/// returning None if the variable isn't set. -pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> { - getenv(n).map(|s| s.into_bytes()) +fn byteify(s: OsString) -> Vec<u8> { + s.to_string_lossy().as_bytes().to_vec() } /// Sets the environment variable `n` to the value `v` for the currently running @@ -247,68 +202,30 @@ pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> { /// None => println!("{} is not defined in the environment.", key) /// } /// ``` +#[deprecated(since = "1.0.0", reason = "renamed to env::set_var")] +#[unstable(feature = "os")] pub fn setenv<T: BytesContainer>(n: &str, v: T) { #[cfg(unix)] fn _setenv(n: &str, v: &[u8]) { - unsafe { - with_env_lock(|| { - let k = CString::from_slice(n.as_bytes()); - let v = CString::from_slice(v); - if libc::funcs::posix01::unistd::setenv(k.as_ptr(), - v.as_ptr(), 1) != 0 { - panic!(IoError::last_error()); - } - }) - } + use os::unix::*; + let v: OsString = OsStringExt::from_vec(v.to_vec()); + env::set_var(n, &v) } #[cfg(windows)] fn _setenv(n: &str, v: &[u8]) { - let mut n: Vec<u16> = n.utf16_units().collect(); - n.push(0); - let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect(); - v.push(0); - - unsafe { - with_env_lock(|| { - if libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr()) == 0 { - panic!(IoError::last_error()); - } - }) - } + let v = str::from_utf8(v).unwrap(); + env::set_var(n, v) } _setenv(n, v.container_as_bytes()) } /// Remove a variable from the environment entirely. +#[deprecated(since = "1.0.0", reason = "renamed to env::remove_var")] +#[unstable(feature = "os")] pub fn unsetenv(n: &str) { - #[cfg(unix)] - fn _unsetenv(n: &str) { - unsafe { - with_env_lock(|| { - let nbuf = CString::from_slice(n.as_bytes()); - if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr()) != 0 { - panic!(IoError::last_error()); - } - }) - } - } - - #[cfg(windows)] - fn _unsetenv(n: &str) { - let mut n: Vec<u16> = n.utf16_units().collect(); - n.push(0); - unsafe { - with_env_lock(|| { - if libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null()) == 0 { - panic!(IoError::last_error()); - } - }) - } - } - - _unsetenv(n) + env::remove_var(n) } /// Parses input according to platform conventions for the `PATH` @@ -328,8 +245,12 @@ pub fn unsetenv(n: &str) { /// None => println!("{} is not defined in the environment.", key) /// } /// ``` +#[deprecated(since = "1.0.0", reason = "renamed to env::split_paths")] +#[unstable(feature = "os")] pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> { - sys::os::split_paths(unparsed.container_as_bytes()) + let b = unparsed.container_as_bytes(); + let s = str::from_utf8(b).unwrap(); + env::split_paths(s).collect() } /// Joins a collection of `Path`s appropriately for the `PATH` @@ -353,8 +274,14 @@ pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> { /// paths.push(Path::new("/home/xyz/bin")); /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap()); /// ``` +#[deprecated(since = "1.0.0", reason = "renamed to env::join_paths")] +#[unstable(feature = "os")] pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> { - sys::os::join_paths(paths) + env::join_paths(paths.iter().map(|s| { + str::from_utf8(s.container_as_bytes()).unwrap() + })).map(|s| { + s.to_string_lossy().into_owned().into_bytes() + }).map_err(|_| "failed to join paths") } /// A low-level OS in-memory pipe. @@ -388,6 +315,8 @@ pub unsafe fn pipe() -> IoResult<Pipe> { /// Returns the proper dll filename for the given basename of a file /// as a String. #[cfg(not(target_os="ios"))] +#[deprecated(since = "1.0.0", reason = "this function will be removed, use the constants directly")] +#[unstable(feature = "os")] pub fn dll_filename(base: &str) -> String { format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX) } @@ -405,8 +334,10 @@ pub fn dll_filename(base: &str) -> String { /// None => println!("Unable to get the path of this executable!") /// }; /// ``` +#[deprecated(since = "1.0.0", reason = "renamed to env::current_exe")] +#[unstable(feature = "os")] pub fn self_exe_name() -> Option<Path> { - sys::os::load_self().and_then(Path::new_opt) + env::current_exe().ok() } /// Optionally returns the filesystem path to the current executable which is @@ -424,8 +355,10 @@ pub fn self_exe_name() -> Option<Path> { /// None => println!("Impossible to fetch the path of this executable.") /// }; /// ``` +#[deprecated(since = "1.0.0", reason = "use env::current_exe + dir_path/pop")] +#[unstable(feature = "os")] pub fn self_exe_path() -> Option<Path> { - self_exe_name().map(|mut p| { p.pop(); p }) + env::current_exe().ok().map(|mut p| { p.pop(); p }) } /// Optionally returns the path to the current user's home directory if known. @@ -452,6 +385,9 @@ pub fn self_exe_path() -> Option<Path> { /// None => println!("Impossible to get your home dir!") /// } /// ``` +#[deprecated(since = "1.0.0", reason = "renamed to env::home_dir")] +#[allow(deprecated)] +#[unstable(feature = "os")] pub fn homedir() -> Option<Path> { #[inline] #[cfg(unix)] @@ -487,6 +423,9 @@ pub fn homedir() -> Option<Path> { /// On Windows, returns the value of, in order, the 'TMP', 'TEMP', /// 'USERPROFILE' environment variable if any are set and not the empty /// string. Otherwise, tmpdir returns the path to the Windows directory. +#[deprecated(since = "1.0.0", reason = "renamed to env::temp_dir")] +#[allow(deprecated)] +#[unstable(feature = "os")] pub fn tmpdir() -> Path { return lookup(); @@ -542,11 +481,13 @@ pub fn tmpdir() -> Path { // NB: this is here rather than in path because it is a form of environment // querying; what it does depends on the process working directory, not just // the input paths. +#[deprecated(since = "1.0.0", reason = "use env::current_dir + .join directly")] +#[unstable(feature = "os")] pub fn make_absolute(p: &Path) -> IoResult<Path> { if p.is_absolute() { Ok(p.clone()) } else { - getcwd().map(|mut cwd| { + env::current_dir().map(|mut cwd| { cwd.push(p); cwd }) @@ -565,6 +506,8 @@ pub fn make_absolute(p: &Path) -> IoResult<Path> { /// assert!(os::change_dir(&root).is_ok()); /// println!("Successfully changed working directory to {}!", root.display()); /// ``` +#[deprecated(since = "1.0.0", reason = "renamed to env::set_current_dir")] +#[unstable(feature = "os")] pub fn change_dir(p: &Path) -> IoResult<()> { return sys::os::chdir(p); } @@ -592,8 +535,6 @@ pub fn last_os_error() -> String { error_string(errno() as uint) } -static EXIT_STATUS: AtomicIsize = ATOMIC_ISIZE_INIT; - /// Sets the process exit code /// /// Sets the exit code returned by the process if all supervised tasks @@ -602,14 +543,18 @@ static EXIT_STATUS: AtomicIsize = ATOMIC_ISIZE_INIT; /// ignored and the process exits with the default panic status. /// /// Note that this is not synchronized against modifications of other threads. +#[deprecated(since = "1.0.0", reason = "renamed to env::set_exit_status")] +#[unstable(feature = "os")] pub fn set_exit_status(code: int) { - EXIT_STATUS.store(code, Ordering::SeqCst) + env::set_exit_status(code as i32) } /// Fetches the process's current exit code. This defaults to 0 and can change /// by calling `set_exit_status`. +#[deprecated(since = "1.0.0", reason = "renamed to env::get_exit_status")] +#[unstable(feature = "os")] pub fn get_exit_status() -> int { - EXIT_STATUS.load(Ordering::SeqCst) + env::get_exit_status() as isize } #[cfg(target_os = "macos")] @@ -693,7 +638,8 @@ fn real_args_as_bytes() -> Vec<Vec<u8>> { #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] fn real_args_as_bytes() -> Vec<Vec<u8>> { use rt; rt::args::clone().unwrap_or_else(|| vec![]) @@ -726,7 +672,7 @@ fn real_args() -> Vec<String> { // Push it onto the list. let ptr = ptr as *const u16; let buf = slice::from_raw_buf(&ptr, len); - let opt_s = String::from_utf16(sys::os::truncate_utf16_at_nul(buf)); + let opt_s = String::from_utf16(sys::truncate_utf16_at_nul(buf)); opt_s.ok().expect("CommandLineToArgvW returned invalid UTF-16") }).collect(); @@ -777,12 +723,16 @@ extern "system" { /// println!("{}", argument); /// } /// ``` +#[deprecated(since = "1.0.0", reason = "use env::args instead")] +#[unstable(feature = "os")] pub fn args() -> Vec<String> { real_args() } /// Returns the arguments which this program was started with (normally passed /// via the command line) as byte vectors. +#[deprecated(since = "1.0.0", reason = "use env::args_raw instead")] +#[unstable(feature = "os")] pub fn args_as_bytes() -> Vec<Vec<u8>> { real_args_as_bytes() } @@ -790,11 +740,13 @@ pub fn args_as_bytes() -> Vec<Vec<u8>> { #[cfg(target_os = "macos")] extern { // These functions are in crt_externs.h. - pub fn _NSGetArgc() -> *mut c_int; - pub fn _NSGetArgv() -> *mut *mut *mut c_char; + fn _NSGetArgc() -> *mut c_int; + fn _NSGetArgv() -> *mut *mut *mut c_char; } /// Returns the page size of the current architecture in bytes. +#[deprecated(since = "1.0.0", reason = "renamed to env::page_size")] +#[unstable(feature = "os")] pub fn page_size() -> uint { sys::os::page_size() } @@ -970,9 +922,9 @@ impl MemoryMap { let mut fd = -1; let mut offset = 0; let mut custom_flags = false; - let len = round_up(min_len, page_size()); + let len = round_up(min_len, env::page_size()); - for &o in options.iter() { + for &o in options { match o { MapReadable => { prot |= libc::PROT_READ; }, MapWritable => { prot |= libc::PROT_WRITE; }, @@ -1020,7 +972,7 @@ impl MemoryMap { /// Granularity that the offset or address must be for `MapOffset` and /// `MapAddr` respectively. pub fn granularity() -> uint { - page_size() + env::page_size() } } @@ -1049,9 +1001,9 @@ impl MemoryMap { let mut executable = false; let mut handle: HANDLE = libc::INVALID_HANDLE_VALUE; let mut offset: uint = 0; - let len = round_up(min_len, page_size()); + let len = round_up(min_len, env::page_size()); - for &o in options.iter() { + for &o in options { match o { MapReadable => { readable = true; }, MapWritable => { writable = true; }, @@ -1184,6 +1136,8 @@ impl MemoryMap { } #[cfg(target_os = "linux")] +#[deprecated(since = "1.0.0", reason = "renamed to env::consts")] +#[unstable(feature = "os")] pub mod consts { pub use os::arch_consts::ARCH; @@ -1215,6 +1169,8 @@ pub mod consts { } #[cfg(target_os = "macos")] +#[deprecated(since = "1.0.0", reason = "renamed to env::consts")] +#[unstable(feature = "os")] pub mod consts { pub use os::arch_consts::ARCH; @@ -1246,6 +1202,8 @@ pub mod consts { } #[cfg(target_os = "ios")] +#[deprecated(since = "1.0.0", reason = "renamed to env::consts")] +#[unstable(feature = "os")] pub mod consts { pub use os::arch_consts::ARCH; @@ -1265,6 +1223,8 @@ pub mod consts { } #[cfg(target_os = "freebsd")] +#[deprecated(since = "1.0.0", reason = "renamed to env::consts")] +#[unstable(feature = "os")] pub mod consts { pub use os::arch_consts::ARCH; @@ -1296,6 +1256,8 @@ pub mod consts { } #[cfg(target_os = "dragonfly")] +#[deprecated(since = "1.0.0", reason = "renamed to env::consts")] +#[unstable(feature = "os")] pub mod consts { pub use os::arch_consts::ARCH; @@ -1326,7 +1288,40 @@ pub mod consts { pub const EXE_EXTENSION: &'static str = ""; } +#[cfg(target_os = "openbsd")] +pub mod consts { + pub use os::arch_consts::ARCH; + + pub const FAMILY: &'static str = "unix"; + + /// A string describing the specific operating system in use: in this + /// case, `openbsd`. + pub const SYSNAME: &'static str = "openbsd"; + + /// Specifies the filename prefix used for shared libraries on this + /// platform: in this case, `lib`. + pub const DLL_PREFIX: &'static str = "lib"; + + /// Specifies the filename suffix used for shared libraries on this + /// platform: in this case, `.so`. + pub const DLL_SUFFIX: &'static str = ".so"; + + /// Specifies the file extension used for shared libraries on this + /// platform that goes after the dot: in this case, `so`. + pub const DLL_EXTENSION: &'static str = "so"; + + /// Specifies the filename suffix used for executable binaries on this + /// platform: in this case, the empty string. + pub const EXE_SUFFIX: &'static str = ""; + + /// Specifies the file extension, if any, used for executable binaries + /// on this platform: in this case, the empty string. + pub const EXE_EXTENSION: &'static str = ""; +} + #[cfg(target_os = "android")] +#[deprecated(since = "1.0.0", reason = "renamed to env::consts")] +#[unstable(feature = "os")] pub mod consts { pub use os::arch_consts::ARCH; @@ -1358,6 +1353,8 @@ pub mod consts { } #[cfg(target_os = "windows")] +#[deprecated(since = "1.0.0", reason = "renamed to env::consts")] +#[unstable(feature = "os")] pub mod consts { pub use os::arch_consts::ARCH; @@ -1522,7 +1519,7 @@ mod tests { fn test_env_getenv() { let e = env(); assert!(e.len() > 0u); - for p in e.iter() { + for p in &e { let (n, v) = (*p).clone(); debug!("{}", n); let v2 = getenv(n.as_slice()); @@ -1577,7 +1574,7 @@ mod tests { setenv("HOME", ""); assert!(os::homedir().is_none()); - for s in oldhome.iter() { + if let Some(s) = oldhome { setenv("HOME", s.as_slice()); } } @@ -1606,10 +1603,10 @@ mod tests { setenv("USERPROFILE", "/home/PaloAlto"); assert!(os::homedir() == Some(Path::new("/home/MountainView"))); - for s in oldhome.iter() { + if let Some(s) = oldhome { setenv("HOME", s.as_slice()); } - for s in olduserprofile.iter() { + if let Some(s) = olduserprofile { setenv("USERPROFILE", s.as_slice()); } } diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index b5409da9c9c..0d80258d7e0 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -68,8 +68,6 @@ use fmt; use iter::IteratorExt; use option::Option; use option::Option::{None, Some}; -#[cfg(stage0)] -use ops::FullRange; use str; use str::StrExt; use string::{String, CowString}; @@ -625,11 +623,11 @@ pub trait GenericPath: Clone + GenericPathUnsafe { fn push_many<T: BytesContainer>(&mut self, paths: &[T]) { let t: Option<&T> = None; if BytesContainer::is_str(t) { - for p in paths.iter() { + for p in paths { self.push(p.container_as_str().unwrap()) } } else { - for p in paths.iter() { + for p in paths { self.push(p.container_as_bytes()) } } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index 6a0c8a93010..69f815e3f8b 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -31,7 +31,7 @@ pub type Components<'a> = Split<'a, u8, fn(&u8) -> bool>; /// Iterator that yields successive components of a Path as Option<&str> pub type StrComponents<'a> = - Map<&'a [u8], Option<&'a str>, Components<'a>, fn(&[u8]) -> Option<&str>>; + Map<Components<'a>, fn(&[u8]) -> Option<&str>>; /// Represents a POSIX file path #[derive(Clone)] diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index b524b89ef9f..fcdebaf2cd3 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -25,8 +25,6 @@ use iter::{AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map, repeat}; use mem; use option::Option::{self, Some, None}; -#[cfg(stage0)] -use ops::FullRange; use result::Result::{self, Ok, Err}; use slice::{SliceExt, SliceConcatExt}; use str::{SplitTerminator, FromStr, StrExt}; @@ -40,11 +38,11 @@ use super::{contains_nul, BytesContainer, GenericPath, GenericPathUnsafe}; /// Each component is yielded as Option<&str> for compatibility with PosixPath, but /// every component in WindowsPath is guaranteed to be Some. pub type StrComponents<'a> = - Map<&'a str, Option<&'a str>, SplitTerminator<'a, char>, fn(&'a str) -> Option<&'a str>>; + Map<SplitTerminator<'a, char>, fn(&'a str) -> Option<&'a str>>; /// Iterator that yields successive components of a Path as &[u8] pub type Components<'a> = - Map<Option<&'a str>, &'a [u8], StrComponents<'a>, fn(Option<&str>) -> &[u8]>; + Map<StrComponents<'a>, fn(Option<&str>) -> &[u8]>; /// Represents a Windows path // Notes for Windows path impl: diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index b3c4ffa5120..2398485afef 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -18,10 +18,6 @@ #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce}; -#[cfg(stage0)] -#[unstable(feature = "std_misc")] -#[doc(no_inline)] pub use ops::FullRange; - // Reexported functions #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use mem::drop; diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index 211abc2fc83..cc72c5bed99 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -464,7 +464,7 @@ mod test { // check every remainder mod 8, both in small and big vectors. let lengths = [0, 1, 2, 3, 4, 5, 6, 7, 80, 81, 82, 83, 84, 85, 86, 87]; - for &n in lengths.iter() { + for &n in &lengths { let mut v = repeat(0u8).take(n).collect::<Vec<_>>(); r.fill_bytes(v.as_mut_slice()); diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 992afb2d10f..4b45d5501c2 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -404,7 +404,7 @@ mod test { } // start all the tasks - for tx in txs.iter() { + for tx in &txs { tx.send(()).unwrap(); } } diff --git a/src/libstd/rt/args.rs b/src/libstd/rt/args.rs index b63f2e2d73a..b3bed4af962 100644 --- a/src/libstd/rt/args.rs +++ b/src/libstd/rt/args.rs @@ -1,4 +1,4 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -42,7 +42,8 @@ pub fn clone() -> Option<Vec<Vec<u8>>> { imp::clone() } #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] mod imp { use prelude::v1::*; diff --git a/src/libstd/rt/at_exit_imp.rs b/src/libstd/rt/at_exit_imp.rs index 5823f8453d8..3f15cf71ec3 100644 --- a/src/libstd/rt/at_exit_imp.rs +++ b/src/libstd/rt/at_exit_imp.rs @@ -58,7 +58,7 @@ pub fn cleanup() { // If we never called init, not need to cleanup! if queue as uint != 0 { let queue: Box<Queue> = mem::transmute(queue); - for to_run in queue.into_iter() { + for to_run in *queue { to_run.invoke(()); } } diff --git a/src/libstd/rt/backtrace.rs b/src/libstd/rt/backtrace.rs index f2d66e1a4d7..905cc06c4f0 100644 --- a/src/libstd/rt/backtrace.rs +++ b/src/libstd/rt/backtrace.rs @@ -14,7 +14,7 @@ use prelude::v1::*; -use os; +use env; use sync::atomic::{self, Ordering}; pub use sys::backtrace::write; @@ -29,7 +29,7 @@ pub fn log_enabled() -> bool { _ => {} } - let val = match os::getenv("RUST_BACKTRACE") { + let val = match env::var("RUST_BACKTRACE") { Some(..) => 2, None => 1, }; diff --git a/src/libstd/rt/libunwind.rs b/src/libstd/rt/libunwind.rs index dd9923307d6..43e3a43f56d 100644 --- a/src/libstd/rt/libunwind.rs +++ b/src/libstd/rt/libunwind.rs @@ -101,7 +101,7 @@ pub type _Unwind_Exception_Cleanup_Fn = #[link(name = "gcc_s")] extern {} -#[cfg(target_os = "android")] +#[cfg(any(target_os = "android", target_os = "openbsd"))] #[link(name = "gcc")] extern {} diff --git a/src/libstd/rt/mod.rs b/src/libstd/rt/mod.rs index 7e19f1cac2c..00088d6d99a 100644 --- a/src/libstd/rt/mod.rs +++ b/src/libstd/rt/mod.rs @@ -65,7 +65,7 @@ fn lang_start(main: *const u8, argc: int, argv: *const *const u8) -> int { use prelude::v1::*; use mem; - use os; + use env; use rt; use sys_common::thread_info::{self, NewThread}; use sys_common; @@ -131,7 +131,7 @@ fn lang_start(main: *const u8, argc: int, argv: *const *const u8) -> int { if failed { rt::DEFAULT_ERROR_CODE } else { - os::get_exit_status() + env::get_exit_status() as isize } } diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index fb40a6c8f60..81ca5aa0e8a 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -160,7 +160,7 @@ pub fn panicking() -> bool { // An uninlined, unmangled function upon which to slap yer breakpoints #[inline(never)] #[no_mangle] -#[cfg_attr(not(stage0), allow(private_no_mangle_fns))] +#[allow(private_no_mangle_fns)] fn rust_panic(cause: Box<Any + Send>) -> ! { rtdebug!("begin_unwind()"); @@ -238,7 +238,7 @@ pub mod eabi { #[lang="eh_personality"] #[no_mangle] // referenced from rust_try.ll - #[cfg_attr(not(stage0), allow(private_no_mangle_fns))] + #[allow(private_no_mangle_fns)] extern fn rust_eh_personality( version: c_int, actions: uw::_Unwind_Action, @@ -551,7 +551,7 @@ fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) -> let amt = CALLBACK_CNT.load(Ordering::SeqCst); &CALLBACKS[..cmp::min(amt, MAX_CALLBACKS)] }; - for cb in callbacks.iter() { + for cb in callbacks { match cb.load(Ordering::SeqCst) { 0 => {} n => { diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index f5727a38b69..86d21cf7278 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -13,6 +13,7 @@ use prelude::v1::*; use cmp; +use env; use fmt; use intrinsics; use libc::{self, uintptr_t}; @@ -51,7 +52,7 @@ pub fn min_stack() -> uint { 0 => {} n => return n - 1, } - let amt = os::getenv("RUST_MIN_STACK").and_then(|s| s.parse().ok()); + let amt = env::var_string("RUST_MIN_STACK").ok().and_then(|s| s.parse().ok()); let amt = amt.unwrap_or(2 * 1024 * 1024); // 0 is our sentinel value, so ensure that we'll never see 0 after // initialization has run @@ -62,15 +63,15 @@ pub fn min_stack() -> uint { /// Get's the number of scheduler threads requested by the environment /// either `RUST_THREADS` or `num_cpus`. pub fn default_sched_threads() -> uint { - match os::getenv("RUST_THREADS") { - Some(nstr) => { + match env::var_string("RUST_THREADS") { + Ok(nstr) => { let opt_n: Option<uint> = nstr.parse().ok(); match opt_n { Some(n) if n > 0 => n, _ => panic!("`RUST_THREADS` is `{}`, should be a positive integer", nstr) } } - None => { + Err(..) => { if limit_thread_creation_due_to_osx_and_valgrind() { 1 } else { diff --git a/src/libstd/rtdeps.rs b/src/libstd/rtdeps.rs index 06b68162487..1392bc815c4 100644 --- a/src/libstd/rtdeps.rs +++ b/src/libstd/rtdeps.rs @@ -1,4 +1,4 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -39,7 +39,7 @@ extern {} #[link(name = "pthread")] extern {} -#[cfg(target_os = "dragonfly")] +#[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] #[link(name = "pthread")] extern {} diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 95b570dd9c8..2dfc708e15b 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -508,7 +508,7 @@ mod tests { } // Wait for children to pass their asserts - for r in children.into_iter() { + for r in children { assert!(r.join().is_ok()); } diff --git a/src/libstd/sys/common/mutex.rs b/src/libstd/sys/common/mutex.rs index 9aea0fb3b31..0ca22826700 100644 --- a/src/libstd/sys/common/mutex.rs +++ b/src/libstd/sys/common/mutex.rs @@ -24,13 +24,6 @@ unsafe impl Sync for Mutex {} pub const MUTEX_INIT: Mutex = Mutex(imp::MUTEX_INIT); impl Mutex { - /// Creates a newly initialized mutex. - /// - /// Behavior is undefined if the mutex is moved after the first method is - /// called on the mutex. - #[inline] - pub unsafe fn new() -> Mutex { Mutex(imp::Mutex::new()) } - /// Lock the mutex blocking the current thread until it is available. /// /// Behavior is undefined if the mutex has been moved between this and any diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys/common/net.rs index 51b6e0a1c1e..833de8adda4 100644 --- a/src/libstd/sys/common/net.rs +++ b/src/libstd/sys/common/net.rs @@ -1,4 +1,4 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -554,7 +554,7 @@ pub fn await(fds: &[sock_t], deadline: Option<u64>, status: SocketStatus) -> IoResult<()> { let mut set: c::fd_set = unsafe { mem::zeroed() }; let mut max = 0; - for &fd in fds.iter() { + for &fd in fds { c::fd_set(&mut set, fd); max = cmp::max(max, fd + 1); } @@ -694,10 +694,16 @@ impl TcpStream { setsockopt(self.fd(), libc::IPPROTO_TCP, libc::TCP_KEEPIDLE, seconds as libc::c_int) } + #[cfg(target_os = "openbsd")] + fn set_tcp_keepalive(&mut self, seconds: uint) -> IoResult<()> { + setsockopt(self.fd(), libc::IPPROTO_TCP, libc::SO_KEEPALIVE, + seconds as libc::c_int) + } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly")))] + target_os = "dragonfly", + target_os = "openbsd")))] fn set_tcp_keepalive(&mut self, _seconds: uint) -> IoResult<()> { Ok(()) } diff --git a/src/libstd/sys/common/rwlock.rs b/src/libstd/sys/common/rwlock.rs index df016b9e293..fe374e1fd78 100644 --- a/src/libstd/sys/common/rwlock.rs +++ b/src/libstd/sys/common/rwlock.rs @@ -21,13 +21,6 @@ pub struct RWLock(imp::RWLock); pub const RWLOCK_INIT: RWLock = RWLock(imp::RWLOCK_INIT); impl RWLock { - /// Creates a new instance of an RWLock. - /// - /// Usage of an RWLock is undefined if it is moved after its first use (any - /// function calls below). - #[inline] - pub unsafe fn new() -> RWLock { RWLock(imp::RWLock::new()) } - /// Acquire shared access to the underlying lock, blocking the current /// thread to do so. /// diff --git a/src/libstd/sys/common/stack.rs b/src/libstd/sys/common/stack.rs index 88bb9395cf1..8dd2f154fa8 100644 --- a/src/libstd/sys/common/stack.rs +++ b/src/libstd/sys/common/stack.rs @@ -227,18 +227,13 @@ pub unsafe fn record_sp_limit(limit: uint) { } // aarch64 - FIXME(AARCH64): missing... - #[cfg(target_arch = "aarch64")] - unsafe fn target_record_sp_limit(_: uint) { - } - // powerpc - FIXME(POWERPC): missing... - #[cfg(target_arch = "powerpc")] - unsafe fn target_record_sp_limit(_: uint) { - } - - - // iOS segmented stack is disabled for now, see related notes - #[cfg(all(target_arch = "arm", target_os = "ios"))] #[inline(always)] + // arm-ios - iOS segmented stack is disabled for now, see related notes + // openbsd - segmented stack is disabled + #[cfg(any(target_arch = "aarch64", + target_arch = "powerpc", + all(target_arch = "arm", target_os = "ios"), + target_os = "openbsd"))] unsafe fn target_record_sp_limit(_: uint) { } } @@ -327,21 +322,17 @@ pub unsafe fn get_sp_limit() -> uint { } // aarch64 - FIXME(AARCH64): missing... - #[cfg(target_arch = "aarch64")] - unsafe fn target_get_sp_limit() -> uint { - 1024 - } - - // powepc - FIXME(POWERPC): missing... - #[cfg(target_arch = "powerpc")] - unsafe fn target_get_sp_limit() -> uint { - 1024 - } - - // iOS doesn't support segmented stacks yet. This function might - // be called by runtime though so it is unsafe to mark it as - // unreachable, let's return a fixed constant. - #[cfg(all(target_arch = "arm", target_os = "ios"))] #[inline(always)] + // powerpc - FIXME(POWERPC): missing... + // arm-ios - iOS doesn't support segmented stacks yet. + // openbsd - OpenBSD doesn't support segmented stacks. + // + // This function might be called by runtime though + // so it is unsafe to unreachable, let's return a fixed constant. + #[cfg(any(target_arch = "aarch64", + target_arch = "powerpc", + all(target_arch = "arm", target_os = "ios"), + target_os = "openbsd"))] + #[inline(always)] unsafe fn target_get_sp_limit() -> uint { 1024 } diff --git a/src/libstd/sys/common/wtf8.rs b/src/libstd/sys/common/wtf8.rs index fdcb0c19f30..b30af10986b 100644 --- a/src/libstd/sys/common/wtf8.rs +++ b/src/libstd/sys/common/wtf8.rs @@ -366,7 +366,7 @@ impl FromIterator<CodePoint> for Wtf8Buf { /// This replaces surrogate code point pairs with supplementary code points, /// like concatenating ill-formed UTF-16 strings effectively would. impl Extend<CodePoint> for Wtf8Buf { - fn extend<T: Iterator<Item=CodePoint>>(&mut self, mut iterator: T) { + fn extend<T: Iterator<Item=CodePoint>>(&mut self, iterator: T) { let (low, _high) = iterator.size_hint(); // Lower bound of one byte per code point (ASCII only) self.bytes.reserve(low); @@ -680,17 +680,6 @@ impl ops::Index<ops::RangeTo<usize>> for Wtf8 { } } -#[cfg(stage0)] -impl ops::Index<ops::FullRange> for Wtf8 { - type Output = Wtf8; - - #[inline] - fn index(&self, _range: &ops::FullRange) -> &Wtf8 { - self - } -} - -#[cfg(not(stage0))] impl ops::Index<ops::RangeFull> for Wtf8 { type Output = Wtf8; diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index e310b8f6d90..5e512e9261b 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -240,7 +240,7 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { #[cfg(not(any(target_os = "macos", target_os = "ios")))] fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { - use os; + use env; use ptr; //////////////////////////////////////////////////////////////////////// @@ -318,8 +318,9 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256]; if !STATE.is_null() { return STATE } let selfname = if cfg!(target_os = "freebsd") || - cfg!(target_os = "dragonfly") { - os::self_exe_name() + cfg!(target_os = "dragonfly") || + cfg!(target_os = "openbsd") { + env::current_exe().ok() } else { None }; diff --git a/src/libstd/sys/unix/c.rs b/src/libstd/sys/unix/c.rs index 9016d1a2c99..89bd9a23406 100644 --- a/src/libstd/sys/unix/c.rs +++ b/src/libstd/sys/unix/c.rs @@ -23,7 +23,8 @@ use libc; #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] pub const FIONBIO: libc::c_ulong = 0x8004667e; #[cfg(any(all(target_os = "linux", any(target_arch = "x86", @@ -41,7 +42,8 @@ pub const FIONBIO: libc::c_ulong = 0x667e; #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] pub const FIOCLEX: libc::c_ulong = 0x20006601; #[cfg(any(all(target_os = "linux", any(target_arch = "x86", @@ -59,13 +61,61 @@ pub const FIOCLEX: libc::c_ulong = 0x6601; #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] pub const MSG_DONTWAIT: libc::c_int = 0x80; #[cfg(any(target_os = "linux", target_os = "android"))] pub const MSG_DONTWAIT: libc::c_int = 0x40; pub const WNOHANG: libc::c_int = 1; +#[cfg(target_os = "linux")] +pub const _SC_GETPW_R_SIZE_MAX: libc::c_int = 70; +#[cfg(any(target_os = "macos", + target_os = "freebsd"))] +pub const _SC_GETPW_R_SIZE_MAX: libc::c_int = 71; +#[cfg(target_os = "android")] +pub const _SC_GETPW_R_SIZE_MAX: libc::c_int = 0x0048; + +#[repr(C)] +#[cfg(target_os = "linux")] +pub struct passwd { + pub pw_name: *mut libc::c_char, + pub pw_passwd: *mut libc::c_char, + pub pw_uid: libc::uid_t, + pub pw_gid: libc::gid_t, + pub pw_gecos: *mut libc::c_char, + pub pw_dir: *mut libc::c_char, + pub pw_shell: *mut libc::c_char, +} + +#[repr(C)] +#[cfg(any(target_os = "macos", + target_os = "freebsd"))] +pub struct passwd { + pub pw_name: *mut libc::c_char, + pub pw_passwd: *mut libc::c_char, + pub pw_uid: libc::uid_t, + pub pw_gid: libc::gid_t, + pub pw_change: libc::time_t, + pub pw_class: *mut libc::c_char, + pub pw_gecos: *mut libc::c_char, + pub pw_dir: *mut libc::c_char, + pub pw_shell: *mut libc::c_char, + pub pw_expire: libc::time_t, +} + +#[repr(C)] +#[cfg(target_os = "android")] +pub struct passwd { + pub pw_name: *mut libc::c_char, + pub pw_passwd: *mut libc::c_char, + pub pw_uid: libc::uid_t, + pub pw_gid: libc::gid_t, + pub pw_dir: *mut libc::c_char, + pub pw_shell: *mut libc::c_char, +} + extern { pub fn gettimeofday(timeval: *mut libc::timeval, tzp: *mut libc::c_void) -> libc::c_int; @@ -92,6 +142,12 @@ extern { pub fn sigaddset(set: *mut sigset_t, signum: libc::c_int) -> libc::c_int; pub fn sigdelset(set: *mut sigset_t, signum: libc::c_int) -> libc::c_int; pub fn sigemptyset(set: *mut sigset_t) -> libc::c_int; + + pub fn getpwuid_r(uid: libc::uid_t, + pwd: *mut passwd, + buf: *mut libc::c_char, + buflen: libc::size_t, + result: *mut *mut passwd) -> libc::c_int; } #[cfg(any(target_os = "macos", target_os = "ios"))] @@ -111,6 +167,7 @@ mod select { #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "dragonfly", + target_os = "openbsd", target_os = "linux"))] mod select { use uint; @@ -235,7 +292,8 @@ mod signal { #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] mod signal { use libc; @@ -248,7 +306,9 @@ mod signal { pub const SA_SIGINFO: libc::c_int = 0x0040; pub const SIGCHLD: libc::c_int = 20; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(any(target_os = "macos", + target_os = "ios", + target_os = "openbsd"))] pub type sigset_t = u32; #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] #[repr(C)] diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index f2f2e7436bf..b03b9046966 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -141,7 +141,7 @@ pub fn retry<T, F> (mut f: F) -> T where let one: T = Int::one(); loop { let n = f(); - if n == -one && os::errno() == libc::EINTR as int { } + if n == -one && os::errno() == libc::EINTR as i32 { } else { return n } } } @@ -155,7 +155,7 @@ pub fn ms_to_timeval(ms: u64) -> libc::timeval { pub fn wouldblock() -> bool { let err = os::errno(); - err == libc::EWOULDBLOCK as int || err == libc::EAGAIN as int + err == libc::EWOULDBLOCK as i32 || err == libc::EAGAIN as i32 } pub fn set_nonblocking(fd: sock_t, nb: bool) -> IoResult<()> { diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index dd343baa7c9..b3f37962945 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -11,93 +11,74 @@ //! Implementation of `std::os` functionality for unix systems use prelude::v1::*; +use os::unix::*; -use error::{FromError, Error}; -use ffi::{self, CString}; +use error::Error as StdError; +use ffi::{self, CString, OsString, OsStr, AsOsStr}; use fmt; -use old_io::{IoError, IoResult}; +use iter; use libc::{self, c_int, c_char, c_void}; -use os::TMPBUF_SZ; -use os; -use path::{BytesContainer}; +use mem; +use old_io::{IoResult, IoError, fs}; use ptr; +use slice; use str; +use sys::c; use sys::fs::FileDesc; +use vec; -const BUF_BYTES : uint = 2048u; +const BUF_BYTES: usize = 2048; +const TMPBUF_SZ: usize = 128; /// Returns the platform-specific value of errno -pub fn errno() -> int { +pub fn errno() -> i32 { #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))] - fn errno_location() -> *const c_int { - extern { - fn __error() -> *const c_int; - } - unsafe { - __error() - } + unsafe fn errno_location() -> *const c_int { + extern { fn __error() -> *const c_int; } + __error() } #[cfg(target_os = "dragonfly")] + unsafe fn errno_location() -> *const c_int { + extern { fn __dfly_error() -> *const c_int; } + __dfly_error() + } + + #[cfg(target_os = "openbsd")] fn errno_location() -> *const c_int { extern { - fn __dfly_error() -> *const c_int; + fn __errno() -> *const c_int; } unsafe { - __dfly_error() + __errno() } } #[cfg(any(target_os = "linux", target_os = "android"))] - fn errno_location() -> *const c_int { - extern { - fn __errno_location() -> *const c_int; - } - unsafe { - __errno_location() - } + unsafe fn errno_location() -> *const c_int { + extern { fn __errno_location() -> *const c_int; } + __errno_location() } unsafe { - (*errno_location()) as int + (*errno_location()) as i32 } } /// Get a detailed string description for the given error number pub fn error_string(errno: i32) -> String { - #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "android", - target_os = "freebsd", - target_os = "dragonfly"))] - fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) - -> c_int { - extern { - fn strerror_r(errnum: c_int, buf: *mut c_char, - buflen: libc::size_t) -> c_int; - } - unsafe { - strerror_r(errnum, buf, buflen) - } - } - - // GNU libc provides a non-compliant version of strerror_r by default - // and requires macros to instead use the POSIX compliant variant. - // So we just use __xpg_strerror_r which is always POSIX compliant #[cfg(target_os = "linux")] - fn strerror_r(errnum: c_int, buf: *mut c_char, - buflen: libc::size_t) -> c_int { - extern { - fn __xpg_strerror_r(errnum: c_int, - buf: *mut c_char, - buflen: libc::size_t) - -> c_int; - } - unsafe { - __xpg_strerror_r(errnum, buf, buflen) - } + extern { + #[link_name = "__xpg_strerror_r"] + fn strerror_r(errnum: c_int, buf: *mut c_char, + buflen: libc::size_t) -> c_int; + } + #[cfg(not(target_os = "linux"))] + extern { + fn strerror_r(errnum: c_int, buf: *mut c_char, + buflen: libc::size_t) -> c_int; } let mut buf = [0 as c_char; TMPBUF_SZ]; @@ -113,15 +94,6 @@ pub fn error_string(errno: i32) -> String { } } -pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> { - let mut fds = [0; 2]; - if libc::pipe(fds.as_mut_ptr()) == 0 { - Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true))) - } else { - Err(super::last_error()) - } -} - pub fn getcwd() -> IoResult<Path> { let mut buf = [0 as c_char; BUF_BYTES]; unsafe { @@ -133,43 +105,68 @@ pub fn getcwd() -> IoResult<Path> { } } -pub unsafe fn get_env_pairs() -> Vec<Vec<u8>> { - extern { - fn rust_env_pairs() -> *const *const c_char; - } - let mut environ = rust_env_pairs(); - if environ as uint == 0 { - panic!("os::env() failure getting env string from OS: {}", - os::last_os_error()); +pub fn chdir(p: &Path) -> IoResult<()> { + let p = CString::from_slice(p.as_vec()); + unsafe { + match libc::chdir(p.as_ptr()) == (0 as c_int) { + true => Ok(()), + false => Err(IoError::last_error()), + } } - let mut result = Vec::new(); - while *environ != ptr::null() { - let env_pair = ffi::c_str_to_bytes(&*environ).to_vec(); - result.push(env_pair); - environ = environ.offset(1); +} + +pub struct SplitPaths<'a> { + iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, + fn(&'a [u8]) -> Path>, +} + +pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> { + fn is_colon(b: &u8) -> bool { *b == b':' } + let unparsed = unparsed.as_byte_slice(); + SplitPaths { + iter: unparsed.split(is_colon as fn(&u8) -> bool) + .map(Path::new as fn(&'a [u8]) -> Path) } - result } -pub fn split_paths(unparsed: &[u8]) -> Vec<Path> { - unparsed.split(|b| *b == b':').map(Path::new).collect() +impl<'a> Iterator for SplitPaths<'a> { + type Item = Path; + fn next(&mut self) -> Option<Path> { self.iter.next() } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } -pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> { +#[derive(Debug)] +pub struct JoinPathsError; + +pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> + where I: Iterator<Item=T>, T: AsOsStr +{ let mut joined = Vec::new(); let sep = b':'; - for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() { + for (i, path) in paths.enumerate() { + let path = path.as_os_str().as_byte_slice(); if i > 0 { joined.push(sep) } - if path.contains(&sep) { return Err("path segment contains separator `:`") } + if path.contains(&sep) { + return Err(JoinPathsError) + } joined.push_all(path); } + Ok(OsStringExt::from_vec(joined)) +} + +impl fmt::Display for JoinPathsError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "path segment contains separator `:`".fmt(f) + } +} - Ok(joined) +impl StdError for JoinPathsError { + fn description(&self) -> &str { "failed to join paths" } } #[cfg(target_os = "freebsd")] -pub fn load_self() -> Option<Vec<u8>> { +pub fn current_exe() -> IoResult<Path> { unsafe { use libc::funcs::bsd44::*; use libc::consts::os::extra::*; @@ -181,66 +178,305 @@ pub fn load_self() -> Option<Vec<u8>> { let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint, ptr::null_mut(), &mut sz, ptr::null_mut(), 0u as libc::size_t); - if err != 0 { return None; } - if sz == 0 { return None; } + if err != 0 { return Err(IoError::last_error()); } + if sz == 0 { return Err(IoError::last_error()); } let mut v: Vec<u8> = Vec::with_capacity(sz as uint); let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint, v.as_mut_ptr() as *mut libc::c_void, &mut sz, ptr::null_mut(), 0u as libc::size_t); - if err != 0 { return None; } - if sz == 0 { return None; } + if err != 0 { return Err(IoError::last_error()); } + if sz == 0 { return Err(IoError::last_error()); } v.set_len(sz as uint - 1); // chop off trailing NUL - Some(v) + Ok(Path::new(v)) } } #[cfg(target_os = "dragonfly")] +pub fn current_exe() -> IoResult<Path> { + fs::readlink(&Path::new("/proc/curproc/file")) +} + +#[cfg(target_os = "openbsd")] pub fn load_self() -> Option<Vec<u8>> { - use old_io; + use sync::{StaticMutex, MUTEX_INIT}; - match old_io::fs::readlink(&Path::new("/proc/curproc/file")) { - Ok(path) => Some(path.into_vec()), - Err(..) => None + static LOCK: StaticMutex = MUTEX_INIT; + + extern { + fn rust_load_self() -> *const c_char; } -} -#[cfg(any(target_os = "linux", target_os = "android"))] -pub fn load_self() -> Option<Vec<u8>> { - use old_io; + let _guard = LOCK.lock(); - match old_io::fs::readlink(&Path::new("/proc/self/exe")) { - Ok(path) => Some(path.into_vec()), - Err(..) => None + unsafe { + let v = rust_load_self(); + if v.is_null() { + None + } else { + Some(ffi::c_str_to_bytes(&v).to_vec()) + } } } +#[cfg(any(target_os = "linux", target_os = "android"))] +pub fn current_exe() -> IoResult<Path> { + fs::readlink(&Path::new("/proc/self/exe")) +} + #[cfg(any(target_os = "macos", target_os = "ios"))] -pub fn load_self() -> Option<Vec<u8>> { +pub fn current_exe() -> IoResult<Path> { unsafe { use libc::funcs::extra::_NSGetExecutablePath; let mut sz: u32 = 0; _NSGetExecutablePath(ptr::null_mut(), &mut sz); - if sz == 0 { return None; } + if sz == 0 { return Err(IoError::last_error()); } let mut v: Vec<u8> = Vec::with_capacity(sz as uint); let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz); - if err != 0 { return None; } + if err != 0 { return Err(IoError::last_error()); } v.set_len(sz as uint - 1); // chop off trailing NUL - Some(v) + Ok(Path::new(v)) } } -pub fn chdir(p: &Path) -> IoResult<()> { - let p = CString::from_slice(p.as_vec()); +pub struct Args { + iter: vec::IntoIter<OsString>, + _dont_send_or_sync_me: *mut (), +} + +impl Iterator for Args { + type Item = OsString; + fn next(&mut self) -> Option<OsString> { self.iter.next() } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } +} + +/// Returns the command line arguments +/// +/// Returns a list of the command line arguments. +#[cfg(target_os = "macos")] +pub fn args() -> Args { + extern { + // These functions are in crt_externs.h. + fn _NSGetArgc() -> *mut c_int; + fn _NSGetArgv() -> *mut *mut *mut c_char; + } + + let vec = unsafe { + let (argc, argv) = (*_NSGetArgc() as isize, + *_NSGetArgv() as *const *const c_char); + range(0, argc as isize).map(|i| { + let bytes = ffi::c_str_to_bytes(&*argv.offset(i)).to_vec(); + OsStringExt::from_vec(bytes) + }).collect::<Vec<_>>() + }; + Args { + iter: vec.into_iter(), + _dont_send_or_sync_me: 0 as *mut (), + } +} + +// As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs +// and use underscores in their names - they're most probably +// are considered private and therefore should be avoided +// Here is another way to get arguments using Objective C +// runtime +// +// In general it looks like: +// res = Vec::new() +// let args = [[NSProcessInfo processInfo] arguments] +// for i in range(0, [args count]) +// res.push([args objectAtIndex:i]) +// res +#[cfg(target_os = "ios")] +pub fn args() -> Args { + use iter::range; + use mem; + + #[link(name = "objc")] + extern { + fn sel_registerName(name: *const libc::c_uchar) -> Sel; + fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId; + fn objc_getClass(class_name: *const libc::c_uchar) -> NsId; + } + + #[link(name = "Foundation", kind = "framework")] + extern {} + + type Sel = *const libc::c_void; + type NsId = *const libc::c_void; + + let mut res = Vec::new(); + unsafe { - match libc::chdir(p.as_ptr()) == (0 as c_int) { - true => Ok(()), - false => Err(IoError::last_error()), + let processInfoSel = sel_registerName("processInfo\0".as_ptr()); + let argumentsSel = sel_registerName("arguments\0".as_ptr()); + let utf8Sel = sel_registerName("UTF8String\0".as_ptr()); + let countSel = sel_registerName("count\0".as_ptr()); + let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr()); + + let klass = objc_getClass("NSProcessInfo\0".as_ptr()); + let info = objc_msgSend(klass, processInfoSel); + let args = objc_msgSend(info, argumentsSel); + + let cnt: int = mem::transmute(objc_msgSend(args, countSel)); + for i in range(0, cnt) { + let tmp = objc_msgSend(args, objectAtSel, i); + let utf_c_str: *const libc::c_char = + mem::transmute(objc_msgSend(tmp, utf8Sel)); + let bytes = ffi::c_str_to_bytes(&utf_c_str).to_vec(); + res.push(OsString::from_vec(bytes)) + } + } + + Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ } +} + +#[cfg(any(target_os = "linux", + target_os = "android", + target_os = "freebsd", + target_os = "dragonfly"))] +pub fn args() -> Args { + use rt; + let bytes = rt::args::clone().unwrap_or(Vec::new()); + let v: Vec<OsString> = bytes.into_iter().map(|v| { + OsStringExt::from_vec(v) + }).collect(); + Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ } +} + +pub struct Env { + iter: vec::IntoIter<(OsString, OsString)>, + _dont_send_or_sync_me: *mut (), +} + +impl Iterator for Env { + type Item = (OsString, OsString); + fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } +} + +#[cfg(target_os = "macos")] +pub unsafe fn environ() -> *mut *const *const c_char { + extern { fn _NSGetEnviron() -> *mut *const *const c_char; } + _NSGetEnviron() +} + +#[cfg(not(target_os = "macos"))] +pub unsafe fn environ() -> *mut *const *const c_char { + extern { static mut environ: *const *const c_char; } + &mut environ +} + +/// Returns a vector of (variable, value) byte-vector pairs for all the +/// environment variables of the current process. +pub fn env() -> Env { + return unsafe { + let mut environ = *environ(); + if environ as usize == 0 { + panic!("os::env() failure getting env string from OS: {}", + IoError::last_error()); + } + let mut result = Vec::new(); + while *environ != ptr::null() { + result.push(parse(ffi::c_str_to_bytes(&*environ))); + environ = environ.offset(1); + } + Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ } + }; + + fn parse(input: &[u8]) -> (OsString, OsString) { + let mut it = input.splitn(1, |b| *b == b'='); + let key = it.next().unwrap().to_vec(); + let default: &[u8] = &[]; + let val = it.next().unwrap_or(default).to_vec(); + (OsStringExt::from_vec(key), OsStringExt::from_vec(val)) + } +} + +pub fn getenv(k: &OsStr) -> Option<OsString> { + unsafe { + let s = CString::from_slice(k.as_byte_slice()); + let s = libc::getenv(s.as_ptr()) as *const _; + if s.is_null() { + None + } else { + Some(OsStringExt::from_vec(ffi::c_str_to_bytes(&s).to_vec())) + } + } +} + +pub fn setenv(k: &OsStr, v: &OsStr) { + unsafe { + let k = CString::from_slice(k.as_byte_slice()); + let v = CString::from_slice(v.as_byte_slice()); + if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1) != 0 { + panic!("failed setenv: {}", IoError::last_error()); + } + } +} + +pub fn unsetenv(n: &OsStr) { + unsafe { + let nbuf = CString::from_slice(n.as_byte_slice()); + if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr()) != 0 { + panic!("failed unsetenv: {}", IoError::last_error()); } } } -pub fn page_size() -> uint { +pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> { + let mut fds = [0; 2]; + if libc::pipe(fds.as_mut_ptr()) == 0 { + Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true))) + } else { + Err(IoError::last_error()) + } +} + +pub fn page_size() -> usize { unsafe { - libc::sysconf(libc::_SC_PAGESIZE) as uint + libc::sysconf(libc::_SC_PAGESIZE) as usize + } +} + +pub fn temp_dir() -> Path { + getenv("TMPDIR".as_os_str()).map(|p| Path::new(p.into_vec())).unwrap_or_else(|| { + if cfg!(target_os = "android") { + Path::new("/data/local/tmp") + } else { + Path::new("/tmp") + } + }) +} + +pub fn home_dir() -> Option<Path> { + return getenv("HOME".as_os_str()).or_else(|| unsafe { + fallback() + }).map(|os| { + Path::new(os.into_vec()) + }); + + #[cfg(target_os = "android")] + unsafe fn fallback() -> Option<OsString> { None } + #[cfg(not(target_os = "android"))] + unsafe fn fallback() -> Option<OsString> { + let mut amt = match libc::sysconf(c::_SC_GETPW_R_SIZE_MAX) { + n if n < 0 => 512 as usize, + n => n as usize, + }; + let me = libc::getuid(); + loop { + let mut buf = Vec::with_capacity(amt); + let mut passwd: c::passwd = mem::zeroed(); + let mut result = 0 as *mut _; + match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(), + buf.capacity() as libc::size_t, + &mut result) { + 0 if !result.is_null() => {} + _ => return None + } + let ptr = passwd.pw_dir as *const _; + let bytes = ffi::c_str_to_bytes(&ptr).to_vec(); + return Some(OsStringExt::from_vec(bytes)) + } } } diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index b004a47f8a3..7e117b10a34 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -72,18 +72,6 @@ impl Process { } } - #[cfg(target_os = "macos")] - unsafe fn set_environ(envp: *const c_void) { - extern { fn _NSGetEnviron() -> *mut *const c_void; } - - *_NSGetEnviron() = envp; - } - #[cfg(not(target_os = "macos"))] - unsafe fn set_environ(envp: *const c_void) { - extern { static mut environ: *const c_void; } - environ = envp; - } - unsafe fn set_cloexec(fd: c_int) { let ret = c::ioctl(fd, c::FIOCLEX); assert_eq!(ret, 0); @@ -269,7 +257,7 @@ impl Process { fail(&mut output); } if !envp.is_null() { - set_environ(envp); + *sys::os::environ() = envp as *const _; } let _ = execvp(*argv, argv as *mut _); fail(&mut output); @@ -570,7 +558,7 @@ fn with_envp<K,V,T,F>(env: Option<&HashMap<K, V>>, Some(env) => { let mut tmps = Vec::with_capacity(env.len()); - for pair in env.iter() { + for pair in env { let mut kv = Vec::new(); kv.push_all(pair.0.container_as_bytes()); kv.push('=' as u8); @@ -604,7 +592,8 @@ fn translate_status(status: c_int) -> ProcessExit { #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] mod imp { pub fn WIFEXITED(status: i32) -> bool { (status & 0x7f) == 0 } pub fn WEXITSTATUS(status: i32) -> i32 { status >> 8 } diff --git a/src/libstd/sys/unix/stack_overflow.rs b/src/libstd/sys/unix/stack_overflow.rs index a526f3393f2..3512fa36eb3 100644 --- a/src/libstd/sys/unix/stack_overflow.rs +++ b/src/libstd/sys/unix/stack_overflow.rs @@ -32,7 +32,9 @@ impl Drop for Handler { } } -#[cfg(any(target_os = "linux", target_os = "macos"))] +#[cfg(any(target_os = "linux", + target_os = "macos", + target_os = "openbsd"))] mod imp { use core::prelude::*; use sys_common::stack; @@ -203,7 +205,7 @@ mod imp { } - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", target_os = "openbsd"))] mod signal { use libc; use super::sighandler_t; @@ -212,7 +214,10 @@ mod imp { pub const SA_SIGINFO: libc::c_int = 0x0040; pub const SIGBUS: libc::c_int = 10; + #[cfg(target_os = "macos")] pub const SIGSTKSZ: libc::size_t = 131072; + #[cfg(target_os = "openbsd")] + pub const SIGSTKSZ: libc::size_t = 40960; pub const SIG_DFL: sighandler_t = 0 as sighandler_t; @@ -220,6 +225,7 @@ mod imp { // This structure has more fields, but we're not all that interested in // them. + #[cfg(target_os = "macos")] #[repr(C)] pub struct siginfo { pub si_signo: libc::c_int, @@ -231,6 +237,16 @@ mod imp { pub si_addr: *mut libc::c_void } + #[cfg(target_os = "openbsd")] + #[repr(C)] + pub struct siginfo { + pub si_signo: libc::c_int, + pub si_code: libc::c_int, + pub si_errno: libc::c_int, + // union + pub si_addr: *mut libc::c_void, + } + #[repr(C)] pub struct sigaltstack { pub ss_sp: *mut libc::c_void, @@ -260,7 +276,8 @@ mod imp { } #[cfg(not(any(target_os = "linux", - target_os = "macos")))] + target_os = "macos", + target_os = "openbsd")))] mod imp { use libc; diff --git a/src/libstd/sys/unix/sync.rs b/src/libstd/sys/unix/sync.rs index c1e3fc88794..bc93513af63 100644 --- a/src/libstd/sys/unix/sync.rs +++ b/src/libstd/sys/unix/sync.rs @@ -44,7 +44,9 @@ extern { pub fn pthread_rwlock_unlock(lock: *mut pthread_rwlock_t) -> libc::c_int; } -#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] +#[cfg(any(target_os = "freebsd", + target_os = "dragonfly", + target_os = "openbsd"))] mod os { use libc; diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs index 26a450b8599..6f030ee91fe 100644 --- a/src/libstd/sys/unix/thread.rs +++ b/src/libstd/sys/unix/thread.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -31,7 +31,9 @@ pub extern fn thread_start(main: *mut libc::c_void) -> rust_thread_return { return start_thread(main); } -#[cfg(all(not(target_os = "linux"), not(target_os = "macos")))] +#[cfg(all(not(target_os = "linux"), + not(target_os = "macos"), + not(target_os = "openbsd")))] pub mod guard { pub unsafe fn current() -> uint { 0 @@ -45,10 +47,15 @@ pub mod guard { } } -#[cfg(any(target_os = "linux", target_os = "macos"))] + +#[cfg(any(target_os = "linux", + target_os = "macos", + target_os = "openbsd"))] pub mod guard { use super::*; - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(any(target_os = "linux", + target_os = "android", + target_os = "openbsd"))] use mem; #[cfg(any(target_os = "linux", target_os = "android"))] use ptr; @@ -64,7 +71,7 @@ pub mod guard { static mut PAGE_SIZE: uint = 0; static mut GUARD_PAGE: uint = 0; - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", target_os = "openbsd"))] unsafe fn get_stack_start() -> *mut libc::c_void { current() as *mut libc::c_void } @@ -141,6 +148,23 @@ pub mod guard { pthread_get_stacksize_np(pthread_self())) as uint } + #[cfg(target_os = "openbsd")] + pub unsafe fn current() -> uint { + let mut current_stack: stack_t = mem::zeroed(); + if pthread_stackseg_np(pthread_self(), &mut current_stack) != 0 { + panic!("failed to get current stack: pthread_stackseg_np") + } + + if pthread_main_np() == 1 { + // main thread + current_stack.ss_sp as uint - current_stack.ss_size as uint + 3 * PAGE_SIZE as uint + + } else { + // new thread + current_stack.ss_sp as uint - current_stack.ss_size as uint + } + } + #[cfg(any(target_os = "linux", target_os = "android"))] pub unsafe fn current() -> uint { let mut attr: libc::pthread_attr_t = mem::zeroed(); @@ -224,7 +248,9 @@ pub unsafe fn set_name(name: &str) { } } -#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] +#[cfg(any(target_os = "freebsd", + target_os = "dragonfly", + target_os = "openbsd"))] pub unsafe fn set_name(name: &str) { // pthread_set_name_np() since almost forever on all BSDs let cname = CString::from_slice(name.as_bytes()); @@ -290,7 +316,9 @@ extern { stacksize: *mut libc::size_t) -> libc::c_int; } -#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] +#[cfg(any(target_os = "freebsd", + target_os = "dragonfly", + target_os = "openbsd"))] extern { pub fn pthread_self() -> libc::pthread_t; fn pthread_set_name_np(tid: libc::pthread_t, name: *const libc::c_char); @@ -304,6 +332,21 @@ extern { fn pthread_setname_np(name: *const libc::c_char) -> libc::c_int; } +#[cfg(target_os = "openbsd")] +extern { + pub fn pthread_stackseg_np(thread: libc::pthread_t, + sinfo: *mut stack_t) -> libc::c_uint; + pub fn pthread_main_np() -> libc::c_uint; +} + +#[cfg(target_os = "openbsd")] +#[repr(C)] +pub struct stack_t { + pub ss_sp: *mut libc::c_void, + pub ss_size: libc::size_t, + pub ss_flags: libc::c_int, +} + extern { fn pthread_create(native: *mut libc::pthread_t, attr: *const libc::pthread_attr_t, diff --git a/src/libstd/sys/unix/thread_local.rs b/src/libstd/sys/unix/thread_local.rs index ea1e9c261fe..62d9a33c83d 100644 --- a/src/libstd/sys/unix/thread_local.rs +++ b/src/libstd/sys/unix/thread_local.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -42,13 +42,15 @@ pub unsafe fn destroy(key: Key) { type pthread_key_t = ::libc::c_ulong; #[cfg(any(target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] type pthread_key_t = ::libc::c_int; #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "freebsd", - target_os = "dragonfly")))] + target_os = "dragonfly", + target_os = "openbsd")))] type pthread_key_t = ::libc::c_uint; extern { diff --git a/src/libstd/sys/unix/time.rs b/src/libstd/sys/unix/time.rs index cc1e23fbca9..bddf7b075df 100644 --- a/src/libstd/sys/unix/time.rs +++ b/src/libstd/sys/unix/time.rs @@ -80,7 +80,8 @@ mod inner { } // Apparently android provides this in some other library? - #[cfg(not(target_os = "android"))] + // OpenBSD provide it via libc + #[cfg(not(any(target_os = "android", target_os = "openbsd")))] #[link(name = "rt")] extern {} diff --git a/src/libstd/sys/unix/tty.rs b/src/libstd/sys/unix/tty.rs index d414f70152d..3a79047445c 100644 --- a/src/libstd/sys/unix/tty.rs +++ b/src/libstd/sys/unix/tty.rs @@ -21,7 +21,8 @@ pub struct TTY { } #[cfg(any(target_os = "macos", - target_os = "freebsd"))] + target_os = "freebsd", + target_os = "openbsd"))] const TIOCGWINSZ: c_ulong = 0x40087468; #[cfg(any(target_os = "linux", target_os = "android"))] @@ -53,7 +54,8 @@ impl TTY { #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos", - target_os = "freebsd"))] + target_os = "freebsd", + target_os = "openbsd"))] pub fn get_winsize(&mut self) -> IoResult<(int, int)> { unsafe { #[repr(C)] diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index 1be1a412ffa..66712b9e3a1 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -7,29 +7,31 @@ // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. -/// As always, windows has something very different than unix, we mainly want -/// to avoid having to depend too much on libunwind for windows. -/// -/// If you google around, you'll find a fair bit of references to built-in -/// functions to get backtraces on windows. It turns out that most of these are -/// in an external library called dbghelp. I was unable to find this library -/// via `-ldbghelp`, but it is apparently normal to do the `dlopen` equivalent -/// of it. -/// -/// You'll also find that there's a function called CaptureStackBackTrace -/// mentioned frequently (which is also easy to use), but sadly I didn't have a -/// copy of that function in my mingw install (maybe it was broken?). Instead, -/// this takes the route of using StackWalk64 in order to walk the stack. + +//! As always, windows has something very different than unix, we mainly want +//! to avoid having to depend too much on libunwind for windows. +//! +//! If you google around, you'll find a fair bit of references to built-in +//! functions to get backtraces on windows. It turns out that most of these are +//! in an external library called dbghelp. I was unable to find this library +//! via `-ldbghelp`, but it is apparently normal to do the `dlopen` equivalent +//! of it. +//! +//! You'll also find that there's a function called CaptureStackBackTrace +//! mentioned frequently (which is also easy to use), but sadly I didn't have a +//! copy of that function in my mingw install (maybe it was broken?). Instead, +//! this takes the route of using StackWalk64 in order to walk the stack. + +#![allow(dead_code)] use dynamic_lib::DynamicLibrary; use ffi; -use core::ops::Index; use intrinsics; use old_io::{IoResult, Writer}; use libc; use mem; use ops::Drop; -use option::Option::{Some, None}; +use option::Option::{Some}; use path::Path; use ptr; use result::Result::{Ok, Err}; @@ -296,7 +298,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> { // According to windows documentation, all dbghelp functions are // single-threaded. static LOCK: StaticMutex = MUTEX_INIT; - let _g = unsafe { LOCK.lock() }; + let _g = LOCK.lock(); // Open up dbghelp.dll, we don't link to it explicitly because it can't // always be found. Additionally, it's nice having fewer dependencies. diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index da3b7ee2f2f..0355565cf00 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -10,17 +10,21 @@ //! C definitions used by libnative that don't belong in liblibc -#![allow(overflowing_literals)] -#![allow(dead_code)] -#![allow(non_camel_case_types)] +#![allow(bad_style, dead_code, overflowing_literals)] use libc; -use prelude::v1::*; -pub const WSADESCRIPTION_LEN: uint = 256; -pub const WSASYS_STATUS_LEN: uint = 128; +pub use self::GET_FILEEX_INFO_LEVELS::*; +pub use self::FILE_INFO_BY_HANDLE_CLASS::*; +pub use libc::consts::os::extra::{ + FILE_ATTRIBUTE_READONLY, + FILE_ATTRIBUTE_DIRECTORY, +}; + +pub const WSADESCRIPTION_LEN: usize = 256; +pub const WSASYS_STATUS_LEN: usize = 128; pub const FIONBIO: libc::c_long = 0x8004667e; -pub const FD_SETSIZE: uint = 64; +pub const FD_SETSIZE: usize = 64; pub const MSG_DONTWAIT: libc::c_int = 0; pub const ERROR_ILLEGAL_CHARACTER: libc::c_int = 582; pub const ENABLE_ECHO_INPUT: libc::DWORD = 0x4; @@ -32,12 +36,15 @@ pub const ENABLE_QUICK_EDIT_MODE: libc::DWORD = 0x40; pub const WSA_INVALID_EVENT: WSAEVENT = 0 as WSAEVENT; pub const FD_ACCEPT: libc::c_long = 0x08; -pub const FD_MAX_EVENTS: uint = 10; +pub const FD_MAX_EVENTS: usize = 10; pub const WSA_INFINITE: libc::DWORD = libc::INFINITE; pub const WSA_WAIT_TIMEOUT: libc::DWORD = libc::consts::os::extra::WAIT_TIMEOUT; pub const WSA_WAIT_EVENT_0: libc::DWORD = libc::consts::os::extra::WAIT_OBJECT_0; pub const WSA_WAIT_FAILED: libc::DWORD = libc::consts::os::extra::WAIT_FAILED; +pub const ERROR_NO_MORE_FILES: libc::DWORD = 18; +pub const TOKEN_READ: libc::DWORD = 0x20008; + #[repr(C)] #[cfg(target_arch = "x86")] pub struct WSADATA { @@ -80,7 +87,7 @@ pub struct fd_set { } pub fn fd_set(set: &mut fd_set, s: libc::SOCKET) { - set.fd_array[set.fd_count as uint] = s; + set.fd_array[set.fd_count as usize] = s; set.fd_count += 1; } @@ -110,6 +117,69 @@ pub struct CONSOLE_SCREEN_BUFFER_INFO { } pub type PCONSOLE_SCREEN_BUFFER_INFO = *mut CONSOLE_SCREEN_BUFFER_INFO; +#[repr(C)] +pub struct WIN32_FILE_ATTRIBUTE_DATA { + pub dwFileAttributes: libc::DWORD, + pub ftCreationTime: libc::FILETIME, + pub ftLastAccessTime: libc::FILETIME, + pub ftLastWriteTime: libc::FILETIME, + pub nFileSizeHigh: libc::DWORD, + pub nFileSizeLow: libc::DWORD, +} + +#[repr(C)] +pub struct BY_HANDLE_FILE_INFORMATION { + pub dwFileAttributes: libc::DWORD, + pub ftCreationTime: libc::FILETIME, + pub ftLastAccessTime: libc::FILETIME, + pub ftLastWriteTime: libc::FILETIME, + pub dwVolumeSerialNumber: libc::DWORD, + pub nFileSizeHigh: libc::DWORD, + pub nFileSizeLow: libc::DWORD, + pub nNumberOfLinks: libc::DWORD, + pub nFileIndexHigh: libc::DWORD, + pub nFileIndexLow: libc::DWORD, +} + +pub type LPBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; + +#[repr(C)] +pub enum GET_FILEEX_INFO_LEVELS { + GetFileExInfoStandard, + GetFileExMaxInfoLevel +} + +#[repr(C)] +pub enum FILE_INFO_BY_HANDLE_CLASS { + FileBasicInfo = 0, + FileStandardInfo = 1, + FileNameInfo = 2, + FileRenameInfo = 3, + FileDispositionInfo = 4, + FileAllocationInfo = 5, + FileEndOfFileInfo = 6, + FileStreamInfo = 7, + FileCompressionInfo = 8, + FileAttributeTagInfo = 9, + FileIdBothDirectoryInfo = 10, // 0xA + FileIdBothDirectoryRestartInfo = 11, // 0xB + FileIoPriorityHintInfo = 12, // 0xC + FileRemoteProtocolInfo = 13, // 0xD + FileFullDirectoryInfo = 14, // 0xE + FileFullDirectoryRestartInfo = 15, // 0xF + FileStorageInfo = 16, // 0x10 + FileAlignmentInfo = 17, // 0x11 + FileIdInfo = 18, // 0x12 + FileIdExtdDirectoryInfo = 19, // 0x13 + FileIdExtdDirectoryRestartInfo = 20, // 0x14 + MaximumFileInfoByHandlesClass +} + +#[repr(C)] +pub struct FILE_END_OF_FILE_INFO { + pub EndOfFile: libc::LARGE_INTEGER, +} + #[link(name = "ws2_32")] extern "system" { pub fn WSAStartup(wVersionRequested: libc::WORD, @@ -156,31 +226,29 @@ extern "system" { } pub mod compat { - use intrinsics::{atomic_store_relaxed, transmute}; - use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; use prelude::v1::*; + use ffi::CString; + use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; + use sync::atomic::{AtomicUsize, Ordering}; extern "system" { fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; fn GetProcAddress(hModule: HMODULE, lpProcName: LPCSTR) -> LPVOID; } - // store_func() is idempotent, so using relaxed ordering for the atomics - // should be enough. This way, calling a function in this compatibility - // layer (after it's loaded) shouldn't be any slower than a regular DLL - // call. - unsafe fn store_func(ptr: *mut uint, module: &str, symbol: &str, fallback: uint) { + fn store_func(ptr: &AtomicUsize, module: &str, symbol: &str, + fallback: usize) -> usize { let mut module: Vec<u16> = module.utf16_units().collect(); module.push(0); let symbol = CString::from_slice(symbol.as_bytes()); - let handle = GetModuleHandleW(module.as_ptr()); - let func: uint = transmute(GetProcAddress(handle, symbol.as_ptr())); - atomic_store_relaxed(ptr, if func == 0 { - fallback - } else { - func - }) + let func = unsafe { + let handle = GetModuleHandleW(module.as_ptr()); + GetProcAddress(handle, symbol.as_ptr()) as usize + }; + let value = if func == 0 {fallback} else {func}; + ptr.store(value, Ordering::SeqCst); + value } /// Macro for creating a compatibility fallback for a Windows function @@ -192,29 +260,36 @@ pub mod compat { /// }) /// ``` /// - /// Note that arguments unused by the fallback implementation should not be called `_` as - /// they are used to be passed to the real function if available. + /// Note that arguments unused by the fallback implementation should not be + /// called `_` as they are used to be passed to the real function if + /// available. macro_rules! compat_fn { ($module:ident::$symbol:ident($($argname:ident: $argtype:ty),*) -> $rettype:ty { $fallback:expr }) => ( #[inline(always)] pub unsafe fn $symbol($($argname: $argtype),*) -> $rettype { - static mut ptr: extern "system" fn($($argname: $argtype),*) -> $rettype = thunk; - - extern "system" fn thunk($($argname: $argtype),*) -> $rettype { - unsafe { - ::sys::c::compat::store_func(&mut ptr as *mut _ as *mut uint, - stringify!($module), - stringify!($symbol), - fallback as uint); - ::intrinsics::atomic_load_relaxed(&ptr)($($argname),*) - } + use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; + use mem; + + static PTR: AtomicUsize = ATOMIC_USIZE_INIT; + + fn load() -> usize { + ::sys::c::compat::store_func(&PTR, + stringify!($module), + stringify!($symbol), + fallback as usize) } extern "system" fn fallback($($argname: $argtype),*) -> $rettype { $fallback } - ::intrinsics::atomic_load_relaxed(&ptr)($($argname),*) + let addr = match PTR.load(Ordering::SeqCst) { + 0 => load(), + n => n, + }; + let f: extern "system" fn($($argtype),*) -> $rettype = + mem::transmute(addr); + f($($argname),*) } ) } @@ -229,10 +304,7 @@ pub mod compat { use libc::c_uint; use libc::types::os::arch::extra::{DWORD, LPCWSTR, BOOLEAN, HANDLE}; use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED; - - extern "system" { - fn SetLastError(dwErrCode: DWORD); - } + use sys::c::SetLastError; compat_fn! { kernel32::CreateSymbolicLinkW(_lpSymlinkFileName: LPCWSTR, @@ -282,4 +354,42 @@ extern "system" { hConsoleOutput: libc::HANDLE, lpConsoleScreenBufferInfo: PCONSOLE_SCREEN_BUFFER_INFO, ) -> libc::BOOL; + + pub fn GetFileAttributesExW(lpFileName: libc::LPCWSTR, + fInfoLevelId: GET_FILEEX_INFO_LEVELS, + lpFileInformation: libc::LPVOID) -> libc::BOOL; + pub fn RemoveDirectoryW(lpPathName: libc::LPCWSTR) -> libc::BOOL; + pub fn SetFileAttributesW(lpFileName: libc::LPCWSTR, + dwFileAttributes: libc::DWORD) -> libc::BOOL; + pub fn GetFileAttributesW(lpFileName: libc::LPCWSTR) -> libc::DWORD; + pub fn GetFileInformationByHandle(hFile: libc::HANDLE, + lpFileInformation: LPBY_HANDLE_FILE_INFORMATION) + -> libc::BOOL; + + pub fn SetLastError(dwErrCode: libc::DWORD); + pub fn GetCommandLineW() -> *mut libc::LPCWSTR; + pub fn LocalFree(ptr: *mut libc::c_void); + pub fn CommandLineToArgvW(lpCmdLine: *mut libc::LPCWSTR, + pNumArgs: *mut libc::c_int) -> *mut *mut u16; + pub fn SetFileTime(hFile: libc::HANDLE, + lpCreationTime: *const libc::FILETIME, + lpLastAccessTime: *const libc::FILETIME, + lpLastWriteTime: *const libc::FILETIME) -> libc::BOOL; + pub fn SetFileInformationByHandle(hFile: libc::HANDLE, + FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, + lpFileInformation: libc::LPVOID, + dwBufferSize: libc::DWORD) -> libc::BOOL; + pub fn GetTempPathW(nBufferLength: libc::DWORD, + lpBuffer: libc::LPCWSTR) -> libc::DWORD; + pub fn OpenProcessToken(ProcessHandle: libc::HANDLE, + DesiredAccess: libc::DWORD, + TokenHandle: *mut libc::HANDLE) -> libc::BOOL; + pub fn GetCurrentProcess() -> libc::HANDLE; +} + +#[link(name = "userenv")] +extern "system" { + pub fn GetUserProfileDirectoryW(hToken: libc::HANDLE, + lpProfileDir: libc::LPCWSTR, + lpcchSize: *mut libc::DWORD) -> libc::BOOL; } diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index 80cdf9782f2..304d7e01532 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -10,20 +10,15 @@ //! Blocking Windows-based file I/O -use alloc::arc::Arc; use libc::{self, c_int}; use mem; -use sys::os::fill_utf16_buf_and_decode; -use path; use ptr; -use str; use old_io; use prelude::v1::*; use sys; -use sys::os; -use sys_common::{keep_going, eof, mkerr_libc}; +use sys_common::{mkerr_libc}; use old_io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; use old_io::{IoResult, IoError, FileStat, SeekStyle}; @@ -262,7 +257,7 @@ pub fn readdir(p: &Path) -> IoResult<Vec<Path>> { let mut more_files = 1 as libc::BOOL; while more_files != 0 { { - let filename = os::truncate_utf16_at_nul(&wfd.cFileName); + let filename = super::truncate_utf16_at_nul(&wfd.cFileName); match String::from_utf16(filename) { Ok(filename) => paths.push(Path::new(filename)), Err(..) => { @@ -368,19 +363,12 @@ pub fn readlink(p: &Path) -> IoResult<Path> { } // Specify (sz - 1) because the documentation states that it's the size // without the null pointer - let ret = fill_utf16_buf_and_decode(|buf, sz| unsafe { + let ret = super::fill_utf16_buf(|buf, sz| unsafe { GetFinalPathNameByHandleW(handle, buf as *const u16, sz - 1, libc::VOLUME_NAME_DOS) - }); - let ret = match ret { - Some(ref s) if s.starts_with(r"\\?\") => { // " - Ok(Path::new(&s[4..])) - } - Some(s) => Ok(Path::new(s)), - None => Err(super::last_error()), - }; + }, super::os2path); assert!(unsafe { libc::CloseHandle(handle) } != 0); return ret; } diff --git a/src/libstd/sys/windows/handle.rs b/src/libstd/sys/windows/handle.rs new file mode 100644 index 00000000000..6737eeef125 --- /dev/null +++ b/src/libstd/sys/windows/handle.rs @@ -0,0 +1,31 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use prelude::v1::*; + +use libc::{self, HANDLE}; + +pub struct Handle(HANDLE); + +unsafe impl Send for Handle {} +unsafe impl Sync for Handle {} + +impl Handle { + pub fn new(handle: HANDLE) -> Handle { + Handle(handle) + } +} + +impl Drop for Handle { + fn drop(&mut self) { + unsafe { let _ = libc::CloseHandle(self.0); } + } +} + diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index e8b65c9b64e..8dd467eba9e 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -11,18 +11,14 @@ #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] -#![allow(unused_imports)] -#![allow(dead_code)] -#![allow(unused_unsafe)] -#![allow(unused_mut)] - -extern crate libc; use prelude::v1::*; -use num; +use ffi::OsStr; +use libc; use mem; use old_io::{self, IoResult, IoError}; +use os::windows::OsStrExt; use sync::{Once, ONCE_INIT}; macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => ( @@ -38,9 +34,10 @@ macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => ( pub mod backtrace; pub mod c; -pub mod ext; pub mod condvar; +pub mod ext; pub mod fs; +pub mod handle; pub mod helper_signal; pub mod mutex; pub mod os; @@ -48,12 +45,12 @@ pub mod os_str; pub mod pipe; pub mod process; pub mod rwlock; -pub mod sync; pub mod stack_overflow; +pub mod sync; pub mod tcp; -pub mod time; pub mod thread; pub mod thread_local; +pub mod time; pub mod timer; pub mod tty; pub mod udp; @@ -158,7 +155,7 @@ pub fn ms_to_timeval(ms: u64) -> libc::timeval { pub fn wouldblock() -> bool { let err = os::errno(); - err == libc::WSAEWOULDBLOCK as uint + err == libc::WSAEWOULDBLOCK as i32 } pub fn set_nonblocking(fd: sock_t, nb: bool) -> IoResult<()> { @@ -191,17 +188,93 @@ pub fn unimpl() -> IoError { } } -pub fn to_utf16(s: Option<&str>) -> IoResult<Vec<u16>> { +fn to_utf16(s: Option<&str>) -> IoResult<Vec<u16>> { match s { - Some(s) => Ok({ - let mut s = s.utf16_units().collect::<Vec<u16>>(); - s.push(0); - s - }), + Some(s) => Ok(to_utf16_os(OsStr::from_str(s))), None => Err(IoError { kind: old_io::InvalidInput, desc: "valid unicode input required", - detail: None - }) + detail: None, + }), + } +} + +fn to_utf16_os(s: &OsStr) -> Vec<u16> { + let mut v: Vec<_> = s.encode_wide().collect(); + v.push(0); + v +} + +// Many Windows APIs follow a pattern of where we hand the a buffer and then +// they will report back to us how large the buffer should be or how many bytes +// currently reside in the buffer. This function is an abstraction over these +// functions by making them easier to call. +// +// The first callback, `f1`, is yielded a (pointer, len) pair which can be +// passed to a syscall. The `ptr` is valid for `len` items (u16 in this case). +// The closure is expected to return what the syscall returns which will be +// interpreted by this function to determine if the syscall needs to be invoked +// again (with more buffer space). +// +// Once the syscall has completed (errors bail out early) the second closure is +// yielded the data which has been read from the syscall. The return value +// from this closure is then the return value of the function. +fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T> + where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD, + F2: FnOnce(&[u16]) -> T +{ + // Start off with a stack buf but then spill over to the heap if we end up + // needing more space. + let mut stack_buf = [0u16; 512]; + let mut heap_buf = Vec::new(); + unsafe { + let mut n = stack_buf.len(); + loop { + let buf = if n <= stack_buf.len() { + &mut stack_buf[] + } else { + let extra = n - heap_buf.len(); + heap_buf.reserve(extra); + heap_buf.set_len(n); + &mut heap_buf[] + }; + + // This function is typically called on windows API functions which + // will return the correct length of the string, but these functions + // also return the `0` on error. In some cases, however, the + // returned "correct length" may actually be 0! + // + // To handle this case we call `SetLastError` to reset it to 0 and + // then check it again if we get the "0 error value". If the "last + // error" is still 0 then we interpret it as a 0 length buffer and + // not an actual error. + c::SetLastError(0); + let k = match f1(buf.as_mut_ptr(), n as libc::DWORD) { + 0 if libc::GetLastError() == 0 => 0, + 0 => return Err(IoError::last_error()), + n => n, + } as usize; + if k == n && libc::GetLastError() == + libc::ERROR_INSUFFICIENT_BUFFER as libc::DWORD { + n *= 2; + } else if k >= n { + n = k; + } else { + return Ok(f2(&buf[..k])) + } + } + } +} + +fn os2path(s: &[u16]) -> Path { + // FIXME: this should not be a panicking conversion (aka path reform) + Path::new(String::from_utf16(s).unwrap()) +} + +pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] { + match v.iter().position(|c| *c == 0) { + // don't include the 0 + Some(i) => &v[..i], + None => v } } diff --git a/src/libstd/sys/windows/mutex.rs b/src/libstd/sys/windows/mutex.rs index 828ad795ed3..75495efc7cb 100644 --- a/src/libstd/sys/windows/mutex.rs +++ b/src/libstd/sys/windows/mutex.rs @@ -38,8 +38,6 @@ pub unsafe fn raw(m: &Mutex) -> ffi::PSRWLOCK { impl Mutex { #[inline] - pub unsafe fn new() -> Mutex { MUTEX_INIT } - #[inline] pub unsafe fn lock(&self) { ffi::AcquireSRWLockExclusive(self.inner.get()) } diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index a82259ad5ec..c71e2d057c3 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -10,48 +10,32 @@ //! Implementation of `std::os` functionality for Windows -// FIXME: move various extern bindings from here into liblibc or -// something similar +#![allow(bad_style)] use prelude::v1::*; +use os::windows::*; +use error::Error as StdError; +use ffi::{OsString, OsStr, AsOsStr}; use fmt; -use old_io::{IoResult, IoError}; -use iter::repeat; -use libc::{c_int, c_void}; -use libc; -use os; -use path::BytesContainer; +use iter::Range; +use libc::types::os::arch::extra::LPWCH; +use libc::{self, c_int, c_void}; +use mem; +use old_io::{IoError, IoResult}; use ptr; use slice; +use sys::c; use sys::fs::FileDesc; +use sys::handle::Handle as RawHandle; -use os::TMPBUF_SZ; -use libc::types::os::arch::extra::DWORD; +use libc::funcs::extra::kernel32::{ + GetEnvironmentStringsW, + FreeEnvironmentStringsW +}; -const BUF_BYTES : uint = 2048u; - -/// Return a slice of `v` ending at (and not including) the first NUL -/// (0). -pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] { - match v.iter().position(|c| *c == 0) { - // don't include the 0 - Some(i) => &v[..i], - None => v - } -} - -pub fn errno() -> uint { - use libc::types::os::arch::extra::DWORD; - - #[link_name = "kernel32"] - extern "system" { - fn GetLastError() -> DWORD; - } - - unsafe { - GetLastError() as uint - } +pub fn errno() -> i32 { + unsafe { libc::GetLastError() as i32 } } /// Get a detailed string description for the given error number @@ -80,7 +64,7 @@ pub fn error_string(errnum: i32) -> String { // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) let langId = 0x0800 as DWORD; - let mut buf = [0 as WCHAR; TMPBUF_SZ]; + let mut buf = [0 as WCHAR; 2048]; unsafe { let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | @@ -94,200 +78,170 @@ pub fn error_string(errnum: i32) -> String { if res == 0 { // Sometimes FormatMessageW can fail e.g. system doesn't like langId, let fm_err = errno(); - return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err); + return format!("OS Error {} (FormatMessageW() returned error {})", + errnum, fm_err); } - let msg = String::from_utf16(truncate_utf16_at_nul(&buf)); + let b = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); + let msg = String::from_utf16(&buf[..b]); match msg { - Ok(msg) => format!("OS Error {}: {}", errnum, msg), + Ok(msg) => msg, Err(..) => format!("OS Error {} (FormatMessageW() returned \ invalid UTF-16)", errnum), } } } -pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> { - // Windows pipes work subtly differently than unix pipes, and their - // inheritance has to be handled in a different way that I do not - // fully understand. Here we explicitly make the pipe non-inheritable, - // which means to pass it to a subprocess they need to be duplicated - // first, as in std::run. - let mut fds = [0; 2]; - match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint, - (libc::O_BINARY | libc::O_NOINHERIT) as c_int) { - 0 => { - assert!(fds[0] != -1 && fds[0] != 0); - assert!(fds[1] != -1 && fds[1] != 0); - Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true))) - } - _ => Err(IoError::last_error()), - } +pub struct Env { + base: LPWCH, + cur: LPWCH, } -pub fn fill_utf16_buf_and_decode<F>(mut f: F) -> Option<String> where - F: FnMut(*mut u16, DWORD) -> DWORD, -{ - unsafe { - let mut n = TMPBUF_SZ as DWORD; - let mut res = None; - let mut done = false; - while !done { - let mut buf: Vec<u16> = repeat(0u16).take(n as uint).collect(); - let k = f(buf.as_mut_ptr(), n); - if k == (0 as DWORD) { - done = true; - } else if k == n && - libc::GetLastError() == - libc::ERROR_INSUFFICIENT_BUFFER as DWORD { - n *= 2 as DWORD; - } else if k >= n { - n = k; - } else { - done = true; - } - if k != 0 && done { - let sub = &buf[.. (k as uint)]; - // We want to explicitly catch the case when the - // closure returned invalid UTF-16, rather than - // set `res` to None and continue. - let s = String::from_utf16(sub).ok() - .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16"); - res = Some(s) +impl Iterator for Env { + type Item = (OsString, OsString); + + fn next(&mut self) -> Option<(OsString, OsString)> { + unsafe { + if *self.cur == 0 { return None } + let p = &*self.cur; + let mut len = 0; + while *(p as *const _).offset(len) != 0 { + len += 1; } + let p = p as *const u16; + let s = slice::from_raw_buf(&p, len as usize); + self.cur = self.cur.offset(len + 1); + + let (k, v) = match s.iter().position(|&b| b == '=' as u16) { + Some(n) => (&s[..n], &s[n+1..]), + None => (s, &[][]), + }; + Some((OsStringExt::from_wide(k), OsStringExt::from_wide(v))) } - return res; } } -pub fn getcwd() -> IoResult<Path> { - use libc::DWORD; - use libc::GetCurrentDirectoryW; - use old_io::OtherIoError; +impl Drop for Env { + fn drop(&mut self) { + unsafe { FreeEnvironmentStringsW(self.base); } + } +} - let mut buf = [0 as u16; BUF_BYTES]; +pub fn env() -> Env { unsafe { - if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD { - return Err(IoError::last_error()); + let ch = GetEnvironmentStringsW(); + if ch as usize == 0 { + panic!("failure getting env string from OS: {}", + IoError::last_error()); } + Env { base: ch, cur: ch } } +} - match String::from_utf16(truncate_utf16_at_nul(&buf)) { - Ok(ref cwd) => Ok(Path::new(cwd)), - Err(..) => Err(IoError { - kind: OtherIoError, - desc: "GetCurrentDirectoryW returned invalid UTF-16", - detail: None, - }), - } +pub struct SplitPaths<'a> { + data: EncodeWide<'a>, + must_yield: bool, } -pub unsafe fn get_env_pairs() -> Vec<Vec<u8>> { - use libc::funcs::extra::kernel32::{ - GetEnvironmentStringsW, - FreeEnvironmentStringsW - }; - let ch = GetEnvironmentStringsW(); - if ch as uint == 0 { - panic!("os::env() failure getting env string from OS: {}", - os::last_os_error()); +pub fn split_paths(unparsed: &OsStr) -> SplitPaths { + SplitPaths { + data: unparsed.encode_wide(), + must_yield: true, } - // Here, we lossily decode the string as UTF16. - // - // The docs suggest that the result should be in Unicode, but - // Windows doesn't guarantee it's actually UTF16 -- it doesn't - // validate the environment string passed to CreateProcess nor - // SetEnvironmentVariable. Yet, it's unlikely that returning a - // raw u16 buffer would be of practical use since the result would - // be inherently platform-dependent and introduce additional - // complexity to this code. - // - // Using the non-Unicode version of GetEnvironmentStrings is even - // worse since the result is in an OEM code page. Characters that - // can't be encoded in the code page would be turned into question - // marks. - let mut result = Vec::new(); - let mut i = 0; - while *ch.offset(i) != 0 { - let p = &*ch.offset(i); - let mut len = 0; - while *(p as *const _).offset(len) != 0 { - len += 1; - } - let p = p as *const u16; - let s = slice::from_raw_buf(&p, len as uint); - result.push(String::from_utf16_lossy(s).into_bytes()); - i += len as int + 1; - } - FreeEnvironmentStringsW(ch); - result } -pub fn split_paths(unparsed: &[u8]) -> Vec<Path> { - // On Windows, the PATH environment variable is semicolon separated. Double - // quotes are used as a way of introducing literal semicolons (since - // c:\some;dir is a valid Windows path). Double quotes are not themselves - // permitted in path names, so there is no way to escape a double quote. - // Quoted regions can appear in arbitrary locations, so - // - // c:\foo;c:\som"e;di"r;c:\bar - // - // Should parse as [c:\foo, c:\some;dir, c:\bar]. - // - // (The above is based on testing; there is no clear reference available - // for the grammar.) - - let mut parsed = Vec::new(); - let mut in_progress = Vec::new(); - let mut in_quote = false; - - for b in unparsed.iter() { - match *b { - b';' if !in_quote => { - parsed.push(Path::new(in_progress.as_slice())); - in_progress.truncate(0) - } - b'"' => { +impl<'a> Iterator for SplitPaths<'a> { + type Item = Path; + fn next(&mut self) -> Option<Path> { + // On Windows, the PATH environment variable is semicolon separated. + // Double quotes are used as a way of introducing literal semicolons + // (since c:\some;dir is a valid Windows path). Double quotes are not + // themselves permitted in path names, so there is no way to escape a + // double quote. Quoted regions can appear in arbitrary locations, so + // + // c:\foo;c:\som"e;di"r;c:\bar + // + // Should parse as [c:\foo, c:\some;dir, c:\bar]. + // + // (The above is based on testing; there is no clear reference available + // for the grammar.) + + + let must_yield = self.must_yield; + self.must_yield = false; + + let mut in_progress = Vec::new(); + let mut in_quote = false; + for b in self.data.by_ref() { + if b == '"' as u16 { in_quote = !in_quote; + } else if b == ';' as u16 && !in_quote { + self.must_yield = true; + break + } else { + in_progress.push(b) } - _ => { - in_progress.push(*b); - } + } + + if !must_yield && in_progress.is_empty() { + None + } else { + Some(super::os2path(&in_progress[])) } } - parsed.push(Path::new(in_progress)); - parsed } -pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> { +#[derive(Show)] +pub struct JoinPathsError; + +pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> + where I: Iterator<Item=T>, T: AsOsStr +{ let mut joined = Vec::new(); - let sep = b';'; + let sep = b';' as u16; - for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() { + for (i, path) in paths.enumerate() { + let path = path.as_os_str(); if i > 0 { joined.push(sep) } - if path.contains(&b'"') { - return Err("path segment contains `\"`"); - } else if path.contains(&sep) { - joined.push(b'"'); - joined.push_all(path); - joined.push(b'"'); + let v = path.encode_wide().collect::<Vec<u16>>(); + if v.contains(&(b'"' as u16)) { + return Err(JoinPathsError) + } else if v.contains(&sep) { + joined.push(b'"' as u16); + joined.push_all(&v[]); + joined.push(b'"' as u16); } else { - joined.push_all(path); + joined.push_all(&v[]); } } - Ok(joined) + Ok(OsStringExt::from_wide(&joined[])) } -pub fn load_self() -> Option<Vec<u8>> { - unsafe { - fill_utf16_buf_and_decode(|buf, sz| { - libc::GetModuleFileNameW(ptr::null_mut(), buf, sz) - }).map(|s| s.to_string().into_bytes()) +impl fmt::Display for JoinPathsError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "path segment contains `\"`".fmt(f) } } +impl StdError for JoinPathsError { + fn description(&self) -> &str { "failed to join paths" } +} + +pub fn current_exe() -> IoResult<Path> { + super::fill_utf16_buf(|buf, sz| unsafe { + libc::GetModuleFileNameW(ptr::null_mut(), buf, sz) + }, super::os2path) +} + +pub fn getcwd() -> IoResult<Path> { + super::fill_utf16_buf(|buf, sz| unsafe { + libc::GetCurrentDirectoryW(sz, buf) + }, super::os2path) +} + pub fn chdir(p: &Path) -> IoResult<()> { - let mut p = p.as_str().unwrap().utf16_units().collect::<Vec<u16>>(); + let mut p = p.as_os_str().encode_wide().collect::<Vec<_>>(); p.push(0); unsafe { @@ -298,39 +252,124 @@ pub fn chdir(p: &Path) -> IoResult<()> { } } -pub fn page_size() -> uint { - use mem; +pub fn getenv(k: &OsStr) -> Option<OsString> { + let k = super::to_utf16_os(k); + super::fill_utf16_buf(|buf, sz| unsafe { + libc::GetEnvironmentVariableW(k.as_ptr(), buf, sz) + }, |buf| { + OsStringExt::from_wide(buf) + }).ok() +} + +pub fn setenv(k: &OsStr, v: &OsStr) { + let k = super::to_utf16_os(k); + let v = super::to_utf16_os(v); + unsafe { - let mut info = mem::zeroed(); - libc::GetSystemInfo(&mut info); + if libc::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) == 0 { + panic!("failed to set env: {}", IoError::last_error()); + } + } +} - return info.dwPageSize as uint; +pub fn unsetenv(n: &OsStr) { + let v = super::to_utf16_os(n); + unsafe { + if libc::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) == 0 { + panic!("failed to unset env: {}", IoError::last_error()); + } } } -#[cfg(test)] -mod tests { - use super::truncate_utf16_at_nul; +pub struct Args { + range: Range<isize>, + cur: *mut *mut u16, +} - #[test] - fn test_truncate_utf16_at_nul() { - let v = []; - let b: &[u16] = &[]; - assert_eq!(truncate_utf16_at_nul(&v), b); +impl Iterator for Args { + type Item = OsString; + fn next(&mut self) -> Option<OsString> { + self.range.next().map(|i| unsafe { + let ptr = *self.cur.offset(i); + let mut len = 0; + while *ptr.offset(len) != 0 { len += 1; } + + // Push it onto the list. + let ptr = ptr as *const u16; + let buf = slice::from_raw_buf(&ptr, len as usize); + OsStringExt::from_wide(buf) + }) + } + fn size_hint(&self) -> (usize, Option<usize>) { self.range.size_hint() } +} - let v = [0, 2, 3]; - assert_eq!(truncate_utf16_at_nul(&v), b); +impl Drop for Args { + fn drop(&mut self) { + unsafe { c::LocalFree(self.cur as *mut c_void); } + } +} - let v = [1, 0, 3]; - let b: &[u16] = &[1]; - assert_eq!(truncate_utf16_at_nul(&v), b); +pub fn args() -> Args { + unsafe { + let mut nArgs: c_int = 0; + let lpCmdLine = c::GetCommandLineW(); + let szArgList = c::CommandLineToArgvW(lpCmdLine, &mut nArgs); - let v = [1, 2, 0]; - let b: &[u16] = &[1, 2]; - assert_eq!(truncate_utf16_at_nul(&v), b); + Args { cur: szArgList, range: range(0, nArgs as isize) } + } +} - let v = [1, 2, 3]; - let b: &[u16] = &[1, 2, 3]; - assert_eq!(truncate_utf16_at_nul(&v), b); +pub fn page_size() -> usize { + unsafe { + let mut info = mem::zeroed(); + libc::GetSystemInfo(&mut info); + return info.dwPageSize as usize; + } +} + +pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> { + // Windows pipes work subtly differently than unix pipes, and their + // inheritance has to be handled in a different way that I do not + // fully understand. Here we explicitly make the pipe non-inheritable, + // which means to pass it to a subprocess they need to be duplicated + // first, as in std::run. + let mut fds = [0; 2]; + match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint, + (libc::O_BINARY | libc::O_NOINHERIT) as c_int) { + 0 => { + assert!(fds[0] != -1 && fds[0] != 0); + assert!(fds[1] != -1 && fds[1] != 0); + Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true))) + } + _ => Err(IoError::last_error()), } } + +pub fn temp_dir() -> Path { + super::fill_utf16_buf(|buf, sz| unsafe { + c::GetTempPathW(sz, buf) + }, super::os2path).unwrap() +} + +pub fn home_dir() -> Option<Path> { + getenv("HOME".as_os_str()).or_else(|| { + getenv("USERPROFILE".as_os_str()) + }).map(|os| { + // FIXME: OsString => Path + Path::new(os.to_str().unwrap()) + }).or_else(|| unsafe { + let me = c::GetCurrentProcess(); + let mut token = ptr::null_mut(); + if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 { + return None + } + let _handle = RawHandle::new(token); + super::fill_utf16_buf(|buf, mut sz| { + match c::GetUserProfileDirectoryW(token, buf, &mut sz) { + 0 if libc::GetLastError() != 0 => 0, + 0 => sz, + n => n as libc::DWORD, + } + }, super::os2path).ok() + }) +} diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index 0bc2a827272..1f228b7d32e 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -352,7 +352,7 @@ impl UnixStream { fn cancel_io(&self) -> IoResult<()> { match unsafe { c::CancelIoEx(self.handle(), ptr::null_mut()) } { - 0 if os::errno() == libc::ERROR_NOT_FOUND as uint => { + 0 if os::errno() == libc::ERROR_NOT_FOUND as i32 => { Ok(()) } 0 => Err(super::last_error()), @@ -374,7 +374,7 @@ impl UnixStream { // acquire the lock. // // See comments in close_read() about why this lock is necessary. - let guard = unsafe { self.inner.lock.lock() }; + let guard = self.inner.lock.lock(); if self.read_closed() { return Err(eof()) } @@ -392,7 +392,7 @@ impl UnixStream { // If our errno doesn't say that the I/O is pending, then we hit some // legitimate error and return immediately. - if os::errno() != libc::ERROR_IO_PENDING as uint { + if os::errno() != libc::ERROR_IO_PENDING as i32 { return Err(super::last_error()) } @@ -417,7 +417,7 @@ impl UnixStream { // If we succeeded, or we failed for some reason other than // CancelIoEx, return immediately if ret != 0 { return Ok(bytes_read as uint) } - if os::errno() != libc::ERROR_OPERATION_ABORTED as uint { + if os::errno() != libc::ERROR_OPERATION_ABORTED as i32 { return Err(super::last_error()) } @@ -450,7 +450,7 @@ impl UnixStream { // going after we woke up. // // See comments in close_read() about why this lock is necessary. - let guard = unsafe { self.inner.lock.lock() }; + let guard = self.inner.lock.lock(); if self.write_closed() { return Err(epipe()) } @@ -465,7 +465,7 @@ impl UnixStream { drop(guard); if ret == 0 { - if err != libc::ERROR_IO_PENDING as uint { + if err != libc::ERROR_IO_PENDING as i32 { return Err(decode_error_detailed(err as i32)) } // Process a timeout if one is pending @@ -481,7 +481,7 @@ impl UnixStream { // aborted, then check to see if the write half was actually // closed or whether we woke up from the read half closing. if ret == 0 { - if os::errno() != libc::ERROR_OPERATION_ABORTED as uint { + if os::errno() != libc::ERROR_OPERATION_ABORTED as i32 { return Err(super::last_error()) } if !wait_succeeded.is_ok() { @@ -525,14 +525,14 @@ impl UnixStream { // close_read() between steps 1 and 2. By atomically executing steps 1 // and 2 with a lock with respect to close_read(), we're guaranteed that // no thread will erroneously sit in a read forever. - let _guard = unsafe { self.inner.lock.lock() }; + let _guard = self.inner.lock.lock(); self.inner.read_closed.store(true, Ordering::SeqCst); self.cancel_io() } pub fn close_write(&mut self) -> IoResult<()> { // see comments in close_read() for why this lock is necessary - let _guard = unsafe { self.inner.lock.lock() }; + let _guard = self.inner.lock.lock(); self.inner.write_closed.store(true, Ordering::SeqCst); self.cancel_io() } diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index 3d66718d00b..3ca735f7fdf 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -10,28 +10,27 @@ use prelude::v1::*; +use collections::hash_map::Hasher; use collections; +use env; use ffi::CString; use hash::Hash; -use collections::hash_map::Hasher; +use libc::{pid_t, c_void}; +use libc; +use mem; use old_io::fs::PathExtensions; -use old_io::process::{ProcessExit, ExitStatus, ExitSignal}; +use old_io::process::{ProcessExit, ExitStatus}; use old_io::{IoResult, IoError}; use old_io; -use libc::{pid_t, c_void, c_int}; -use libc; -use mem; use os; use path::BytesContainer; use ptr; use str; -use sys::fs::FileDesc; use sync::{StaticMutex, MUTEX_INIT}; +use sys::fs::FileDesc; -use sys::fs; -use sys::{self, retry, c, wouldblock, set_nonblocking, ms_to_timeval, timer}; -use sys_common::helper_thread::Helper; -use sys_common::{AsInner, mkerr_libc, timeout}; +use sys::timer; +use sys_common::{AsInner, timeout}; pub use sys_common::ProcessConfig; @@ -106,6 +105,7 @@ impl Process { return ret; } + #[allow(deprecated)] pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>, out_fd: Option<P>, err_fd: Option<P>) -> IoResult<Process> @@ -128,7 +128,7 @@ impl Process { use libc::funcs::extra::msvcrt::get_osfhandle; use mem; - use iter::{Iterator, IteratorExt}; + use iter::IteratorExt; use str::StrExt; if cfg.gid().is_some() || cfg.uid().is_some() { @@ -142,14 +142,14 @@ impl Process { // To have the spawning semantics of unix/windows stay the same, we need to // read the *child's* PATH if one is provided. See #15149 for more details. let program = cfg.env().and_then(|env| { - for (key, v) in env.iter() { + for (key, v) in env { if b"PATH" != key.container_as_bytes() { continue } // Split the value and test each path to see if the // program exists. - for path in os::split_paths(v.container_as_bytes()).into_iter() { + for path in os::split_paths(v.container_as_bytes()) { let path = path.join(cfg.program().as_bytes()) - .with_extension(os::consts::EXE_EXTENSION); + .with_extension(env::consts::EXE_EXTENSION); if path.exists() { return Some(CString::from_slice(path.as_vec())) } @@ -372,7 +372,7 @@ fn make_command_line(prog: &CString, args: &[CString]) -> String { let mut cmd = String::new(); append_arg(&mut cmd, str::from_utf8(prog.as_bytes()).ok() .expect("expected program name to be utf-8 encoded")); - for arg in args.iter() { + for arg in args { cmd.push(' '); append_arg(&mut cmd, str::from_utf8(arg.as_bytes()).ok() .expect("expected argument to be utf-8 encoded")); @@ -437,7 +437,7 @@ fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T Some(env) => { let mut blk = Vec::new(); - for pair in env.iter() { + for pair in env { let kv = format!("{}={}", pair.0.container_as_str().unwrap(), pair.1.container_as_str().unwrap()); diff --git a/src/libstd/sys/windows/rwlock.rs b/src/libstd/sys/windows/rwlock.rs index 88ce85c39f6..76fe352ed77 100644 --- a/src/libstd/sys/windows/rwlock.rs +++ b/src/libstd/sys/windows/rwlock.rs @@ -19,9 +19,6 @@ pub const RWLOCK_INIT: RWLock = RWLock { impl RWLock { #[inline] - pub unsafe fn new() -> RWLock { RWLOCK_INIT } - - #[inline] pub unsafe fn read(&self) { ffi::AcquireSRWLockShared(self.inner.get()) } diff --git a/src/libstd/sys/windows/stack_overflow.rs b/src/libstd/sys/windows/stack_overflow.rs index 0cb4c573ae3..b0410701ee1 100644 --- a/src/libstd/sys/windows/stack_overflow.rs +++ b/src/libstd/sys/windows/stack_overflow.rs @@ -14,7 +14,7 @@ use ptr; use mem; use libc; use libc::types::os::arch::extra::{LPVOID, DWORD, LONG, BOOL}; -use sys_common::{stack, thread_info}; +use sys_common::stack; pub struct Handler { _data: *mut libc::c_void @@ -30,14 +30,6 @@ impl Drop for Handler { fn drop(&mut self) {} } -// get_task_info is called from an exception / signal handler. -// It returns the guard page of the current task or 0 if that -// guard page doesn't exist. None is returned if there's currently -// no local task. -unsafe fn get_task_guard_page() -> uint { - thread_info::stack_guard() -} - // This is initialized in init() and only read from after static mut PAGE_SIZE: uint = 0; diff --git a/src/libstd/sys/windows/sync.rs b/src/libstd/sys/windows/sync.rs index d60646b7db9..7614104c98b 100644 --- a/src/libstd/sys/windows/sync.rs +++ b/src/libstd/sys/windows/sync.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use libc::{BOOL, DWORD, c_void, LPVOID, c_ulong}; +use libc::{BOOL, DWORD, LPVOID, c_ulong}; use libc::types::os::arch::extra::BOOLEAN; pub type PCONDITION_VARIABLE = *mut CONDITION_VARIABLE; diff --git a/src/libstd/sys/windows/tcp.rs b/src/libstd/sys/windows/tcp.rs index 64e440331c1..4804ca510cb 100644 --- a/src/libstd/sys/windows/tcp.rs +++ b/src/libstd/sys/windows/tcp.rs @@ -14,12 +14,11 @@ use libc; use mem; use ptr; use prelude::v1::*; -use super::{last_error, last_net_error, retry, sock_t}; +use super::{last_error, last_net_error, sock_t}; use sync::Arc; use sync::atomic::{AtomicBool, Ordering}; -use sys::fs::FileDesc; use sys::{self, c, set_nonblocking, wouldblock, timer}; -use sys_common::{self, timeout, eof, net}; +use sys_common::{timeout, eof, net}; pub use sys_common::net::TcpStream; @@ -202,10 +201,6 @@ impl TcpAcceptor { Err(eof()) } - pub fn socket_name(&mut self) -> IoResult<ip::SocketAddr> { - net::sockname(self.socket(), libc::getsockname) - } - pub fn set_timeout(&mut self, timeout: Option<u64>) { self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); } diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs index a94adcb3bc7..a38dc9b2d34 100644 --- a/src/libstd/sys/windows/thread.rs +++ b/src/libstd/sys/windows/thread.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::prelude::*; - use boxed::Box; use cmp; use mem; diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index 0f8ceed39a6..54a32e43daf 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -233,6 +233,7 @@ unsafe extern "system" fn on_tls_callback(h: LPVOID, } } +#[allow(dead_code)] // actually called above unsafe fn run_dtors() { let mut any_run = true; for _ in 0..5 { @@ -248,7 +249,7 @@ unsafe fn run_dtors() { DTOR_LOCK.unlock(); ret }; - for &(key, dtor) in dtors.iter() { + for &(key, dtor) in &dtors { let ptr = TlsGetValue(key); if !ptr.is_null() { TlsSetValue(key, ptr::null_mut()); diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs index 34f3c418c55..d156dd801f9 100644 --- a/src/libstd/sys/windows/timer.rs +++ b/src/libstd/sys/windows/timer.rs @@ -28,8 +28,6 @@ use ptr; use old_io::IoResult; use sync::mpsc::{channel, Sender, Receiver, TryRecvError}; -use sys::c; -use sys::fs::FileDesc; use sys_common::helper_thread::Helper; helper_init! { static HELPER: Helper<Req> } diff --git a/src/libstd/sys/windows/tty.rs b/src/libstd/sys/windows/tty.rs index 6ecabfa9853..f02c8e49f41 100644 --- a/src/libstd/sys/windows/tty.rs +++ b/src/libstd/sys/windows/tty.rs @@ -38,7 +38,7 @@ use str::from_utf8; use super::c::{ENABLE_ECHO_INPUT, ENABLE_EXTENDED_FLAGS}; use super::c::{ENABLE_INSERT_MODE, ENABLE_LINE_INPUT}; use super::c::{ENABLE_PROCESSED_INPUT, ENABLE_QUICK_EDIT_MODE}; -use super::c::{ERROR_ILLEGAL_CHARACTER, CONSOLE_SCREEN_BUFFER_INFO}; +use super::c::{CONSOLE_SCREEN_BUFFER_INFO}; use super::c::{ReadConsoleW, WriteConsoleW, GetConsoleMode, SetConsoleMode}; use super::c::{GetConsoleScreenBufferInfo}; @@ -155,9 +155,6 @@ impl TTY { (info.srWindow.Bottom + 1 - info.srWindow.Top) as int)), } } - - // Let us magically declare this as a TTY - pub fn isatty(&self) -> bool { true } } impl Drop for TTY { diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index 2a9bf452329..d4d777789dd 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -425,7 +425,7 @@ mod imp { unsafe extern fn run_dtors(mut ptr: *mut u8) { while !ptr.is_null() { let list: Box<List> = mem::transmute(ptr); - for &(ptr, dtor) in list.iter() { + for &(ptr, dtor) in &*list { dtor(ptr); } ptr = DTORS.get(); diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index 2325b3778c7..de3fa1135b1 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -1,4 +1,4 @@ -// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -24,6 +24,7 @@ pub enum Os { OsFreebsd, OsiOS, OsDragonfly, + OsOpenbsd, } #[derive(PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Clone, Copy, Debug)] @@ -134,7 +135,8 @@ impl fmt::Display for Os { OsiOS => "ios".fmt(f), OsAndroid => "android".fmt(f), OsFreebsd => "freebsd".fmt(f), - OsDragonfly => "dragonfly".fmt(f) + OsDragonfly => "dragonfly".fmt(f), + OsOpenbsd => "openbsd".fmt(f), } } } diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index 8546e03cc87..5535e5911e0 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -730,7 +730,7 @@ impl<'ast> NodeCollector<'ast> { } fn visit_fn_decl(&mut self, decl: &'ast FnDecl) { - for a in decl.inputs.iter() { + for a in &decl.inputs { self.insert(a.id, NodeArg(&*a.pat)); } } @@ -743,7 +743,7 @@ impl<'ast> Visitor<'ast> for NodeCollector<'ast> { self.parent = i.id; match i.node { ItemImpl(_, _, _, _, _, ref impl_items) => { - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { MethodImplItem(ref m) => { self.insert(m.id, NodeImplItem(impl_item)); @@ -755,12 +755,12 @@ impl<'ast> Visitor<'ast> for NodeCollector<'ast> { } } ItemEnum(ref enum_definition, _) => { - for v in enum_definition.variants.iter() { + for v in &enum_definition.variants { self.insert(v.node.id, NodeVariant(&**v)); } } ItemForeignMod(ref nm) => { - for nitem in nm.items.iter() { + for nitem in &nm.items { self.insert(nitem.id, NodeForeignItem(&**nitem)); } } @@ -774,13 +774,13 @@ impl<'ast> Visitor<'ast> for NodeCollector<'ast> { } } ItemTrait(_, _, ref bounds, ref trait_items) => { - for b in bounds.iter() { + for b in &**bounds { if let TraitTyParamBound(ref t, TraitBoundModifier::None) = *b { self.insert(t.trait_ref.ref_id, NodeItem(i)); } } - for tm in trait_items.iter() { + for tm in trait_items { match *tm { RequiredMethod(ref m) => { self.insert(m.id, NodeTraitItem(tm)); diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 7f1264ac9a1..c62f76564a7 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -102,6 +102,20 @@ pub fn is_by_value_binop(b: BinOp_) -> bool { } } +/// Returns `true` if the binary operator is symmetric in the sense that LHS +/// and RHS must have the same type. So the type of LHS can serve as an hint +/// for the type of RHS and vice versa. +pub fn is_symmetric_binop(b: BinOp_) -> bool { + match b { + BiAdd | BiSub | BiMul | BiDiv | BiRem | + BiBitXor | BiBitAnd | BiBitOr | + BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => { + true + } + _ => false + } +} + /// Returns `true` if the unary operator takes its argument by value pub fn is_by_value_unop(u: UnOp) -> bool { match u { @@ -302,7 +316,7 @@ pub fn split_trait_methods(trait_methods: &[TraitItem]) -> (Vec<TypeMethod>, Vec<P<Method>> ) { let mut reqd = Vec::new(); let mut provd = Vec::new(); - for trt_method in trait_methods.iter() { + for trt_method in trait_methods { match *trt_method { RequiredMethod(ref tm) => reqd.push((*tm).clone()), ProvidedMethod(ref m) => provd.push((*m).clone()), @@ -322,21 +336,21 @@ pub fn struct_field_visibility(field: ast::StructField) -> Visibility { pub fn operator_prec(op: ast::BinOp_) -> usize { match op { // 'as' sits here with 12 - BiMul | BiDiv | BiRem => 11us, - BiAdd | BiSub => 10us, - BiShl | BiShr => 9us, - BiBitAnd => 8us, - BiBitXor => 7us, - BiBitOr => 6us, - BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3us, - BiAnd => 2us, - BiOr => 1us + BiMul | BiDiv | BiRem => 11, + BiAdd | BiSub => 10, + BiShl | BiShr => 9, + BiBitAnd => 8, + BiBitXor => 7, + BiBitOr => 6, + BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3, + BiAnd => 2, + BiOr => 1 } } /// Precedence of the `as` operator, which is a binary operator /// not appearing in the prior table. -pub const AS_PREC: usize = 12us; +pub const AS_PREC: usize = 12; pub fn empty_generics() -> Generics { Generics { @@ -391,10 +405,10 @@ pub struct IdVisitor<'a, O:'a> { impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> { fn visit_generics_helper(&mut self, generics: &Generics) { - for type_parameter in generics.ty_params.iter() { + for type_parameter in &*generics.ty_params { self.operation.visit_id(type_parameter.id) } - for lifetime in generics.lifetimes.iter() { + for lifetime in &generics.lifetimes { self.operation.visit_id(lifetime.lifetime.id) } } @@ -430,14 +444,14 @@ impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> { ViewPathSimple(_, _) | ViewPathGlob(_) => {} ViewPathList(_, ref paths) => { - for path in paths.iter() { + for path in paths { self.operation.visit_id(path.node.id()) } } } } ItemEnum(ref enum_definition, _) => { - for variant in enum_definition.variants.iter() { + for variant in &enum_definition.variants { self.operation.visit_id(variant.node.id) } } @@ -511,7 +525,7 @@ impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> { visit::FkFnBlock => {} } - for argument in function_declaration.inputs.iter() { + for argument in &function_declaration.inputs { self.operation.visit_id(argument.id) } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 4427a7aaf02..301a18892d8 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -373,7 +373,7 @@ impl fmt::Display for StabilityLevel { fn find_stability_generic<'a, AM: AttrMetaMethods, I: Iterator<Item=&'a AM>> - (diagnostic: &SpanHandler, mut attrs: I, item_sp: Span) + (diagnostic: &SpanHandler, attrs: I, item_sp: Span) -> (Option<Stability>, Vec<&'a AM>) { let mut stab: Option<Stability> = None; @@ -394,7 +394,7 @@ fn find_stability_generic<'a, let mut feature = None; let mut since = None; let mut reason = None; - for meta in metas.iter() { + for meta in metas { if meta.name().get() == "feature" { match meta.value_str() { Some(v) => feature = Some(v), @@ -490,13 +490,13 @@ fn find_stability_generic<'a, pub fn find_stability(diagnostic: &SpanHandler, attrs: &[Attribute], item_sp: Span) -> Option<Stability> { let (s, used) = find_stability_generic(diagnostic, attrs.iter(), item_sp); - for used in used.into_iter() { mark_used(used) } + for used in used { mark_used(used) } return s; } pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) { let mut set = HashSet::new(); - for meta in metas.iter() { + for meta in metas { let name = meta.name(); if !set.insert(name.clone()) { @@ -518,7 +518,7 @@ pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAt match attr.node.value.node { ast::MetaList(ref s, ref items) if *s == "repr" => { mark_used(attr); - for item in items.iter() { + for item in items { match item.node { ast::MetaWord(ref word) => { let hint = match word.get() { diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 8adb9b24222..00857d10f43 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -431,7 +431,7 @@ impl CodeMap { let lo = self.lookup_char_pos(sp.lo); let hi = self.lookup_char_pos(sp.hi); let mut lines = Vec::new(); - for i in lo.line - 1us..hi.line as usize { + for i in lo.line - 1..hi.line as usize { lines.push(i); }; FileLines {file: lo.file, lines: lines} @@ -453,7 +453,7 @@ impl CodeMap { } pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> { - for fm in self.files.borrow().iter() { + for fm in &*self.files.borrow() { if filename == fm.name { return fm.clone(); } @@ -477,7 +477,7 @@ impl CodeMap { // The number of extra bytes due to multibyte chars in the FileMap let mut total_extra_bytes = 0; - for mbc in map.multibyte_chars.borrow().iter() { + for mbc in &*map.multibyte_chars.borrow() { debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); if mbc.pos < bpos { // every character is at least one byte, so we only @@ -499,10 +499,10 @@ impl CodeMap { let files = self.files.borrow(); let files = &*files; let len = files.len(); - let mut a = 0us; + let mut a = 0; let mut b = len; - while b - a > 1us { - let m = (a + b) / 2us; + while b - a > 1 { + let m = (a + b) / 2; if files[m].start_pos > pos { b = m; } else { @@ -538,12 +538,12 @@ impl CodeMap { let files = self.files.borrow(); let f = (*files)[idx].clone(); - let mut a = 0us; + let mut a = 0; { let lines = f.lines.borrow(); let mut b = lines.len(); - while b - a > 1us { - let m = (a + b) / 2us; + while b - a > 1 { + let m = (a + b) / 2; if (*lines)[m] > pos { b = m; } else { a = m; } } } @@ -552,7 +552,7 @@ impl CodeMap { fn lookup_pos(&self, pos: BytePos) -> Loc { let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos); - let line = a + 1us; // Line numbers start at 1 + let line = a + 1; // Line numbers start at 1 let chpos = self.bytepos_to_file_charpos(pos); let linebpos = (*f.lines.borrow())[a]; let linechpos = self.bytepos_to_file_charpos(linebpos); @@ -763,7 +763,7 @@ mod test { assert_eq!(file_lines.file.name, "blork.rs"); assert_eq!(file_lines.lines.len(), 1); - assert_eq!(file_lines.lines[0], 1us); + assert_eq!(file_lines.lines[0], 1); } #[test] diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 821ac8e2f89..d22054d8ed0 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -25,7 +25,7 @@ use term::WriterWrapper; use term; /// maximum number of lines we will print for each error; arbitrary. -static MAX_LINES: usize = 6us; +static MAX_LINES: usize = 6; #[derive(Clone, Copy)] pub enum RenderSpan { @@ -155,19 +155,19 @@ impl Handler { self.bump_err_count(); } pub fn bump_err_count(&self) { - self.err_count.set(self.err_count.get() + 1us); + self.err_count.set(self.err_count.get() + 1); } pub fn err_count(&self) -> usize { self.err_count.get() } pub fn has_errors(&self) -> bool { - self.err_count.get() > 0us + self.err_count.get() > 0 } pub fn abort_if_errors(&self) { let s; match self.err_count.get() { - 0us => return, - 1us => s = "aborting due to previous error".to_string(), + 0 => return, + 1 => s = "aborting due to previous error".to_string(), _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); @@ -457,43 +457,43 @@ fn highlight_lines(err: &mut EmitterWriter, let mut elided = false; let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { - display_lines = &display_lines[0us..MAX_LINES]; + display_lines = &display_lines[0..MAX_LINES]; elided = true; } // Print the offending lines - for &line_number in display_lines.iter() { + for &line_number in display_lines { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut err.dst, "{}:{} {}\n", fm.name, line_number + 1, line)); } } if elided { - let last_line = display_lines[display_lines.len() - 1us]; - let s = format!("{}:{} ", fm.name, last_line + 1us); + let last_line = display_lines[display_lines.len() - 1]; + let s = format!("{}:{} ", fm.name, last_line + 1); try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len())); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem - if lines.lines.len() == 1us { + if lines.lines.len() == 1 { let lo = cm.lookup_char_pos(sp.lo); - let mut digits = 0us; - let mut num = (lines.lines[0] + 1us) / 10us; + let mut digits = 0; + let mut num = (lines.lines[0] + 1) / 10; // how many digits must be indent past? - while num > 0us { num /= 10us; digits += 1us; } + while num > 0 { num /= 10; digits += 1; } // indent past |name:## | and the 0-offset column location - let left = fm.name.len() + digits + lo.col.to_usize() + 3us; + let left = fm.name.len() + digits + lo.col.to_usize() + 3; let mut s = String::new(); // Skip is the number of characters we need to skip because they are // part of the 'filename:line ' part of the previous line. - let skip = fm.name.len() + digits + 3us; + let skip = fm.name.len() + digits + 3; for _ in 0..skip { s.push(' '); } if let Some(orig) = fm.get_line(lines.lines[0]) { - for pos in 0us..left - skip { + for pos in 0..left - skip { let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). @@ -511,7 +511,7 @@ fn highlight_lines(err: &mut EmitterWriter, let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { // the ^ already takes up one space - let num_squigglies = hi.col.to_usize() - lo.col.to_usize() - 1us; + let num_squigglies = hi.col.to_usize() - lo.col.to_usize() - 1; for _ in 0..num_squigglies { s.push('~'); } @@ -550,7 +550,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, last_line_number + 1, last_line)); } } else { - for &line_number in lines.iter() { + for &line_number in lines { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, line_number + 1, line)); diff --git a/src/libsyntax/ext/concat.rs b/src/libsyntax/ext/concat.rs index 39895a3946a..4e10cc9aacc 100644 --- a/src/libsyntax/ext/concat.rs +++ b/src/libsyntax/ext/concat.rs @@ -25,7 +25,7 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, None => return base::DummyResult::expr(sp) }; let mut accumulator = String::new(); - for e in es.into_iter() { + for e in es { match e.node { ast::ExprLit(ref lit) => { match lit.node { diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 1b84d93738d..02982039be0 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -427,7 +427,7 @@ impl<'a> TraitDef<'a> { bounds.push(cx.typarambound(trait_path.clone())); // also add in any bounds from the declaration - for declared_bound in ty_param.bounds.iter() { + for declared_bound in &*ty_param.bounds { bounds.push((*declared_bound).clone()); } @@ -770,7 +770,7 @@ impl<'a> MethodDef<'a> { let mut raw_fields = Vec::new(); // ~[[fields of self], // [fields of next Self arg], [etc]] let mut patterns = Vec::new(); - for i in 0us..self_args.len() { + for i in 0..self_args.len() { let struct_path= cx.path(DUMMY_SP, vec!( type_ident )); let (pat, ident_expr) = trait_.create_struct_pattern(cx, @@ -859,8 +859,8 @@ impl<'a> MethodDef<'a> { /// (&A2(ref __self_0), /// &A2(ref __arg_1_0)) => (*__self_0).eq(&(*__arg_1_0)), /// _ => { - /// let __self_vi = match *self { A1(..) => 0us, A2(..) => 1us }; - /// let __arg_1_vi = match *__arg_1 { A1(..) => 0us, A2(..) => 1us }; + /// let __self_vi = match *self { A1(..) => 0, A2(..) => 1 }; + /// let __arg_1_vi = match *__arg_1 { A1(..) => 0, A2(..) => 1 }; /// false /// } /// } @@ -904,8 +904,8 @@ impl<'a> MethodDef<'a> { /// (Variant2, Variant2, Variant2) => ... // delegate Matching on Variant2 /// ... /// _ => { - /// let __this_vi = match this { Variant1 => 0us, Variant2 => 1us, ... }; - /// let __that_vi = match that { Variant1 => 0us, Variant2 => 1us, ... }; + /// let __this_vi = match this { Variant1 => 0, Variant2 => 1, ... }; + /// let __that_vi = match that { Variant1 => 0, Variant2 => 1, ... }; /// ... // catch-all remainder can inspect above variant index values. /// } /// } @@ -974,7 +974,7 @@ impl<'a> MethodDef<'a> { subpats.push(p); idents }; - for self_arg_name in self_arg_names.tail().iter() { + for self_arg_name in self_arg_names.tail() { let (p, idents) = mk_self_pat(cx, &self_arg_name[]); subpats.push(p); self_pats_idents.push(idents); @@ -1067,13 +1067,13 @@ impl<'a> MethodDef<'a> { // // ``` // let __self0_vi = match self { - // A => 0us, B(..) => 1us, C(..) => 2us + // A => 0, B(..) => 1, C(..) => 2 // }; // let __self1_vi = match __arg1 { - // A => 0us, B(..) => 1us, C(..) => 2us + // A => 0, B(..) => 1, C(..) => 2 // }; // let __self2_vi = match __arg2 { - // A => 0us, B(..) => 1us, C(..) => 2us + // A => 0, B(..) => 1, C(..) => 2 // }; // ``` let mut index_let_stmts: Vec<P<ast::Stmt>> = Vec::new(); diff --git a/src/libsyntax/ext/deriving/hash.rs b/src/libsyntax/ext/deriving/hash.rs index e7f546b2691..efd93226618 100644 --- a/src/libsyntax/ext/deriving/hash.rs +++ b/src/libsyntax/ext/deriving/hash.rs @@ -100,7 +100,7 @@ fn hash_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) _ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`") }; - for &FieldInfo { ref self_, span, .. } in fields.iter() { + for &FieldInfo { ref self_, span, .. } in fields { stmts.push(call_hash(span, self_.clone())); } diff --git a/src/libsyntax/ext/deriving/primitive.rs b/src/libsyntax/ext/deriving/primitive.rs index c694b054ba3..ae7b20f7853 100644 --- a/src/libsyntax/ext/deriving/primitive.rs +++ b/src/libsyntax/ext/deriving/primitive.rs @@ -93,7 +93,7 @@ fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure let mut arms = Vec::new(); - for variant in enum_def.variants.iter() { + for variant in &enum_def.variants { match variant.node.kind { ast::TupleVariantKind(ref args) => { if !args.is_empty() { diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 9f6bf352b04..9aa454ae8d5 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -21,7 +21,7 @@ use ext::base; use ext::build::AstBuilder; use parse::token; -use std::os; +use std::env; pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { @@ -30,8 +30,8 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT Some(v) => v }; - let e = match os::getenv(&var[]) { - None => { + let e = match env::var_string(&var[]) { + Err(..) => { cx.expr_path(cx.path_all(sp, true, vec!(cx.ident_of("std"), @@ -48,7 +48,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT ast::MutImmutable)), Vec::new())) } - Some(s) => { + Ok(s) => { cx.expr_call_global(sp, vec!(cx.ident_of("std"), cx.ident_of("option"), @@ -101,12 +101,12 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) } } - let e = match os::getenv(var.get()) { - None => { + let e = match env::var_string(var.get()) { + Err(..) => { cx.span_err(sp, msg.get()); cx.expr_usize(sp, 0) } - Some(s) => cx.expr_str(sp, token::intern_and_get_ident(&s[])) + Ok(s) => cx.expr_str(sp, token::intern_and_get_ident(&s[])) }; MacExpr::new(e) } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 5736400313e..6eacb344018 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -362,7 +362,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, // in this file. // Token-tree macros: MacInvocTT(pth, tts, _) => { - if pth.segments.len() > 1us { + if pth.segments.len() > 1 { fld.cx.span_err(pth.span, "expected macro name without module \ separators"); @@ -504,7 +504,7 @@ fn expand_item_modifiers(mut it: P<ast::Item>, fld: &mut MacroExpander) return it.expect_item(); } - for attr in modifiers.iter() { + for attr in &modifiers { let mname = attr.name(); match fld.cx.syntax_env.find(&intern(mname.get())) { @@ -552,7 +552,7 @@ fn expand_item_underscore(item: ast::Item_, fld: &mut MacroExpander) -> ast::Ite // does this attribute list contain "macro_use" ? fn contains_macro_use(fld: &mut MacroExpander, attrs: &[ast::Attribute]) -> bool { - for attr in attrs.iter() { + for attr in attrs { let mut is_use = attr.check_name("macro_use"); if attr.check_name("macro_escape") { fld.cx.span_warn(attr.span, "macro_escape is a deprecated synonym for macro_use"); @@ -853,7 +853,7 @@ impl<'v> Visitor<'v> for PatIdentFinder { ast::Pat { id: _, node: ast::PatIdent(_, ref path1, ref inner), span: _ } => { self.ident_accumulator.push(path1.node); // visit optional subpattern of PatIdent: - for subpat in inner.iter() { + if let Some(ref subpat) = *inner { self.visit_pat(&**subpat) } } @@ -873,7 +873,7 @@ fn pattern_bindings(pat: &ast::Pat) -> Vec<ast::Ident> { /// find the PatIdent paths in a fn fn_decl_arg_bindings(fn_decl: &ast::FnDecl) -> Vec<ast::Ident> { let mut pat_idents = PatIdentFinder{ident_accumulator:Vec::new()}; - for arg in fn_decl.inputs.iter() { + for arg in &fn_decl.inputs { pat_idents.visit_pat(&*arg.pat); } pat_idents.ident_accumulator @@ -931,7 +931,7 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { }, _ => unreachable!() }; - if pth.segments.len() > 1us { + if pth.segments.len() > 1 { fld.cx.span_err(pth.span, "expected macro name without module separators"); return DummyResult::raw_pat(span); } @@ -1063,7 +1063,7 @@ fn expand_annotatable(a: Annotatable, let mut decorator_items = SmallVector::zero(); let mut new_attrs = Vec::new(); - for attr in a.attrs().iter() { + for attr in a.attrs() { let mname = attr.name(); match fld.cx.syntax_env.find(&intern(mname.get())) { @@ -1218,7 +1218,7 @@ fn expand_item_multi_modifier(mut it: Annotatable, return it } - for attr in modifiers.iter() { + for attr in &modifiers { let mname = attr.name(); match fld.cx.syntax_env.find(&intern(mname.get())) { @@ -1420,11 +1420,11 @@ pub fn expand_crate(parse_sess: &parse::ParseSess, let mut cx = ExtCtxt::new(parse_sess, c.config.clone(), cfg); let mut expander = MacroExpander::new(&mut cx); - for def in imported_macros.into_iter() { + for def in imported_macros { expander.cx.insert_macro(def); } - for (name, extension) in user_exts.into_iter() { + for (name, extension) in user_exts { expander.cx.syntax_env.insert(name, extension); } diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 36dbf117604..16aaccb0207 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -499,7 +499,7 @@ impl<'a, 'b> Context<'a, 'b> { self.ecx.expr_ident(e.span, name))); heads.push(self.ecx.expr_addr_of(e.span, e)); } - for name in self.name_ordering.iter() { + for name in &self.name_ordering { let e = match self.names.remove(name) { Some(e) => e, None => continue @@ -706,7 +706,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, cx.ecx.span_err(cx.args[i].span, "argument never used"); } } - for (name, e) in cx.names.iter() { + for (name, e) in &cx.names { if !cx.name_types.contains_key(name) { cx.ecx.span_err(e.span, "named argument never used"); } diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 0f617302c92..9092169e182 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -694,7 +694,7 @@ fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec<P<ast::Stmt>> { fn mk_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Vec<P<ast::Stmt>> { let mut ss = Vec::new(); - for tt in tts.iter() { + for tt in tts { ss.extend(mk_tt(cx, tt).into_iter()); } ss @@ -709,7 +709,7 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) // try removing it when enough of them are gone. let mut p = cx.new_parser_from_tts(tts); - p.quote_depth += 1us; + p.quote_depth += 1; let cx_expr = p.parse_expr(); if !p.eat(&token::Comma) { diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index e3211c7c337..823efdd3eed 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -171,11 +171,11 @@ pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: ByteP stack: vec![], top_elts: TtSeq(ms), sep: sep, - idx: 0us, + idx: 0, up: None, matches: matches, - match_lo: 0us, - match_cur: 0us, + match_lo: 0, + match_cur: 0, match_hi: match_idx_hi, sp_lo: lo } @@ -209,12 +209,12 @@ pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) { match m { &TtSequence(_, ref seq) => { - for next_m in seq.tts.iter() { + for next_m in &seq.tts { n_rec(p_s, next_m, res, ret_val, idx) } } &TtDelimited(_, ref delim) => { - for next_m in delim.tts.iter() { + for next_m in &delim.tts { n_rec(p_s, next_m, res, ret_val, idx) } } @@ -238,8 +238,8 @@ pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) } } let mut ret_val = HashMap::new(); - let mut idx = 0us; - for m in ms.iter() { n_rec(p_s, m, res, &mut ret_val, &mut idx) } + let mut idx = 0; + for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) } ret_val } @@ -383,7 +383,7 @@ pub fn parse(sess: &ParseSess, if seq.op == ast::ZeroOrMore { let mut new_ei = ei.clone(); new_ei.match_cur += seq.num_captures; - new_ei.idx += 1us; + new_ei.idx += 1; //we specifically matched zero repeats. for idx in ei.match_cur..ei.match_cur + seq.num_captures { (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); @@ -398,7 +398,7 @@ pub fn parse(sess: &ParseSess, cur_eis.push(box MatcherPos { stack: vec![], sep: seq.separator.clone(), - idx: 0us, + idx: 0, matches: matches, match_lo: ei_t.match_cur, match_cur: ei_t.match_cur, @@ -442,20 +442,20 @@ pub fn parse(sess: &ParseSess, /* error messages here could be improved with links to orig. rules */ if token_name_eq(&tok, &token::Eof) { - if eof_eis.len() == 1us { + if eof_eis.len() == 1 { let mut v = Vec::new(); - for dv in (&mut eof_eis[0]).matches.iter_mut() { + for dv in &mut (&mut eof_eis[0]).matches { v.push(dv.pop().unwrap()); } return Success(nameize(sess, ms, &v[])); - } else if eof_eis.len() > 1us { + } else if eof_eis.len() > 1 { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { return Failure(sp, "unexpected end of macro invocation".to_string()); } } else { - if (bb_eis.len() > 0us && next_eis.len() > 0us) - || bb_eis.len() > 1us { + if (bb_eis.len() > 0 && next_eis.len() > 0) + || bb_eis.len() > 1 { let nts = bb_eis.iter().map(|ei| { match ei.top_elts.get_tt(ei.idx) { TtToken(_, MatchNt(bind, name, _, _)) => { @@ -469,12 +469,12 @@ pub fn parse(sess: &ParseSess, "local ambiguity: multiple parsing options: \ built-in NTs {} or {} other options.", nts, next_eis.len()).to_string()); - } else if bb_eis.len() == 0us && next_eis.len() == 0us { + } else if bb_eis.len() == 0 && next_eis.len() == 0 { return Failure(sp, format!("no rules expected the token `{}`", pprust::token_to_string(&tok)).to_string()); - } else if next_eis.len() > 0us { + } else if next_eis.len() > 0 { /* Now process the next token */ - while next_eis.len() > 0us { + while next_eis.len() > 0 { cur_eis.push(next_eis.pop().unwrap()); } rdr.next_token(); @@ -488,7 +488,7 @@ pub fn parse(sess: &ParseSess, let match_cur = ei.match_cur; (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal( parse_nt(&mut rust_parser, span, name_string.get())))); - ei.idx += 1us; + ei.idx += 1; ei.match_cur += 1; } _ => panic!() @@ -501,16 +501,16 @@ pub fn parse(sess: &ParseSess, } } - assert!(cur_eis.len() > 0us); + assert!(cur_eis.len() > 0); } } pub fn parse_nt(p: &mut Parser, sp: Span, name: &str) -> Nonterminal { match name { "tt" => { - p.quote_depth += 1us; //but in theory, non-quoted tts might be useful + p.quote_depth += 1; //but in theory, non-quoted tts might be useful let res = token::NtTT(P(p.parse_token_tree())); - p.quote_depth -= 1us; + p.quote_depth -= 1; return res; } _ => {} diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 666281ac6b6..ac9f375e0a4 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -259,7 +259,7 @@ pub fn compile<'cx>(cx: &'cx mut ExtCtxt, _ => cx.span_bug(def.span, "wrong-structured lhs") }; - for lhs in lhses.iter() { + for lhs in &lhses { check_lhs_nt_follows(cx, &**lhs, def.span); } diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 0bf20b8f3e1..83234e3b7a5 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -223,7 +223,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { r.repeat_len.pop(); } } else { /* repeat */ - *r.repeat_idx.last_mut().unwrap() += 1us; + *r.repeat_idx.last_mut().unwrap() += 1; r.stack.last_mut().unwrap().idx = 0; match r.stack.last().unwrap().sep.clone() { Some(tk) => { diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 775cfede70d..4e76359e930 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -253,7 +253,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } fn visit_item(&mut self, i: &ast::Item) { - for attr in i.attrs.iter() { + for attr in &i.attrs { if attr.name() == "thread_local" { self.gate_feature("thread_local", i.span, "`#[thread_local]` is an experimental feature, and does not \ @@ -508,7 +508,7 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::C let mut unknown_features = Vec::new(); - for attr in krate.attrs.iter() { + for attr in &krate.attrs { if !attr.check_name("feature") { continue } @@ -519,7 +519,7 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::C expected #![feature(...)]"); } Some(list) => { - for mi in list.iter() { + for mi in list { let name = match mi.node { ast::MetaWord(ref word) => (*word).clone(), _ => { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index a1362f5382c..9012ec2114d 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -37,7 +37,7 @@ pub trait MoveMap<T> { impl<T> MoveMap<T> for Vec<T> { fn move_map<F>(mut self, mut f: F) -> Vec<T> where F: FnMut(T) -> T { - for p in self.iter_mut() { + for p in &mut self { unsafe { // FIXME(#5016) this shouldn't need to zero to be safe. ptr::write(p, f(ptr::read_and_zero(p))); @@ -1117,7 +1117,7 @@ pub fn noop_fold_crate<T: Folder>(Crate {module, attrs, config, mut exported_mac }, vec![], span) }; - for def in exported_macros.iter_mut() { + for def in &mut exported_macros { def.id = folder.new_id(def.id); } diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 73424136cfb..08e795ef80d 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -23,16 +23,14 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap - #![feature(box_syntax)] #![feature(collections)] #![feature(core)] +#![feature(env)] #![feature(hash)] #![feature(int_uint)] #![feature(io)] #![feature(libc)] -#![feature(os)] #![feature(path)] #![feature(quote, unsafe_destructor)] #![feature(rustc_private)] diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index 54ec9c7b146..06e8728d236 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -13,7 +13,7 @@ use ast; use codemap::{spanned, Spanned, mk_sp, Span}; use parse::common::*; //resolve bug? use parse::token; -use parse::parser::Parser; +use parse::parser::{Parser, TokenType}; use ptr::P; /// A parser that can parse attributes. @@ -69,7 +69,9 @@ impl<'a> ParserAttr for Parser<'a> { let lo = self.span.lo; self.bump(); - let style = if self.eat(&token::Not) { + if permit_inner { self.expected_tokens.push(TokenType::Token(token::Not)); } + let style = if self.token == token::Not { + self.bump(); if !permit_inner { let span = self.span; self.span_err(span, @@ -96,7 +98,8 @@ impl<'a> ParserAttr for Parser<'a> { } }; - if permit_inner && self.eat(&token::Semi) { + if permit_inner && self.token == token::Semi { + self.bump(); self.span_warn(span, "this inner attribute syntax is deprecated. \ The new syntax is `#![foo]`, with a bang and no semicolon"); style = ast::AttrInner; diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 926385ccd11..b17fc7fe82e 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -62,7 +62,7 @@ pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { pub fn strip_doc_comment_decoration(comment: &str) -> String { /// remove whitespace-only lines from the start/end of lines fn vertical_trim(lines: Vec<String> ) -> Vec<String> { - let mut i = 0us; + let mut i = 0; let mut j = lines.len(); // first line of all-stars should be omitted if lines.len() > 0 && @@ -90,7 +90,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { let mut i = usize::MAX; let mut can_trim = true; let mut first = true; - for line in lines.iter() { + for line in &lines { for (j, c) in line.chars().enumerate() { if j > i || !"* \t".contains_char(c) { can_trim = false; @@ -125,7 +125,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { // one-line comments lose their prefix static ONLINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; - for prefix in ONLINERS.iter() { + for prefix in ONLINERS { if comment.starts_with(*prefix) { return (&comment[prefix.len()..]).to_string(); } @@ -158,7 +158,7 @@ fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec<Comment>) { fn consume_whitespace_counting_blank_lines(rdr: &mut StringReader, comments: &mut Vec<Comment>) { while is_whitespace(rdr.curr) && !rdr.is_eof() { - if rdr.col == CharPos(0us) && rdr.curr_is('\n') { + if rdr.col == CharPos(0) && rdr.curr_is('\n') { push_blank_line_comment(rdr, &mut *comments); } rdr.bump(); @@ -305,7 +305,7 @@ fn read_block_comment(rdr: &mut StringReader, let mut style = if code_to_the_left { Trailing } else { Isolated }; rdr.consume_non_eol_whitespace(); - if !rdr.is_eof() && !rdr.curr_is('\n') && lines.len() == 1us { + if !rdr.is_eof() && !rdr.curr_is('\n') && lines.len() == 1 { style = Mixed; } debug!("<<< block comment"); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 2cf6058a433..e6da47304ce 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -279,7 +279,7 @@ impl<'a> StringReader<'a> { /// Converts CRLF to LF in the given string, raising an error on bare CR. fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> CowString<'b> { - let mut i = 0us; + let mut i = 0; while i < s.len() { let str::CharRange { ch, next } = s.char_range_at(i); if ch == '\r' { @@ -331,10 +331,10 @@ impl<'a> StringReader<'a> { let byte_offset_diff = next.next - current_byte_offset; self.pos = self.pos + Pos::from_usize(byte_offset_diff); self.curr = Some(next.ch); - self.col = self.col + CharPos(1us); + self.col = self.col + CharPos(1); if last_char == '\n' { self.filemap.next_line(self.last_pos); - self.col = CharPos(0us); + self.col = CharPos(0); } if byte_offset_diff > 1 { @@ -472,7 +472,7 @@ impl<'a> StringReader<'a> { cmap.files.borrow_mut().push(self.filemap.clone()); let loc = cmap.lookup_char_pos_adj(self.last_pos); debug!("Skipping a shebang"); - if loc.line == 1us && loc.col == CharPos(0us) { + if loc.line == 1 && loc.col == CharPos(0) { // FIXME: Add shebang "token", return it let start = self.last_pos; while !self.curr_is('\n') && !self.is_eof() { self.bump(); } @@ -646,7 +646,7 @@ impl<'a> StringReader<'a> { /// Scan through any digits (base `radix`) or underscores, and return how /// many digits there were. fn scan_digits(&mut self, radix: usize) -> usize { - let mut len = 0us; + let mut len = 0; loop { let c = self.curr; if c == Some('_') { debug!("skipping a _"); self.bump(); continue; } @@ -799,14 +799,14 @@ impl<'a> StringReader<'a> { if self.curr == Some('{') { self.scan_unicode_escape(delim) } else { - let res = self.scan_hex_digits(4us, delim, false); + let res = self.scan_hex_digits(4, delim, false); let sp = codemap::mk_sp(escaped_pos, self.last_pos); self.old_escape_warning(sp); res } } 'U' if !ascii_only => { - let res = self.scan_hex_digits(8us, delim, false); + let res = self.scan_hex_digits(8, delim, false); let sp = codemap::mk_sp(escaped_pos, self.last_pos); self.old_escape_warning(sp); res @@ -877,7 +877,7 @@ impl<'a> StringReader<'a> { fn scan_unicode_escape(&mut self, delim: char) -> bool { self.bump(); // past the { let start_bpos = self.last_pos; - let mut count = 0us; + let mut count = 0; let mut accum_int = 0; while !self.curr_is('}') && count <= 6 { @@ -937,10 +937,10 @@ impl<'a> StringReader<'a> { /// error if it isn't. fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) { match base { - 16us => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \ + 16 => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \ supported"), - 8us => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"), - 2us => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"), + 8 => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"), + 2 => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"), _ => () } } @@ -1189,7 +1189,7 @@ impl<'a> StringReader<'a> { 'r' => { let start_bpos = self.last_pos; self.bump(); - let mut hash_count = 0us; + let mut hash_count = 0; while self.curr_is('#') { self.bump(); hash_count += 1; @@ -1374,7 +1374,7 @@ impl<'a> StringReader<'a> { fn scan_raw_byte_string(&mut self) -> token::Lit { let start_bpos = self.last_pos; self.bump(); - let mut hash_count = 0us; + let mut hash_count = 0; while self.curr_is('#') { self.bump(); hash_count += 1; @@ -1526,7 +1526,7 @@ mod test { // check that the given reader produces the desired stream // of tokens (stop checking after exhausting the expected vec) fn check_tokenization (mut string_reader: StringReader, expected: Vec<token::Token> ) { - for expected_tok in expected.iter() { + for expected_tok in &expected { assert_eq!(&string_reader.next_token().tok, expected_tok); } } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 8ac5b6e5274..eecd7d87185 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -181,7 +181,7 @@ pub fn parse_tts_from_source_str(name: String, name, source ); - p.quote_depth += 1us; + p.quote_depth += 1; // right now this is re-creating the token trees from ... token trees. maybe_aborted(p.parse_all_token_trees(),p) } @@ -324,7 +324,7 @@ pub mod with_hygiene { name, source ); - p.quote_depth += 1us; + p.quote_depth += 1; // right now this is re-creating the token trees from ... token trees. maybe_aborted(p.parse_all_token_trees(),p) } @@ -436,7 +436,7 @@ pub fn str_lit(lit: &str) -> String { let error = |&: i| format!("lexer should have rejected {} at {}", lit, i); /// Eat everything up to a non-whitespace - fn eat<'a>(it: &mut iter::Peekable<(usize, char), str::CharIndices<'a>>) { + fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) { loop { match it.peek().map(|x| x.1) { Some(' ') | Some('\n') | Some('\r') | Some('\t') => { @@ -605,7 +605,7 @@ pub fn binary_lit(lit: &str) -> Rc<Vec<u8>> { let error = |&: i| format!("lexer should have rejected {} at {}", lit, i); /// Eat everything up to a non-whitespace - fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<(usize, u8), I>) { + fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) { loop { match it.peek().map(|x| x.1) { Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => { @@ -683,9 +683,9 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> match suffix { Some(suf) if looks_like_width_suffix(&['f'], suf) => { match base { - 16us => sd.span_err(sp, "hexadecimal float literal is not supported"), - 8us => sd.span_err(sp, "octal float literal is not supported"), - 2us => sd.span_err(sp, "binary float literal is not supported"), + 16 => sd.span_err(sp, "hexadecimal float literal is not supported"), + 8 => sd.span_err(sp, "octal float literal is not supported"), + 2 => sd.span_err(sp, "binary float literal is not supported"), _ => () } let ident = token::intern_and_get_ident(&*s); @@ -755,6 +755,7 @@ mod test { use ast; use abi; use attr::{first_attr_value_str_by_name, AttrMetaMethods}; + use parse; use parse::parser::Parser; use parse::token::{str_to_ident}; use print::pprust::item_to_string; @@ -1163,7 +1164,7 @@ mod test { "impl z { fn a (self: Foo, &myarg: i32) {} }", ]; - for &src in srcs.iter() { + for &src in &srcs { let spans = get_spans_of_pat_idents(src); let Span{ lo, hi, .. } = spans[0]; assert!("self" == &src[lo.to_usize()..hi.to_usize()], @@ -1214,4 +1215,26 @@ mod test { let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap(); assert_eq!(doc.get(), "/** doc comment\n * with CRLF */"); } + + #[test] + fn ttdelim_span() { + let sess = parse::new_parse_sess(); + let expr = parse::parse_expr_from_source_str("foo".to_string(), + "foo!( fn main() { body } )".to_string(), vec![], &sess); + + let tts = match expr.node { + ast::ExprMac(ref mac) => { + let ast::MacInvocTT(_, ref tts, _) = mac.node; + tts.clone() + } + _ => panic!("not a macro"), + }; + + let span = tts.iter().rev().next().unwrap().get_span(); + + match sess.span_diagnostic.cm.span_to_snippet(span) { + Some(s) => assert_eq!(&s[], "{ body }"), + None => panic!("could not get snippet"), + } + } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index d99095eeba3..c3182602a4b 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -290,6 +290,7 @@ pub struct Parser<'a> { #[derive(PartialEq, Eq, Clone)] pub enum TokenType { Token(token::Token), + Keyword(keywords::Keyword), Operator, } @@ -298,6 +299,7 @@ impl TokenType { match *self { TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)), TokenType::Operator => "an operator".to_string(), + TokenType::Keyword(kw) => format!("`{}`", token::get_name(kw.to_name())), } } } @@ -365,9 +367,9 @@ impl<'a> Parser<'a> { token_str)[]); } - pub fn unexpected(&self) -> ! { - let this_token = self.this_token_to_string(); - self.fatal(&format!("unexpected token: `{}`", this_token)[]); + pub fn unexpected(&mut self) -> ! { + self.expect_one_of(&[], &[]); + unreachable!() } /// Expect and consume the token t. Signal an error if @@ -425,10 +427,13 @@ impl<'a> Parser<'a> { let expect = tokens_to_string(&expected[]); let actual = self.this_token_to_string(); self.fatal( - &(if expected.len() != 1 { + &(if expected.len() > 1 { (format!("expected one of {}, found `{}`", expect, actual)) + } else if expected.len() == 0 { + (format!("unexpected token: `{}`", + actual)) } else { (format!("expected {}, found `{}`", expect, @@ -515,7 +520,7 @@ impl<'a> Parser<'a> { pub fn parse_path_list_item(&mut self) -> ast::PathListItem { let lo = self.span.lo; - let node = if self.eat_keyword(keywords::Mod) { + let node = if self.eat_keyword_noexpect(keywords::Mod) { let span = self.last_span; self.span_warn(span, "deprecated syntax; use the `self` keyword now"); ast::PathListMod { id: ast::DUMMY_NODE_ID } @@ -547,9 +552,23 @@ impl<'a> Parser<'a> { is_present } + pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool { + self.expected_tokens.push(TokenType::Keyword(kw)); + self.token.is_keyword(kw) + } + /// If the next token is the given keyword, eat it and return /// true. Otherwise, return false. pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool { + if self.check_keyword(kw) { + self.bump(); + true + } else { + false + } + } + + pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool { if self.token.is_keyword(kw) { self.bump(); true @@ -563,10 +582,7 @@ impl<'a> Parser<'a> { /// Otherwise, eat it. pub fn expect_keyword(&mut self, kw: keywords::Keyword) { if !self.eat_keyword(kw) { - let id_interned_str = token::get_name(kw.to_name()); - let token_str = self.this_token_to_string(); - self.fatal(&format!("expected `{}`, found `{}`", - id_interned_str, token_str)[]) + self.expect_one_of(&[], &[]); } } @@ -593,6 +609,7 @@ impl<'a> Parser<'a> { /// Expect and consume an `&`. If `&&` is seen, replace it with a single /// `&` and continue. If an `&` is not seen, signal an error. fn expect_and(&mut self) { + self.expected_tokens.push(TokenType::Token(token::BinOp(token::And))); match self.token { token::BinOp(token::And) => self.bump(), token::AndAnd => { @@ -601,12 +618,7 @@ impl<'a> Parser<'a> { self.replace_token(token::BinOp(token::And), lo, span.hi) } _ => { - let token_str = self.this_token_to_string(); - let found_token = - Parser::token_to_string(&token::BinOp(token::And)); - self.fatal(&format!("expected `{}`, found `{}`", - found_token, - token_str)[]) + self.expect_one_of(&[], &[]); } } } @@ -614,6 +626,7 @@ impl<'a> Parser<'a> { /// Expect and consume a `|`. If `||` is seen, replace it with a single /// `|` and continue. If a `|` is not seen, signal an error. fn expect_or(&mut self) { + self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or))); match self.token { token::BinOp(token::Or) => self.bump(), token::OrOr => { @@ -622,12 +635,7 @@ impl<'a> Parser<'a> { self.replace_token(token::BinOp(token::Or), lo, span.hi) } _ => { - let found_token = self.this_token_to_string(); - let token_str = - Parser::token_to_string(&token::BinOp(token::Or)); - self.fatal(&format!("expected `{}`, found `{}`", - token_str, - found_token)[]) + self.expect_one_of(&[], &[]); } } } @@ -652,6 +660,7 @@ impl<'a> Parser<'a> { /// This is meant to be used when parsing generics on a path to get the /// starting token. fn eat_lt(&mut self) -> bool { + self.expected_tokens.push(TokenType::Token(token::Lt)); match self.token { token::Lt => { self.bump(); true } token::BinOp(token::Shl) => { @@ -666,11 +675,7 @@ impl<'a> Parser<'a> { fn expect_lt(&mut self) { if !self.eat_lt() { - let found_token = self.this_token_to_string(); - let token_str = Parser::token_to_string(&token::Lt); - self.fatal(&format!("expected `{}`, found `{}`", - token_str, - found_token)[]) + self.expect_one_of(&[], &[]); } } @@ -700,6 +705,7 @@ impl<'a> Parser<'a> { /// with a single > and continue. If a GT is not seen, /// signal an error. pub fn expect_gt(&mut self) { + self.expected_tokens.push(TokenType::Token(token::Gt)); match self.token { token::Gt => self.bump(), token::BinOp(token::Shr) => { @@ -740,7 +746,7 @@ impl<'a> Parser<'a> { // would encounter a `>` and stop. This lets the parser handle trailing // commas in generic parameters, because it can stop either after // parsing a type or after parsing a comma. - for i in iter::count(0us, 1) { + for i in iter::count(0, 1) { if self.check(&token::Gt) || self.token == token::BinOp(token::Shr) || self.token == token::Ge @@ -917,7 +923,7 @@ impl<'a> Parser<'a> { }; self.span = next.sp; self.token = next.tok; - self.tokens_consumed += 1us; + self.tokens_consumed += 1; self.expected_tokens.clear(); // check after each token self.check_unknown_macro_variable(); @@ -998,14 +1004,14 @@ impl<'a> Parser<'a> { /// Is the current token one of the keywords that signals a bare function /// type? pub fn token_is_bare_fn_keyword(&mut self) -> bool { - self.token.is_keyword(keywords::Fn) || - self.token.is_keyword(keywords::Unsafe) || - self.token.is_keyword(keywords::Extern) + self.check_keyword(keywords::Fn) || + self.check_keyword(keywords::Unsafe) || + self.check_keyword(keywords::Extern) } /// Is the current token one of the keywords that signals a closure type? pub fn token_is_closure_keyword(&mut self) -> bool { - self.token.is_keyword(keywords::Unsafe) + self.check_keyword(keywords::Unsafe) } pub fn get_lifetime(&mut self) -> ast::Ident { @@ -1035,7 +1041,7 @@ impl<'a> Parser<'a> { let lifetime_defs = self.parse_late_bound_lifetime_defs(); // examine next token to decide to do - if self.eat_keyword(keywords::Proc) { + if self.eat_keyword_noexpect(keywords::Proc) { self.parse_proc_type(lifetime_defs) } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() { self.parse_ty_bare_fn_or_ty_closure(lifetime_defs) @@ -1166,11 +1172,11 @@ impl<'a> Parser<'a> { // Closure: [unsafe] <'lt> |S| [:Bounds] -> T // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T - if self.token.is_keyword(keywords::Fn) { + if self.check_keyword(keywords::Fn) { self.parse_ty_bare_fn(lifetime_defs) - } else if self.token.is_keyword(keywords::Extern) { + } else if self.check_keyword(keywords::Extern) { self.parse_ty_bare_fn(lifetime_defs) - } else if self.token.is_keyword(keywords::Unsafe) { + } else if self.check_keyword(keywords::Unsafe) { if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) || t.is_keyword(keywords::Extern)) { self.parse_ty_bare_fn(lifetime_defs) @@ -1480,7 +1486,7 @@ impl<'a> Parser<'a> { // BORROWED POINTER self.expect_and(); self.parse_borrowed_pointee() - } else if self.token.is_keyword(keywords::For) { + } else if self.check_keyword(keywords::For) { self.parse_for_in_type() } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() { @@ -1494,14 +1500,14 @@ impl<'a> Parser<'a> { })) { // CLOSURE self.parse_ty_closure(Vec::new()) - } else if self.eat_keyword(keywords::Typeof) { + } else if self.eat_keyword_noexpect(keywords::Typeof) { // TYPEOF // In order to not be ambiguous, the type must be surrounded by parens. self.expect(&token::OpenDelim(token::Paren)); let e = self.parse_expr(); self.expect(&token::CloseDelim(token::Paren)); TyTypeof(e) - } else if self.eat_keyword(keywords::Proc) { + } else if self.eat_keyword_noexpect(keywords::Proc) { self.parse_proc_type(Vec::new()) } else if self.eat_lt() { // QUALIFIED PATH `<TYPE as TRAIT_REF>::item` @@ -2092,6 +2098,7 @@ impl<'a> Parser<'a> { } fn expect_open_delim(&mut self) -> token::DelimToken { + self.expected_tokens.push(TokenType::Token(token::Gt)); match self.token { token::OpenDelim(delim) => { self.bump(); @@ -2233,7 +2240,7 @@ impl<'a> Parser<'a> { if self.eat_keyword(keywords::Move) { return self.parse_lambda_expr(CaptureByValue); } - if self.eat_keyword(keywords::Proc) { + if self.eat_keyword_noexpect(keywords::Proc) { let span = self.last_span; let _ = self.parse_proc_decl(); let _ = self.parse_expr(); @@ -2307,8 +2314,8 @@ impl<'a> Parser<'a> { hi = self.span.hi; } else if self.check(&token::ModSep) || self.token.is_ident() && - !self.token.is_keyword(keywords::True) && - !self.token.is_keyword(keywords::False) { + !self.check_keyword(keywords::True) && + !self.check_keyword(keywords::False) { let pth = self.parse_path(LifetimeAndTypesWithColons); @@ -2625,7 +2632,7 @@ impl<'a> Parser<'a> { } pub fn check_unknown_macro_variable(&mut self) { - if self.quote_depth == 0us { + if self.quote_depth == 0 { match self.token { token::SubstNt(name, _) => self.fatal(&format!("unknown macro variable `{}`", @@ -2694,7 +2701,7 @@ impl<'a> Parser<'a> { token_str)[]) }, /* we ought to allow different depths of unquotation */ - token::Dollar | token::SubstNt(..) if p.quote_depth > 0us => { + token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => { p.parse_unquoted() } _ => { @@ -2706,7 +2713,7 @@ impl<'a> Parser<'a> { match self.token { token::Eof => { let open_braces = self.open_braces.clone(); - for sp in open_braces.iter() { + for sp in &open_braces { self.span_help(*sp, "did you mean to close this delimiter?"); } // There shouldn't really be a span, but it's easier for the test runner @@ -2735,7 +2742,7 @@ impl<'a> Parser<'a> { self.open_braces.pop().unwrap(); // Expand to cover the entire delimited token tree - let span = Span { hi: self.span.hi, ..pre_span }; + let span = Span { hi: close_span.hi, ..pre_span }; TtDelimited(span, Rc::new(Delimited { delim: delim, @@ -2792,7 +2799,7 @@ impl<'a> Parser<'a> { ex = ExprAddrOf(m, e); } token::Ident(_, _) => { - if !self.token.is_keyword(keywords::Box) { + if !self.check_keyword(keywords::Box) { return self.parse_dot_or_call_expr(); } @@ -2879,7 +2886,7 @@ impl<'a> Parser<'a> { } } None => { - if AS_PREC >= min_prec && self.eat_keyword(keywords::As) { + if AS_PREC >= min_prec && self.eat_keyword_noexpect(keywords::As) { let rhs = self.parse_ty(); let _as = self.mk_expr(lhs.span.lo, rhs.span.hi, @@ -3002,7 +3009,7 @@ impl<'a> Parser<'a> { /// Parse an 'if' or 'if let' expression ('if' token already eaten) pub fn parse_if_expr(&mut self) -> P<Expr> { - if self.token.is_keyword(keywords::Let) { + if self.check_keyword(keywords::Let) { return self.parse_if_let_expr(); } let lo = self.last_span.lo; @@ -3655,7 +3662,7 @@ impl<'a> Parser<'a> { } let lo = self.span.lo; - if self.token.is_keyword(keywords::Let) { + if self.check_keyword(keywords::Let) { check_expected_item(self, &item_attrs[]); self.expect_keyword(keywords::Let); let decl = self.parse_let(); @@ -5200,7 +5207,7 @@ impl<'a> Parser<'a> { Some(i) => { let mut err = String::from_str("circular modules: "); let len = included_mod_stack.len(); - for p in included_mod_stack[i.. len].iter() { + for p in &included_mod_stack[i.. len] { err.push_str(&p.display().as_cow()[]); err.push_str(" -> "); } @@ -5302,7 +5309,7 @@ impl<'a> Parser<'a> { let (maybe_path, ident) = match self.token { token::Ident(..) => { let the_ident = self.parse_ident(); - let path = if self.eat_keyword(keywords::As) { + let path = if self.eat_keyword_noexpect(keywords::As) { // skip the ident if there is one if self.token.is_ident() { self.bump(); } @@ -5445,7 +5452,7 @@ impl<'a> Parser<'a> { seq_sep_trailing_allowed(token::Comma), |p| p.parse_ty_sum() ); - for ty in arg_tys.into_iter() { + for ty in arg_tys { args.push(ast::VariantArg { ty: ty, id: ast::DUMMY_NODE_ID, @@ -5595,14 +5602,13 @@ impl<'a> Parser<'a> { token_str)[]); } - if self.eat_keyword(keywords::Virtual) { + if self.eat_keyword_noexpect(keywords::Virtual) { let span = self.span; self.span_err(span, "`virtual` structs have been removed from the language"); } - if self.token.is_keyword(keywords::Static) { + if self.eat_keyword(keywords::Static) { // STATIC ITEM - self.bump(); let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable}; let (ident, item_, extra_attrs) = self.parse_item_const(Some(m)); let last_span = self.last_span; @@ -5614,9 +5620,8 @@ impl<'a> Parser<'a> { maybe_append(attrs, extra_attrs)); return Ok(item); } - if self.token.is_keyword(keywords::Const) { + if self.eat_keyword(keywords::Const) { // CONST ITEM - self.bump(); if self.eat_keyword(keywords::Mut) { let last_span = self.last_span; self.span_err(last_span, "const globals cannot be mutable"); @@ -5632,8 +5637,8 @@ impl<'a> Parser<'a> { maybe_append(attrs, extra_attrs)); return Ok(item); } - if self.token.is_keyword(keywords::Unsafe) && - self.look_ahead(1us, |t| t.is_keyword(keywords::Trait)) + if self.check_keyword(keywords::Unsafe) && + self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) { // UNSAFE TRAIT ITEM self.expect_keyword(keywords::Unsafe); @@ -5649,8 +5654,8 @@ impl<'a> Parser<'a> { maybe_append(attrs, extra_attrs)); return Ok(item); } - if self.token.is_keyword(keywords::Unsafe) && - self.look_ahead(1us, |t| t.is_keyword(keywords::Impl)) + if self.check_keyword(keywords::Unsafe) && + self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) { // IMPL ITEM self.expect_keyword(keywords::Unsafe); @@ -5665,7 +5670,7 @@ impl<'a> Parser<'a> { maybe_append(attrs, extra_attrs)); return Ok(item); } - if self.token.is_keyword(keywords::Fn) { + if self.check_keyword(keywords::Fn) { // FUNCTION ITEM self.bump(); let (ident, item_, extra_attrs) = @@ -5679,8 +5684,8 @@ impl<'a> Parser<'a> { maybe_append(attrs, extra_attrs)); return Ok(item); } - if self.token.is_keyword(keywords::Unsafe) - && self.look_ahead(1us, |t| *t != token::OpenDelim(token::Brace)) { + if self.check_keyword(keywords::Unsafe) + && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) { // UNSAFE FUNCTION ITEM self.bump(); let abi = if self.eat_keyword(keywords::Extern) { @@ -5784,11 +5789,11 @@ impl<'a> Parser<'a> { let visibility = self.parse_visibility(); - if self.token.is_keyword(keywords::Static) { + if self.check_keyword(keywords::Static) { // FOREIGN STATIC ITEM return Ok(self.parse_item_foreign_static(visibility, attrs)); } - if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) { + if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) { // FOREIGN FUNCTION ITEM return Ok(self.parse_item_foreign_fn(visibility, attrs)); } @@ -5912,9 +5917,9 @@ impl<'a> Parser<'a> { self.bump(); match self.token { - token::Ident(i, _) => { - self.bump(); - path.push(i); + token::Ident(..) => { + let ident = self.parse_ident(); + path.push(ident); } // foo::bar::{a,b,c} @@ -5954,11 +5959,16 @@ impl<'a> Parser<'a> { return P(spanned(lo, self.span.hi, ViewPathGlob(path))); } + // fall-through for case foo::bar::; + token::Semi => { + self.span_err(self.span, "expected identifier or `{` or `*`, found `;`"); + } + _ => break } } } - let mut rename_to = path[path.len() - 1us]; + let mut rename_to = path[path.len() - 1]; let path = ast::Path { span: mk_sp(lo, self.last_span.hi), global: false, diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 5531ce7b119..5c3892e49c0 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -456,7 +456,7 @@ macro_rules! declare_special_idents_and_keywords {( pub use self::Keyword::*; use ast; - #[derive(Copy)] + #[derive(Copy, Clone, PartialEq, Eq)] pub enum Keyword { $( $sk_variant, )* $( $rk_variant, )* diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 70d6a5f695a..707b3c72ecd 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -132,15 +132,15 @@ pub fn buf_str(toks: &[Token], let mut i = left; let mut l = lim; let mut s = string::String::from_str("["); - while i != right && l != 0us { - l -= 1us; + while i != right && l != 0 { + l -= 1; if i != left { s.push_str(", "); } s.push_str(&format!("{}={}", szs[i], tok_str(&toks[i]))[]); - i += 1us; + i += 1; i %= n; } s.push(']'); @@ -326,8 +326,8 @@ impl Printer { if self.scan_stack_empty { self.left_total = 1; self.right_total = 1; - self.left = 0us; - self.right = 0us; + self.left = 0; + self.right = 0; } else { self.advance_right(); } debug!("pp Begin({})/buffer ~[{},{}]", b.offset, self.left, self.right); @@ -355,8 +355,8 @@ impl Printer { if self.scan_stack_empty { self.left_total = 1; self.right_total = 1; - self.left = 0us; - self.right = 0us; + self.left = 0; + self.right = 0; } else { self.advance_right(); } debug!("pp Break({})/buffer ~[{},{}]", b.offset, self.left, self.right); @@ -410,7 +410,7 @@ impl Printer { if self.scan_stack_empty { self.scan_stack_empty = false; } else { - self.top += 1us; + self.top += 1; self.top %= self.buf_len; assert!((self.top != self.bottom)); } @@ -422,7 +422,7 @@ impl Printer { if self.top == self.bottom { self.scan_stack_empty = true; } else { - self.top += self.buf_len - 1us; self.top %= self.buf_len; + self.top += self.buf_len - 1; self.top %= self.buf_len; } return x; } @@ -436,12 +436,12 @@ impl Printer { if self.top == self.bottom { self.scan_stack_empty = true; } else { - self.bottom += 1us; self.bottom %= self.buf_len; + self.bottom += 1; self.bottom %= self.buf_len; } return x; } pub fn advance_right(&mut self) { - self.right += 1us; + self.right += 1; self.right %= self.buf_len; assert!((self.right != self.left)); } @@ -471,7 +471,7 @@ impl Printer { break; } - self.left += 1us; + self.left += 1; self.left %= self.buf_len; left_size = self.size[self.left]; @@ -520,7 +520,7 @@ impl Printer { pub fn get_top(&mut self) -> PrintStackElem { let print_stack = &mut self.print_stack; let n = print_stack.len(); - if n != 0us { + if n != 0 { (*print_stack)[n - 1] } else { PrintStackElem { @@ -565,7 +565,7 @@ impl Printer { Token::End => { debug!("print End -> pop End"); let print_stack = &mut self.print_stack; - assert!((print_stack.len() != 0us)); + assert!((print_stack.len() != 0)); print_stack.pop().unwrap(); Ok(()) } @@ -667,11 +667,11 @@ pub fn spaces(p: &mut Printer, n: usize) -> old_io::IoResult<()> { } pub fn zerobreak(p: &mut Printer) -> old_io::IoResult<()> { - spaces(p, 0us) + spaces(p, 0) } pub fn space(p: &mut Printer) -> old_io::IoResult<()> { - spaces(p, 1us) + spaces(p, 1) } pub fn hardbreak(p: &mut Printer) -> old_io::IoResult<()> { diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 5367ccc1357..e6d895a49fc 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -92,10 +92,10 @@ pub fn rust_printer_annotated<'a>(writer: Box<old_io::Writer+'static>, } #[allow(non_upper_case_globals)] -pub const indent_unit: usize = 4us; +pub const indent_unit: usize = 4; #[allow(non_upper_case_globals)] -pub const default_columns: usize = 78us; +pub const default_columns: usize = 78; /// Requires you to pass an input filename and reader so that /// it can scan the input text for comments and literals to @@ -377,7 +377,7 @@ pub fn block_to_string(blk: &ast::Block) -> String { // containing cbox, will be closed by print-block at } try!(s.cbox(indent_unit)); // head-ibox, will be closed by print-block after { - try!(s.ibox(0us)); + try!(s.ibox(0)); s.print_block(blk) }) } @@ -516,7 +516,7 @@ impl<'a> State<'a> { pub fn bclose_maybe_open (&mut self, span: codemap::Span, indented: usize, close_box: bool) -> IoResult<()> { try!(self.maybe_print_comment(span.hi)); - try!(self.break_offset_if_not_bol(1us, -(indented as isize))); + try!(self.break_offset_if_not_bol(1, -(indented as isize))); try!(word(&mut self.s, "}")); if close_box { try!(self.end()); // close the outer-box @@ -591,9 +591,9 @@ impl<'a> State<'a> { pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> IoResult<()> where F: FnMut(&mut State, &T) -> IoResult<()>, { - try!(self.rbox(0us, b)); + try!(self.rbox(0, b)); let mut first = true; - for elt in elts.iter() { + for elt in elts { if first { first = false; } else { try!(self.word_space(",")); } try!(op(self, elt)); } @@ -609,13 +609,13 @@ impl<'a> State<'a> { F: FnMut(&mut State, &T) -> IoResult<()>, G: FnMut(&T) -> codemap::Span, { - try!(self.rbox(0us, b)); + try!(self.rbox(0, b)); let len = elts.len(); - let mut i = 0us; - for elt in elts.iter() { + let mut i = 0; + for elt in elts { try!(self.maybe_print_comment(get_span(elt).hi)); try!(op(self, elt)); - i += 1us; + i += 1; if i < len { try!(word(&mut self.s, ",")); try!(self.maybe_print_trailing_comment(get_span(elt), @@ -634,7 +634,7 @@ impl<'a> State<'a> { pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) -> IoResult<()> { try!(self.print_inner_attributes(attrs)); - for item in _mod.items.iter() { + for item in &_mod.items { try!(self.print_item(&**item)); } Ok(()) @@ -643,7 +643,7 @@ impl<'a> State<'a> { pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) -> IoResult<()> { try!(self.print_inner_attributes(attrs)); - for item in nmod.items.iter() { + for item in &nmod.items { try!(self.print_foreign_item(&**item)); } Ok(()) @@ -651,8 +651,8 @@ impl<'a> State<'a> { pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> IoResult<()> { - for l in lifetime.iter() { - try!(self.print_lifetime(l)); + if let Some(l) = *lifetime { + try!(self.print_lifetime(&l)); try!(self.nbsp()); } Ok(()) @@ -660,7 +660,7 @@ impl<'a> State<'a> { pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> { try!(self.maybe_print_comment(ty.span.lo)); - try!(self.ibox(0us)); + try!(self.ibox(0)); match ty.node { ast::TyVec(ref ty) => { try!(word(&mut self.s, "[")); @@ -799,7 +799,7 @@ impl<'a> State<'a> { ast::ItemExternCrate(ref optional_path) => { try!(self.head(&visibility_qualified(item.vis, "extern crate")[])); - for &(ref p, style) in optional_path.iter() { + if let Some((ref p, style)) = *optional_path { try!(self.print_string(p.get(), style)); try!(space(&mut self.s)); try!(word(&mut self.s, "as")); @@ -880,7 +880,7 @@ impl<'a> State<'a> { } ast::ItemTy(ref ty, ref params) => { try!(self.ibox(indent_unit)); - try!(self.ibox(0us)); + try!(self.ibox(0)); try!(self.word_nbsp(&visibility_qualified(item.vis, "type")[])); try!(self.print_ident(item.ident)); try!(self.print_generics(params)); @@ -945,7 +945,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.bopen()); try!(self.print_inner_attributes(&item.attrs[])); - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { ast::MethodImplItem(ref meth) => { try!(self.print_method(&**meth)); @@ -966,7 +966,7 @@ impl<'a> State<'a> { try!(self.print_generics(generics)); let bounds: Vec<_> = bounds.iter().map(|b| b.clone()).collect(); let mut real_bounds = Vec::with_capacity(bounds.len()); - for b in bounds.into_iter() { + for b in bounds { if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = b { try!(space(&mut self.s)); try!(self.word_space("for ?")); @@ -979,7 +979,7 @@ impl<'a> State<'a> { try!(self.print_where_clause(generics)); try!(word(&mut self.s, " ")); try!(self.bopen()); - for meth in methods.iter() { + for meth in methods { try!(self.print_trait_method(meth)); } try!(self.bclose(item.span)); @@ -1010,7 +1010,7 @@ impl<'a> State<'a> { if !t.bound_lifetimes.is_empty() { try!(word(&mut self.s, "for<")); let mut comma = false; - for lifetime_def in t.bound_lifetimes.iter() { + for lifetime_def in &t.bound_lifetimes { if comma { try!(self.word_space(",")) } @@ -1039,7 +1039,7 @@ impl<'a> State<'a> { variants: &[P<ast::Variant>], span: codemap::Span) -> IoResult<()> { try!(self.bopen()); - for v in variants.iter() { + for v in variants { try!(self.space_if_not_bol()); try!(self.maybe_print_comment(v.span.lo)); try!(self.print_outer_attributes(&v.node.attrs[])); @@ -1094,7 +1094,7 @@ impl<'a> State<'a> { try!(self.bopen()); try!(self.hardbreak_if_not_bol()); - for field in struct_def.fields.iter() { + for field in &struct_def.fields { match field.node.kind { ast::UnnamedField(..) => panic!("unexpected unnamed field"), ast::NamedField(ident, visibility) => { @@ -1141,7 +1141,7 @@ impl<'a> State<'a> { }, ast::TtSequence(_, ref seq) => { try!(word(&mut self.s, "$(")); - for tt_elt in seq.tts.iter() { + for tt_elt in &seq.tts { try!(self.print_tt(tt_elt)); } try!(word(&mut self.s, ")")); @@ -1277,8 +1277,8 @@ impl<'a> State<'a> { pub fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> IoResult<()> { - let mut count = 0us; - for attr in attrs.iter() { + let mut count = 0; + for attr in attrs { match attr.node.style { ast::AttrOuter => { try!(self.print_attribute(attr)); @@ -1295,8 +1295,8 @@ impl<'a> State<'a> { pub fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> IoResult<()> { - let mut count = 0us; - for attr in attrs.iter() { + let mut count = 0; + for attr in attrs { match attr.node.style { ast::AttrInner => { try!(self.print_attribute(attr)); @@ -1395,7 +1395,7 @@ impl<'a> State<'a> { try!(self.print_inner_attributes(attrs)); - for st in blk.stmts.iter() { + for st in &blk.stmts { try!(self.print_stmt(&**st)); } match blk.expr { @@ -1416,8 +1416,8 @@ impl<'a> State<'a> { match _else.node { // "another else-if" ast::ExprIf(ref i, ref then, ref e) => { - try!(self.cbox(indent_unit - 1us)); - try!(self.ibox(0us)); + try!(self.cbox(indent_unit - 1)); + try!(self.ibox(0)); try!(word(&mut self.s, " else if ")); try!(self.print_expr(&**i)); try!(space(&mut self.s)); @@ -1426,8 +1426,8 @@ impl<'a> State<'a> { } // "another else-if-let" ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => { - try!(self.cbox(indent_unit - 1us)); - try!(self.ibox(0us)); + try!(self.cbox(indent_unit - 1)); + try!(self.ibox(0)); try!(word(&mut self.s, " else if let ")); try!(self.print_pat(&**pat)); try!(space(&mut self.s)); @@ -1439,8 +1439,8 @@ impl<'a> State<'a> { } // "final else" ast::ExprBlock(ref b) => { - try!(self.cbox(indent_unit - 1us)); - try!(self.ibox(0us)); + try!(self.cbox(indent_unit - 1)); + try!(self.ibox(0)); try!(word(&mut self.s, " else ")); self.print_block(&**b) } @@ -1606,7 +1606,7 @@ impl<'a> State<'a> { try!(self.print_expr(&*args[0])); try!(word(&mut self.s, ".")); try!(self.print_ident(ident.node)); - if tys.len() > 0us { + if tys.len() > 0 { try!(word(&mut self.s, "::<")); try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&**ty))); @@ -1691,8 +1691,8 @@ impl<'a> State<'a> { try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e))); } ast::ExprWhile(ref test, ref blk, opt_ident) => { - for ident in opt_ident.iter() { - try!(self.print_ident(*ident)); + if let Some(ident) = opt_ident { + try!(self.print_ident(ident)); try!(self.word_space(":")); } try!(self.head("while")); @@ -1701,8 +1701,8 @@ impl<'a> State<'a> { try!(self.print_block(&**blk)); } ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => { - for ident in opt_ident.iter() { - try!(self.print_ident(*ident)); + if let Some(ident) = opt_ident { + try!(self.print_ident(ident)); try!(self.word_space(":")); } try!(self.head("while let")); @@ -1714,8 +1714,8 @@ impl<'a> State<'a> { try!(self.print_block(&**blk)); } ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => { - for ident in opt_ident.iter() { - try!(self.print_ident(*ident)); + if let Some(ident) = opt_ident { + try!(self.print_ident(ident)); try!(self.word_space(":")); } try!(self.head("for")); @@ -1727,8 +1727,8 @@ impl<'a> State<'a> { try!(self.print_block(&**blk)); } ast::ExprLoop(ref blk, opt_ident) => { - for ident in opt_ident.iter() { - try!(self.print_ident(*ident)); + if let Some(ident) = opt_ident { + try!(self.print_ident(ident)); try!(self.word_space(":")); } try!(self.head("loop")); @@ -1742,7 +1742,7 @@ impl<'a> State<'a> { try!(self.print_expr(&**expr)); try!(space(&mut self.s)); try!(self.bopen()); - for arm in arms.iter() { + for arm in arms { try!(self.print_arm(arm)); } try!(self.bclose_(expr.span, indent_unit)); @@ -1777,7 +1777,7 @@ impl<'a> State<'a> { // containing cbox, will be closed by print-block at } try!(self.cbox(indent_unit)); // head-box, will be closed by print-block after { - try!(self.ibox(0us)); + try!(self.ibox(0)); try!(self.print_block(&**blk)); } ast::ExprAssign(ref lhs, ref rhs) => { @@ -1825,16 +1825,16 @@ impl<'a> State<'a> { ast::ExprBreak(opt_ident) => { try!(word(&mut self.s, "break")); try!(space(&mut self.s)); - for ident in opt_ident.iter() { - try!(self.print_ident(*ident)); + if let Some(ident) = opt_ident { + try!(self.print_ident(ident)); try!(space(&mut self.s)); } } ast::ExprAgain(opt_ident) => { try!(word(&mut self.s, "continue")); try!(space(&mut self.s)); - for ident in opt_ident.iter() { - try!(self.print_ident(*ident)); + if let Some(ident) = opt_ident { + try!(self.print_ident(ident)); try!(space(&mut self.s)) } } @@ -1991,7 +1991,7 @@ impl<'a> State<'a> { } let mut first = true; - for segment in path.segments.iter() { + for segment in &path.segments { if first { first = false } else { @@ -2040,7 +2040,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "<")); let mut comma = false; - for lifetime in data.lifetimes.iter() { + for lifetime in &data.lifetimes { if comma { try!(self.word_space(",")) } @@ -2059,7 +2059,7 @@ impl<'a> State<'a> { comma = true; } - for binding in data.bindings.iter() { + for binding in &*data.bindings { if comma { try!(self.word_space(",")) } @@ -2154,7 +2154,7 @@ impl<'a> State<'a> { }, |f| f.node.pat.span)); if etc { - if fields.len() != 0us { try!(self.word_space(",")); } + if fields.len() != 0 { try!(self.word_space(",")); } try!(word(&mut self.s, "..")); } try!(space(&mut self.s)); @@ -2193,7 +2193,7 @@ impl<'a> State<'a> { try!(self.commasep(Inconsistent, &before[], |s, p| s.print_pat(&**p))); - for p in slice.iter() { + if let Some(ref p) = *slice { if !before.is_empty() { try!(self.word_space(",")); } try!(self.print_pat(&**p)); match **p { @@ -2221,10 +2221,10 @@ impl<'a> State<'a> { try!(space(&mut self.s)); } try!(self.cbox(indent_unit)); - try!(self.ibox(0us)); + try!(self.ibox(0)); try!(self.print_outer_attributes(&arm.attrs[])); let mut first = true; - for p in arm.pats.iter() { + for p in &arm.pats { if first { first = false; } else { @@ -2307,9 +2307,9 @@ impl<'a> State<'a> { -> IoResult<()> { // It is unfortunate to duplicate the commasep logic, but we want the // self type and the args all in the same box. - try!(self.rbox(0us, Inconsistent)); + try!(self.rbox(0, Inconsistent)); let mut first = true; - for &explicit_self in opt_explicit_self.iter() { + if let Some(explicit_self) = opt_explicit_self { let m = match explicit_self { &ast::SelfStatic => ast::MutImmutable, _ => match decl.inputs[0].pat.node { @@ -2327,7 +2327,7 @@ impl<'a> State<'a> { &decl.inputs[1..] }; - for arg in args.iter() { + for arg in args { if first { first = false; } else { try!(self.word_space(",")); } try!(self.print_arg(arg)); } @@ -2397,7 +2397,7 @@ impl<'a> State<'a> { if !bounds.is_empty() { try!(word(&mut self.s, prefix)); let mut first = true; - for bound in bounds.iter() { + for bound in bounds { try!(self.nbsp()); if first { first = false; @@ -2437,7 +2437,7 @@ impl<'a> State<'a> { { try!(self.print_lifetime(&lifetime.lifetime)); let mut sep = ":"; - for v in lifetime.bounds.iter() { + for v in &lifetime.bounds { try!(word(&mut self.s, sep)); try!(self.print_lifetime(v)); sep = "+"; @@ -2457,7 +2457,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "<")); let mut ints = Vec::new(); - for i in 0us..total { + for i in 0..total { ints.push(i); } @@ -2707,7 +2707,7 @@ impl<'a> State<'a> { if span.hi < (*cmnt).pos && (*cmnt).pos < next && span_line.line == comment_line.line { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1us; + self.cur_cmnt_and_lit.cur_cmnt += 1; } } _ => () @@ -2725,7 +2725,7 @@ impl<'a> State<'a> { match self.next_comment() { Some(ref cmnt) => { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1us; + self.cur_cmnt_and_lit.cur_cmnt += 1; } _ => break } @@ -2792,7 +2792,7 @@ impl<'a> State<'a> { } ast::LitBinary(ref v) => { let mut escaped: String = String::new(); - for &ch in v.iter() { + for &ch in &**v { ascii::escape_default(ch as u8, |ch| escaped.push(ch as char)); } @@ -2807,7 +2807,7 @@ impl<'a> State<'a> { while self.cur_cmnt_and_lit.cur_lit < lits.len() { let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone(); if ltrl.pos > pos { return None; } - self.cur_cmnt_and_lit.cur_lit += 1us; + self.cur_cmnt_and_lit.cur_lit += 1; if ltrl.pos == pos { return Some(ltrl); } } None @@ -2822,7 +2822,7 @@ impl<'a> State<'a> { Some(ref cmnt) => { if (*cmnt).pos < pos { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1us; + self.cur_cmnt_and_lit.cur_cmnt += 1; } else { break; } } _ => break @@ -2835,14 +2835,14 @@ impl<'a> State<'a> { cmnt: &comments::Comment) -> IoResult<()> { match cmnt.style { comments::Mixed => { - assert_eq!(cmnt.lines.len(), 1us); + assert_eq!(cmnt.lines.len(), 1); try!(zerobreak(&mut self.s)); try!(word(&mut self.s, &cmnt.lines[0][])); zerobreak(&mut self.s) } comments::Isolated => { try!(self.hardbreak_if_not_bol()); - for line in cmnt.lines.iter() { + for line in &cmnt.lines { // Don't print empty lines because they will end up as trailing // whitespace if !line.is_empty() { @@ -2854,12 +2854,12 @@ impl<'a> State<'a> { } comments::Trailing => { try!(word(&mut self.s, " ")); - if cmnt.lines.len() == 1us { + if cmnt.lines.len() == 1 { try!(word(&mut self.s, &cmnt.lines[0][])); hardbreak(&mut self.s) } else { - try!(self.ibox(0us)); - for line in cmnt.lines.iter() { + try!(self.ibox(0)); + for line in &cmnt.lines { if !line.is_empty() { try!(word(&mut self.s, &line[])); } diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index a7679adca2e..61ce664d2c7 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -356,8 +356,8 @@ fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { let tparm_cnt = generics.ty_params.len(); // NB: inadequate check, but we're running // well before resolve, can't get too deep. - input_cnt == 1us - && no_output && tparm_cnt == 0us + input_cnt == 1 + && no_output && tparm_cnt == 0 } _ => false } diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 1b35b1b04a3..51144267519 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -40,7 +40,7 @@ impl<T: Eq + Hash<Hasher> + Clone + 'static> Interner<T> { pub fn prefill(init: &[T]) -> Interner<T> { let rv = Interner::new(); - for v in init.iter() { + for v in init { rv.intern((*v).clone()); } rv @@ -158,7 +158,7 @@ impl StrInterner { pub fn prefill(init: &[&str]) -> StrInterner { let rv = StrInterner::new(); - for &v in init.iter() { rv.intern(v); } + for &v in init { rv.intern(v); } rv } diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index 12f871b2782..a6c92c03743 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -38,7 +38,7 @@ impl<T> FromIterator<T> for SmallVector<T> { } impl<T> Extend<T> for SmallVector<T> { - fn extend<I: Iterator<Item=T>>(&mut self, mut iter: I) { + fn extend<I: Iterator<Item=T>>(&mut self, iter: I) { for val in iter { self.push(val); } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index eb906788aa7..bd84306fe17 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -159,13 +159,13 @@ pub fn walk_inlined_item<'v,V>(visitor: &mut V, item: &'v InlinedItem) pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate) { visitor.visit_mod(&krate.module, krate.span, CRATE_NODE_ID); - for attr in krate.attrs.iter() { + for attr in &krate.attrs { visitor.visit_attribute(attr); } } pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod) { - for item in module.items.iter() { + for item in &module.items { visitor.visit_item(&**item) } } @@ -179,7 +179,7 @@ pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local) { pub fn walk_lifetime_def<'v, V: Visitor<'v>>(visitor: &mut V, lifetime_def: &'v LifetimeDef) { visitor.visit_name(lifetime_def.lifetime.span, lifetime_def.lifetime.name); - for bound in lifetime_def.bounds.iter() { + for bound in &lifetime_def.bounds { visitor.visit_lifetime_bound(bound); } } @@ -239,7 +239,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { visitor.visit_path(path, item.id); } ViewPathList(ref prefix, ref list) => { - for id in list.iter() { + for id in list { match id.node { PathListIdent { name, .. } => { visitor.visit_ident(id.span, name); @@ -270,7 +270,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { visitor.visit_mod(module, item.span, item.id) } ItemForeignMod(ref foreign_module) => { - for foreign_item in foreign_module.items.iter() { + for foreign_item in &foreign_module.items { visitor.visit_foreign_item(&**foreign_item) } } @@ -293,7 +293,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { None => () } visitor.visit_ty(&**typ); - for impl_item in impl_items.iter() { + for impl_item in impl_items { match *impl_item { MethodImplItem(ref method) => { walk_method_helper(visitor, &**method) @@ -315,13 +315,13 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { ItemTrait(_, ref generics, ref bounds, ref methods) => { visitor.visit_generics(generics); walk_ty_param_bounds_helper(visitor, bounds); - for method in methods.iter() { + for method in methods { visitor.visit_trait_item(method) } } ItemMac(ref mac) => visitor.visit_mac(mac), } - for attr in item.attrs.iter() { + for attr in &item.attrs { visitor.visit_attribute(attr); } } @@ -329,7 +329,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { pub fn walk_enum_def<'v, V: Visitor<'v>>(visitor: &mut V, enum_definition: &'v EnumDef, generics: &'v Generics) { - for variant in enum_definition.variants.iter() { + for variant in &enum_definition.variants { visitor.visit_variant(&**variant, generics); } } @@ -341,7 +341,7 @@ pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V, match variant.node.kind { TupleVariantKind(ref variant_arguments) => { - for variant_argument in variant_arguments.iter() { + for variant_argument in variant_arguments { visitor.visit_ty(&*variant_argument.ty) } } @@ -356,7 +356,7 @@ pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V, Some(ref expr) => visitor.visit_expr(&**expr), None => () } - for attr in variant.node.attrs.iter() { + for attr in &variant.node.attrs { visitor.visit_attribute(attr); } } @@ -385,12 +385,12 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty) { visitor.visit_ty(&*mutable_type.ty) } TyTup(ref tuple_element_types) => { - for tuple_element_type in tuple_element_types.iter() { + for tuple_element_type in tuple_element_types { visitor.visit_ty(&**tuple_element_type) } } TyBareFn(ref function_declaration) => { - for argument in function_declaration.decl.inputs.iter() { + for argument in &function_declaration.decl.inputs { visitor.visit_ty(&*argument.ty) } walk_fn_ret_ty(visitor, &function_declaration.decl.output); @@ -422,13 +422,13 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty) { pub fn walk_lifetime_decls_helper<'v, V: Visitor<'v>>(visitor: &mut V, lifetimes: &'v Vec<LifetimeDef>) { - for l in lifetimes.iter() { + for l in lifetimes { visitor.visit_lifetime_def(l); } } pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path) { - for segment in path.segments.iter() { + for segment in &path.segments { visitor.visit_path_segment(path.span, segment); } } @@ -453,21 +453,21 @@ pub fn walk_path_parameters<'v, V: Visitor<'v>>(visitor: &mut V, path_parameters: &'v PathParameters) { match *path_parameters { ast::AngleBracketedParameters(ref data) => { - for typ in data.types.iter() { + for typ in &*data.types { visitor.visit_ty(&**typ); } - for lifetime in data.lifetimes.iter() { + for lifetime in &data.lifetimes { visitor.visit_lifetime_ref(lifetime); } - for binding in data.bindings.iter() { + for binding in &*data.bindings { visitor.visit_assoc_type_binding(&**binding); } } ast::ParenthesizedParameters(ref data) => { - for typ in data.inputs.iter() { + for typ in &data.inputs { visitor.visit_ty(&**typ); } - for typ in data.output.iter() { + if let Some(ref typ) = data.output { visitor.visit_ty(&**typ); } } @@ -484,20 +484,20 @@ pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) { match pattern.node { PatEnum(ref path, ref children) => { visitor.visit_path(path, pattern.id); - for children in children.iter() { - for child in children.iter() { - visitor.visit_pat(&**child) + if let Some(ref children) = *children { + for child in children { + visitor.visit_pat(&*child) } } } PatStruct(ref path, ref fields, _) => { visitor.visit_path(path, pattern.id); - for field in fields.iter() { + for field in fields { visitor.visit_pat(&*field.node.pat) } } PatTup(ref tuple_elements) => { - for tuple_element in tuple_elements.iter() { + for tuple_element in tuple_elements { visitor.visit_pat(&**tuple_element) } } @@ -519,13 +519,13 @@ pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) { } PatWild(_) => (), PatVec(ref prepattern, ref slice_pattern, ref postpatterns) => { - for prepattern in prepattern.iter() { + for prepattern in prepattern { visitor.visit_pat(&**prepattern) } - for slice_pattern in slice_pattern.iter() { + if let Some(ref slice_pattern) = *slice_pattern { visitor.visit_pat(&**slice_pattern) } - for postpattern in postpatterns.iter() { + for postpattern in postpatterns { visitor.visit_pat(&**postpattern) } } @@ -545,14 +545,14 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, ForeignItemStatic(ref typ, _) => visitor.visit_ty(&**typ), } - for attr in foreign_item.attrs.iter() { + for attr in &foreign_item.attrs { visitor.visit_attribute(attr); } } pub fn walk_ty_param_bounds_helper<'v, V: Visitor<'v>>(visitor: &mut V, bounds: &'v OwnedSlice<TyParamBound>) { - for bound in bounds.iter() { + for bound in &**bounds { visitor.visit_ty_param_bound(bound) } } @@ -576,11 +576,11 @@ pub fn walk_ty_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v TyParam) { } pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) { - for type_parameter in generics.ty_params.iter() { + for type_parameter in &*generics.ty_params { walk_ty_param(visitor, type_parameter); } walk_lifetime_decls_helper(visitor, &generics.lifetimes); - for predicate in generics.where_clause.predicates.iter() { + for predicate in &generics.where_clause.predicates { match predicate { &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bounded_ty, ref bounds, @@ -593,7 +593,7 @@ pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics ..}) => { visitor.visit_lifetime_ref(lifetime); - for bound in bounds.iter() { + for bound in bounds { visitor.visit_lifetime_ref(bound); } } @@ -615,7 +615,7 @@ pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FunctionR } pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl) { - for argument in function_declaration.inputs.iter() { + for argument in &function_declaration.inputs { visitor.visit_pat(&*argument.pat); visitor.visit_ty(&*argument.ty) } @@ -635,7 +635,7 @@ pub fn walk_method_helper<'v, V: Visitor<'v>>(visitor: &mut V, method: &'v Metho &**body, method.span, method.id); - for attr in method.attrs.iter() { + for attr in &method.attrs { visitor.visit_attribute(attr); } @@ -673,12 +673,12 @@ pub fn walk_fn<'v, V: Visitor<'v>>(visitor: &mut V, pub fn walk_ty_method<'v, V: Visitor<'v>>(visitor: &mut V, method_type: &'v TypeMethod) { visitor.visit_ident(method_type.span, method_type.ident); visitor.visit_explicit_self(&method_type.explicit_self); - for argument_type in method_type.decl.inputs.iter() { + for argument_type in &method_type.decl.inputs { visitor.visit_ty(&*argument_type.ty) } visitor.visit_generics(&method_type.generics); walk_fn_ret_ty(visitor, &method_type.decl.output); - for attr in method_type.attrs.iter() { + for attr in &method_type.attrs { visitor.visit_attribute(attr); } } @@ -695,7 +695,7 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_method: &'v Tr pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V, struct_definition: &'v StructDef) { - for field in struct_definition.fields.iter() { + for field in &struct_definition.fields { visitor.visit_struct_field(field) } } @@ -708,13 +708,13 @@ pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, visitor.visit_ty(&*struct_field.node.ty); - for attr in struct_field.node.attrs.iter() { + for attr in &struct_field.node.attrs { visitor.visit_attribute(attr); } } pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block) { - for statement in block.stmts.iter() { + for statement in &block.stmts { visitor.visit_stmt(&**statement) } walk_expr_opt(visitor, &block.expr) @@ -746,7 +746,7 @@ pub fn walk_expr_opt<'v, V: Visitor<'v>>(visitor: &mut V, } pub fn walk_exprs<'v, V: Visitor<'v>>(visitor: &mut V, expressions: &'v [P<Expr>]) { - for expression in expressions.iter() { + for expression in expressions { visitor.visit_expr(&**expression) } } @@ -770,25 +770,25 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { } ExprStruct(ref path, ref fields, ref optional_base) => { visitor.visit_path(path, expression.id); - for field in fields.iter() { + for field in fields { visitor.visit_expr(&*field.expr) } walk_expr_opt(visitor, optional_base) } ExprTup(ref subexpressions) => { - for subexpression in subexpressions.iter() { + for subexpression in subexpressions { visitor.visit_expr(&**subexpression) } } ExprCall(ref callee_expression, ref arguments) => { - for argument in arguments.iter() { + for argument in arguments { visitor.visit_expr(&**argument) } visitor.visit_expr(&**callee_expression) } ExprMethodCall(_, ref types, ref arguments) => { walk_exprs(visitor, arguments.as_slice()); - for typ in types.iter() { + for typ in types { visitor.visit_ty(&**typ) } } @@ -832,7 +832,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { ExprLoop(ref block, _) => visitor.visit_block(&**block), ExprMatch(ref subexpression, ref arms, _) => { visitor.visit_expr(&**subexpression); - for arm in arms.iter() { + for arm in arms { visitor.visit_arm(arm) } } @@ -881,11 +881,11 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { visitor.visit_expr(&**subexpression) } ExprInlineAsm(ref ia) => { - for input in ia.inputs.iter() { + for input in &ia.inputs { let (_, ref input) = *input; visitor.visit_expr(&**input) } - for output in ia.outputs.iter() { + for output in &ia.outputs { let (_, ref output, _) = *output; visitor.visit_expr(&**output) } @@ -896,12 +896,12 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { } pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm) { - for pattern in arm.pats.iter() { + for pattern in &arm.pats { visitor.visit_pat(&**pattern) } walk_expr_opt(visitor, &arm.guard); visitor.visit_expr(&*arm.body); - for attr in arm.attrs.iter() { + for attr in &arm.attrs { visitor.visit_attribute(attr); } } diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index 27a46fb5a68..219c9baf4c8 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -55,13 +55,14 @@ #![feature(core)] #![feature(int_uint)] #![feature(io)] -#![feature(os)] #![feature(path)] #![feature(rustc_private)] #![feature(slicing_syntax)] #![feature(staged_api)] #![feature(std_misc)] #![feature(unicode)] +#![feature(env)] +#![cfg_attr(windows, feature(libc))] #[macro_use] extern crate log; diff --git a/src/libterm/terminfo/mod.rs b/src/libterm/terminfo/mod.rs index d126717ce68..17c1e8cdb8c 100644 --- a/src/libterm/terminfo/mod.rs +++ b/src/libterm/terminfo/mod.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::old_io::IoResult; -use std::os; +use std::env; use attr; use color; @@ -172,9 +172,9 @@ impl<T: Writer+Send> TerminfoTerminal<T> { /// Returns `None` whenever the terminal cannot be created for some /// reason. pub fn new(out: T) -> Option<Box<Terminal<T>+Send+'static>> { - let term = match os::getenv("TERM") { - Some(t) => t, - None => { + let term = match env::var_string("TERM") { + Ok(t) => t, + Err(..) => { debug!("TERM environment variable not defined"); return None; } @@ -182,7 +182,7 @@ impl<T: Writer+Send> TerminfoTerminal<T> { let entry = open(&term[]); if entry.is_err() { - if os::getenv("MSYSCON").map_or(false, |s| { + if env::var_string("MSYSCON").ok().map_or(false, |s| { "mintty.exe" == s }) { // msys terminal diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs index 0b51a976c0e..4173744ab4b 100644 --- a/src/libterm/terminfo/parm.rs +++ b/src/libterm/terminfo/parm.rs @@ -109,7 +109,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) *dst = (*src).clone(); } - for &c in cap.iter() { + for &c in cap { let cur = c as char; let mut old_state = state; match state { @@ -613,7 +613,7 @@ mod test { } let caps = ["%d", "%c", "%s", "%Pa", "%l", "%!", "%~"]; - for &cap in caps.iter() { + for &cap in &caps { let res = get_res("", cap, &[], vars); assert!(res.is_err(), "Op {} succeeded incorrectly with 0 stack entries", cap); @@ -627,7 +627,7 @@ mod test { "Op {} failed with 1 stack entry: {}", cap, res.err().unwrap()); } let caps = ["%+", "%-", "%*", "%/", "%m", "%&", "%|", "%A", "%O"]; - for &cap in caps.iter() { + for &cap in &caps { let res = expand(cap.as_bytes(), &[], vars); assert!(res.is_err(), "Binop {} succeeded incorrectly with 0 stack entries", cap); @@ -648,7 +648,7 @@ mod test { #[test] fn test_comparison_ops() { let v = [('<', [1u8, 0u8, 0u8]), ('=', [0u8, 1u8, 0u8]), ('>', [0u8, 0u8, 1u8])]; - for &(op, bs) in v.iter() { + for &(op, bs) in &v { let s = format!("%{{1}}%{{2}}%{}%d", op); let res = expand(s.as_bytes(), &[], &mut Variables::new()); assert!(res.is_ok(), res.err().unwrap()); diff --git a/src/libterm/terminfo/searcher.rs b/src/libterm/terminfo/searcher.rs index 1e84c0462d6..6ee477fc808 100644 --- a/src/libterm/terminfo/searcher.rs +++ b/src/libterm/terminfo/searcher.rs @@ -14,8 +14,7 @@ use std::old_io::File; use std::old_io::fs::PathExtensions; -use std::os::getenv; -use std::os; +use std::env; /// Return path to database entry for `term` pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> { @@ -23,21 +22,21 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> { return None; } - let homedir = os::homedir(); + let homedir = env::home_dir(); let mut dirs_to_search = Vec::new(); let first_char = term.char_at(0); // Find search directory - match getenv("TERMINFO") { - Some(dir) => dirs_to_search.push(Path::new(dir)), - None => { + match env::var_string("TERMINFO") { + Ok(dir) => dirs_to_search.push(Path::new(dir)), + Err(..) => { if homedir.is_some() { // ncurses compatibility; dirs_to_search.push(homedir.unwrap().join(".terminfo")) } - match getenv("TERMINFO_DIRS") { - Some(dirs) => for i in dirs.split(':') { + match env::var_string("TERMINFO_DIRS") { + Ok(dirs) => for i in dirs.split(':') { if i == "" { dirs_to_search.push(Path::new("/usr/share/terminfo")); } else { @@ -48,7 +47,7 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> { // According to /etc/terminfo/README, after looking at // ~/.terminfo, ncurses will search /etc/terminfo, then // /lib/terminfo, and eventually /usr/share/terminfo. - None => { + Err(..) => { dirs_to_search.push(Path::new("/etc/terminfo")); dirs_to_search.push(Path::new("/lib/terminfo")); dirs_to_search.push(Path::new("/usr/share/terminfo")); @@ -58,7 +57,7 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> { }; // Look for the terminal in all of the search directories - for p in dirs_to_search.iter() { + for p in &dirs_to_search { if p.exists() { let f = first_char.to_string(); let newp = p.join_many(&[&f[], term]); diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index f22c58c54a6..0692d7e5faa 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -16,7 +16,7 @@ //! benchmarks themselves) should be done via the `#[test]` and //! `#[bench]` attributes. //! -//! See the [Testing Guide](../guide-testing.html) for more details. +//! See the [Testing Chapter](../book/testing.html) of the book for more details. // Currently, not much of this is meant for users. It is intended to // support the simplest interface possible for representing and @@ -32,16 +32,14 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap - #![feature(asm, slicing_syntax)] #![feature(box_syntax)] #![feature(collections)] #![feature(core)] +#![feature(env)] #![feature(hash)] #![feature(int_uint)] #![feature(io)] -#![feature(os)] #![feature(path)] #![feature(rustc_private)] #![feature(staged_api)] @@ -75,7 +73,7 @@ use std::old_io::{File, ChanReader, ChanWriter}; use std::old_io; use std::iter::repeat; use std::num::{Float, Int}; -use std::os; +use std::env; use std::sync::mpsc::{channel, Sender}; use std::thread::{self, Thread}; use std::thunk::{Thunk, Invoke}; @@ -388,7 +386,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> { let mut nocapture = matches.opt_present("nocapture"); if !nocapture { - nocapture = os::getenv("RUST_TEST_NOCAPTURE").is_some(); + nocapture = env::var("RUST_TEST_NOCAPTURE").is_some(); } let color = match matches.opt_str("color").as_ref().map(|s| s.as_slice()) { @@ -576,7 +574,7 @@ impl<T: Writer> ConsoleTestState<T> { try!(self.write_plain("\nfailures:\n")); let mut failures = Vec::new(); let mut fail_out = String::new(); - for &(ref f, ref stdout) in self.failures.iter() { + for &(ref f, ref stdout) in &self.failures { failures.push(f.name.to_string()); if stdout.len() > 0 { fail_out.push_str(format!("---- {} stdout ----\n\t", @@ -593,7 +591,7 @@ impl<T: Writer> ConsoleTestState<T> { try!(self.write_plain("\nfailures:\n")); failures.sort(); - for name in failures.iter() { + for name in &failures { try!(self.write_plain(format!(" {}\n", name.as_slice()).as_slice())); } @@ -652,7 +650,7 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn> ) -> old_io: TrMetrics(mm) => { let tname = test.name.as_slice(); let MetricMap(mm) = mm; - for (k,v) in mm.iter() { + for (k,v) in &mm { st.metrics .insert_metric(format!("{}.{}", tname, @@ -806,7 +804,7 @@ fn run_tests<F>(opts: &TestOpts, // All benchmarks run at the end, in serial. // (this includes metric fns) - for b in filtered_benchs_and_metrics.into_iter() { + for b in filtered_benchs_and_metrics { try!(callback(TeWait(b.desc.clone(), b.testfn.padding()))); run_test(opts, !opts.run_benchmarks, b, tx.clone()); let (test, result, stdout) = rx.recv().unwrap(); @@ -817,15 +815,15 @@ fn run_tests<F>(opts: &TestOpts, fn get_concurrency() -> uint { use std::rt; - match os::getenv("RUST_TEST_TASKS") { - Some(s) => { + match env::var_string("RUST_TEST_TASKS") { + Ok(s) => { let opt_n: Option<uint> = s.parse().ok(); match opt_n { Some(n) if n > 0 => n, _ => panic!("RUST_TEST_TASKS is `{}`, should be a positive integer.", s) } } - None => { + Err(..) => { rt::default_sched_threads() } } @@ -1060,7 +1058,7 @@ impl Bencher { let loop_run = Duration::span(|| { - for p in samples.iter_mut() { + for p in &mut *samples { self.bench_n(n, |x| f(x)); *p = self.ns_per_iter() as f64; }; @@ -1068,7 +1066,7 @@ impl Bencher { stats::winsorize(samples, 5.0); summ = Some(stats::Summary::new(samples)); - for p in samples.iter_mut() { + for p in &mut *samples { self.bench_n(5 * n, |x| f(x)); *p = self.ns_per_iter() as f64; }; @@ -1299,7 +1297,7 @@ mod tests { { fn testfn() { } let mut tests = Vec::new(); - for name in names.iter() { + for name in &names { let test = TestDescAndFn { desc: TestDesc { name: DynTestName((*name).clone()), diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 237acbd7b65..ebd86dbf61c 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -167,7 +167,7 @@ impl<T: Float + FromPrimitive> Stats<T> for [T] { fn sum(&self) -> T { let mut partials = vec![]; - for &x in self.iter() { + for &x in self { let mut x = x; let mut j = 0; // This inner loop applies `hi`/`lo` summation to each @@ -223,7 +223,7 @@ impl<T: Float + FromPrimitive> Stats<T> for [T] { } else { let mean = self.mean(); let mut v: T = Float::zero(); - for s in self.iter() { + for s in self { let x = *s - mean; v = v + x*x; } @@ -321,7 +321,7 @@ pub fn winsorize<T: Float + FromPrimitive>(samples: &mut [T], pct: T) { let lo = percentile_of_sorted(tmp.as_slice(), pct); let hundred: T = FromPrimitive::from_uint(100).unwrap(); let hi = percentile_of_sorted(tmp.as_slice(), hundred-pct); - for samp in samples.iter_mut() { + for samp in samples { if *samp > hi { *samp = hi } else if *samp < lo { @@ -332,7 +332,7 @@ pub fn winsorize<T: Float + FromPrimitive>(samples: &mut [T], pct: T) { /// Returns a HashMap with the number of occurrences of every element in the /// sequence that the iterator exposes. -pub fn freq_count<T, U>(mut iter: T) -> hash_map::HashMap<U, uint> +pub fn freq_count<T, U>(iter: T) -> hash_map::HashMap<U, uint> where T: Iterator<Item=U>, U: Eq + Clone + Hash<Hasher> { let mut map: hash_map::HashMap<U,uint> = hash_map::HashMap::new(); diff --git a/src/libunicode/normalize.rs b/src/libunicode/normalize.rs index c6f86ccd9d4..e35634ac465 100644 --- a/src/libunicode/normalize.rs +++ b/src/libunicode/normalize.rs @@ -52,7 +52,7 @@ fn d<F>(c: char, i: &mut F, k: bool) where F: FnMut(char) { // First check the canonical decompositions match bsearch_table(c, canonical_table) { Some(canon) => { - for x in canon.iter() { + for x in canon { d(*x, i, k); } return; @@ -66,7 +66,7 @@ fn d<F>(c: char, i: &mut F, k: bool) where F: FnMut(char) { // Then check the compatibility decompositions match bsearch_table(c, compatibility_table) { Some(compat) => { - for x in compat.iter() { + for x in compat { d(*x, i, k); } return; diff --git a/src/libunicode/u_str.rs b/src/libunicode/u_str.rs index 9a757c0c980..0e3aacbc09a 100644 --- a/src/libunicode/u_str.rs +++ b/src/libunicode/u_str.rs @@ -32,7 +32,7 @@ use tables::grapheme::GraphemeCat; /// An iterator over the words of a string, separated by a sequence of whitespace #[stable(feature = "rust1", since = "1.0.0")] pub struct Words<'a> { - inner: Filter<&'a str, Split<'a, fn(char) -> bool>, fn(&&str) -> bool>, + inner: Filter<Split<'a, fn(char) -> bool>, fn(&&str) -> bool>, } /// Methods for Unicode string slices diff --git a/src/llvm b/src/llvm -Subproject b820135911e17c7a46b901db56baa48e5155bf4 +Subproject 2d54c4f559b1acbfe1867950c3a25bfb2f76b69 diff --git a/src/rt/rust_builtin.c b/src/rt/rust_builtin.c index 03cd3fd6b88..382cbf0d5d1 100644 --- a/src/rt/rust_builtin.c +++ b/src/rt/rust_builtin.c @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -47,7 +47,7 @@ extern char **environ; #endif #endif -#if defined(__FreeBSD__) || defined(__linux__) || defined(__ANDROID__) || defined(__DragonFly__) +#if defined(__FreeBSD__) || defined(__linux__) || defined(__ANDROID__) || defined(__DragonFly__) || defined(__OpenBSD__) extern char **environ; #endif @@ -199,6 +199,56 @@ rust_unset_sigprocmask() { int *__dfly_error(void) { return __error(); } #endif +#if defined(__OpenBSD__) +#include <sys/param.h> +#include <sys/sysctl.h> +#include <limits.h> + +const char * rust_load_self() { + static char *self = NULL; + + if (self == NULL) { + int mib[4]; + char **argv = NULL; + size_t argv_len; + + /* initialize mib */ + mib[0] = CTL_KERN; + mib[1] = KERN_PROC_ARGS; + mib[2] = getpid(); + mib[3] = KERN_PROC_ARGV; + + /* request KERN_PROC_ARGV size */ + argv_len = 0; + if (sysctl(mib, 4, NULL, &argv_len, NULL, 0) == -1) + return (NULL); + + /* allocate size */ + if ((argv = malloc(argv_len)) == NULL) + return (NULL); + + /* request KERN_PROC_ARGV */ + if (sysctl(mib, 4, argv, &argv_len, NULL, 0) == -1) { + free(argv); + return (NULL); + } + + /* get realpath if possible */ + if ((argv[0] != NULL) && ((*argv[0] == '.') || (*argv[0] == '/') + || (strstr(argv[0], "/") != NULL))) + + self = realpath(argv[0], NULL); + else + self = NULL; + + /* cleanup */ + free(argv); + } + + return (self); +} +#endif + // // Local Variables: // mode: C++ diff --git a/src/rustbook/book.rs b/src/rustbook/book.rs index 2707a6346c8..e7739300790 100644 --- a/src/rustbook/book.rs +++ b/src/rustbook/book.rs @@ -49,7 +49,7 @@ impl<'a> Iterator for BookItems<'a> { let cur = self.cur_items.get(self.cur_idx).unwrap(); let mut section = "".to_string(); - for &(_, idx) in self.stack.iter() { + for &(_, idx) in &self.stack { section.push_str(&(idx + 1).to_string()[]); section.push('.'); } diff --git a/src/rustbook/build.rs b/src/rustbook/build.rs index ccb572a113a..3c9c4bdedcc 100644 --- a/src/rustbook/build.rs +++ b/src/rustbook/build.rs @@ -177,7 +177,7 @@ impl Subcommand for Build { } Err(errors) => { let n = errors.len(); - for err in errors.into_iter() { + for err in errors { term.err(&format!("error: {}", err)[]); } diff --git a/src/rustbook/test.rs b/src/rustbook/test.rs index db02481cb02..d3cb8a7316e 100644 --- a/src/rustbook/test.rs +++ b/src/rustbook/test.rs @@ -64,7 +64,7 @@ impl Subcommand for Test { } } Err(errors) => { - for err in errors.into_iter() { + for err in errors { term.err(&err[]); } return Err(box "There was an error." as Box<Error>); diff --git a/src/rustllvm/ExecutionEngineWrapper.cpp b/src/rustllvm/ExecutionEngineWrapper.cpp index d37cf9d12a5..8ca81ab3d68 100644 --- a/src/rustllvm/ExecutionEngineWrapper.cpp +++ b/src/rustllvm/ExecutionEngineWrapper.cpp @@ -82,21 +82,24 @@ extern "C" LLVMExecutionEngineRef LLVMBuildExecutionEngine( InitializeNativeTargetAsmPrinter(); InitializeNativeTargetAsmParser(); - std::unique_ptr<Module> m(unwrap(mod)); - RustJITMemoryManager *mm = unwrap(mref); - std::string error_str; TargetOptions options; options.JITEmitDebugInfo = true; options.NoFramePointerElim = true; - ExecutionEngine *ee = EngineBuilder(std::move(m)) - .setEngineKind(EngineKind::JIT) - .setErrorStr(&error_str) - .setMCJITMemoryManager(mm) - .setTargetOptions(options) - .create(); + ExecutionEngine *ee = + #if LLVM_VERSION_MINOR <= 5 + EngineBuilder(unwrap(mod)) + .setMCJITMemoryManager(unwrap(mref)) + #else + EngineBuilder(std::unique_ptr<Module>(unwrap(mod))) + .setMCJITMemoryManager(std::unique_ptr<RustJITMemoryManager>(unwrap(mref))) + #endif + .setEngineKind(EngineKind::JIT) + .setErrorStr(&error_str) + .setTargetOptions(options) + .create(); if (!ee) LLVMRustSetLastError(error_str.c_str()); diff --git a/src/rustllvm/RustWrapper.cpp b/src/rustllvm/RustWrapper.cpp index 728ff1461fc..aaf6d8df29c 100644 --- a/src/rustllvm/RustWrapper.cpp +++ b/src/rustllvm/RustWrapper.cpp @@ -228,8 +228,22 @@ extern "C" LLVMValueRef LLVMInlineAsm(LLVMTypeRef Ty, typedef DIBuilder* DIBuilderRef; +#if LLVM_VERSION_MINOR >= 6 +typedef struct LLVMOpaqueMetadata *LLVMMetadataRef; + +namespace llvm { +DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef) + +inline Metadata **unwrap(LLVMMetadataRef *Vals) { + return reinterpret_cast<Metadata**>(Vals); +} +} +#else +typedef LLVMValueRef LLVMMetadataRef; +#endif + template<typename DIT> -DIT unwrapDI(LLVMValueRef ref) { +DIT unwrapDI(LLVMMetadataRef ref) { return DIT(ref ? unwrap<MDNode>(ref) : NULL); } @@ -257,7 +271,7 @@ extern "C" void LLVMDIBuilderFinalize(DIBuilderRef Builder) { Builder->finalize(); } -extern "C" LLVMValueRef LLVMDIBuilderCreateCompileUnit( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateCompileUnit( DIBuilderRef Builder, unsigned Lang, const char* File, @@ -277,17 +291,17 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateCompileUnit( SplitName)); } -extern "C" LLVMValueRef LLVMDIBuilderCreateFile( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateFile( DIBuilderRef Builder, const char* Filename, const char* Directory) { return wrap(Builder->createFile(Filename, Directory)); } -extern "C" LLVMValueRef LLVMDIBuilderCreateSubroutineType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateSubroutineType( DIBuilderRef Builder, - LLVMValueRef File, - LLVMValueRef ParameterTypes) { + LLVMMetadataRef File, + LLVMMetadataRef ParameterTypes) { return wrap(Builder->createSubroutineType( unwrapDI<DIFile>(File), #if LLVM_VERSION_MINOR >= 6 @@ -297,22 +311,22 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateSubroutineType( #endif } -extern "C" LLVMValueRef LLVMDIBuilderCreateFunction( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateFunction( DIBuilderRef Builder, - LLVMValueRef Scope, + LLVMMetadataRef Scope, const char* Name, const char* LinkageName, - LLVMValueRef File, + LLVMMetadataRef File, unsigned LineNo, - LLVMValueRef Ty, + LLVMMetadataRef Ty, bool isLocalToUnit, bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized, LLVMValueRef Fn, - LLVMValueRef TParam, - LLVMValueRef Decl) { + LLVMMetadataRef TParam, + LLVMMetadataRef Decl) { return wrap(Builder->createFunction( unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File), LineNo, @@ -323,7 +337,7 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateFunction( unwrapDI<MDNode*>(Decl))); } -extern "C" LLVMValueRef LLVMDIBuilderCreateBasicType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateBasicType( DIBuilderRef Builder, const char* Name, uint64_t SizeInBits, @@ -334,9 +348,9 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateBasicType( AlignInBits, Encoding)); } -extern "C" LLVMValueRef LLVMDIBuilderCreatePointerType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreatePointerType( DIBuilderRef Builder, - LLVMValueRef PointeeTy, + LLVMMetadataRef PointeeTy, uint64_t SizeInBits, uint64_t AlignInBits, const char* Name) { @@ -344,19 +358,19 @@ extern "C" LLVMValueRef LLVMDIBuilderCreatePointerType( unwrapDI<DIType>(PointeeTy), SizeInBits, AlignInBits, Name)); } -extern "C" LLVMValueRef LLVMDIBuilderCreateStructType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateStructType( DIBuilderRef Builder, - LLVMValueRef Scope, + LLVMMetadataRef Scope, const char* Name, - LLVMValueRef File, + LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags, - LLVMValueRef DerivedFrom, - LLVMValueRef Elements, + LLVMMetadataRef DerivedFrom, + LLVMMetadataRef Elements, unsigned RunTimeLang, - LLVMValueRef VTableHolder, + LLVMMetadataRef VTableHolder, const char *UniqueId) { return wrap(Builder->createStructType( unwrapDI<DIDescriptor>(Scope), @@ -376,17 +390,17 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateStructType( )); } -extern "C" LLVMValueRef LLVMDIBuilderCreateMemberType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateMemberType( DIBuilderRef Builder, - LLVMValueRef Scope, + LLVMMetadataRef Scope, const char* Name, - LLVMValueRef File, + LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags, - LLVMValueRef Ty) { + LLVMMetadataRef Ty) { return wrap(Builder->createMemberType( unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo, @@ -394,10 +408,10 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateMemberType( unwrapDI<DIType>(Ty))); } -extern "C" LLVMValueRef LLVMDIBuilderCreateLexicalBlock( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock( DIBuilderRef Builder, - LLVMValueRef Scope, - LLVMValueRef File, + LLVMMetadataRef Scope, + LLVMMetadataRef File, unsigned Line, unsigned Col) { return wrap(Builder->createLexicalBlock( @@ -409,17 +423,17 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateLexicalBlock( )); } -extern "C" LLVMValueRef LLVMDIBuilderCreateStaticVariable( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateStaticVariable( DIBuilderRef Builder, - LLVMValueRef Context, + LLVMMetadataRef Context, const char* Name, const char* LinkageName, - LLVMValueRef File, + LLVMMetadataRef File, unsigned LineNo, - LLVMValueRef Ty, + LLVMMetadataRef Ty, bool isLocalToUnit, LLVMValueRef Val, - LLVMValueRef Decl = NULL) { + LLVMMetadataRef Decl = NULL) { #if LLVM_VERSION_MINOR == 6 return wrap(Builder->createGlobalVariable(unwrapDI<DIDescriptor>(Context), #else @@ -431,21 +445,42 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateStaticVariable( LineNo, unwrapDI<DIType>(Ty), isLocalToUnit, - unwrap(Val), + cast<Constant>(unwrap(Val)), unwrapDI<MDNode*>(Decl))); } -extern "C" LLVMValueRef LLVMDIBuilderCreateLocalVariable( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateVariable( DIBuilderRef Builder, unsigned Tag, - LLVMValueRef Scope, + LLVMMetadataRef Scope, const char* Name, - LLVMValueRef File, + LLVMMetadataRef File, unsigned LineNo, - LLVMValueRef Ty, + LLVMMetadataRef Ty, bool AlwaysPreserve, unsigned Flags, + int64_t* AddrOps, + unsigned AddrOpsCount, unsigned ArgNo) { +#if LLVM_VERSION_MINOR < 6 + if (AddrOpsCount > 0) { + SmallVector<llvm::Value *, 16> addr_ops; + llvm::Type *Int64Ty = Type::getInt64Ty(VMContext); + for (int i = 0; i < AddrOpsCount; ++i) + addr_ops.push_back(ConstantInt::get(Int64Ty, AddrOps[i])); + + return wrap(Builder->createComplexVariable( + Tag, + unwrapDI<DIDescriptor>(Scope), + Name, + unwrapDI<DIFile>(File), + LineNo, + unwrapDI<DIType>(Ty), + addr_ops, + ArgNo + )); + } +#endif return wrap(Builder->createLocalVariable(Tag, unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), @@ -453,66 +488,94 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateLocalVariable( unwrapDI<DIType>(Ty), AlwaysPreserve, Flags, ArgNo)); } -extern "C" LLVMValueRef LLVMDIBuilderCreateArrayType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateArrayType( DIBuilderRef Builder, uint64_t Size, uint64_t AlignInBits, - LLVMValueRef Ty, - LLVMValueRef Subscripts) { + LLVMMetadataRef Ty, + LLVMMetadataRef Subscripts) { return wrap(Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty), unwrapDI<DIArray>(Subscripts))); } -extern "C" LLVMValueRef LLVMDIBuilderCreateVectorType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateVectorType( DIBuilderRef Builder, uint64_t Size, uint64_t AlignInBits, - LLVMValueRef Ty, - LLVMValueRef Subscripts) { + LLVMMetadataRef Ty, + LLVMMetadataRef Subscripts) { return wrap(Builder->createVectorType(Size, AlignInBits, unwrapDI<DIType>(Ty), unwrapDI<DIArray>(Subscripts))); } -extern "C" LLVMValueRef LLVMDIBuilderGetOrCreateSubrange( +extern "C" LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange( DIBuilderRef Builder, int64_t Lo, int64_t Count) { return wrap(Builder->getOrCreateSubrange(Lo, Count)); } -extern "C" LLVMValueRef LLVMDIBuilderGetOrCreateArray( +extern "C" LLVMMetadataRef LLVMDIBuilderGetOrCreateArray( DIBuilderRef Builder, - LLVMValueRef* Ptr, + LLVMMetadataRef* Ptr, unsigned Count) { return wrap(Builder->getOrCreateArray( - ArrayRef<Value*>(reinterpret_cast<Value**>(Ptr), Count))); + ArrayRef<Metadata*>(unwrap(Ptr), Count))); } extern "C" LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd( DIBuilderRef Builder, LLVMValueRef Val, - LLVMValueRef VarInfo, + LLVMMetadataRef VarInfo, + int64_t* AddrOps, + unsigned AddrOpsCount, LLVMBasicBlockRef InsertAtEnd) { +#if LLVM_VERSION_MINOR >= 6 + DIExpression Expr; + if (AddrOpsCount == 0) { + Expr = Builder->createExpression(); + } else { + llvm::ArrayRef<int64_t> addr_ops(AddrOps, AddrOpsCount); + Expr = Builder->createExpression(addr_ops); + } +#endif return wrap(Builder->insertDeclare( unwrap(Val), unwrapDI<DIVariable>(VarInfo), +#if LLVM_VERSION_MINOR >= 6 + Expr, +#endif unwrap(InsertAtEnd))); } extern "C" LLVMValueRef LLVMDIBuilderInsertDeclareBefore( DIBuilderRef Builder, LLVMValueRef Val, - LLVMValueRef VarInfo, + LLVMMetadataRef VarInfo, + int64_t* AddrOps, + unsigned AddrOpsCount, LLVMValueRef InsertBefore) { +#if LLVM_VERSION_MINOR >= 6 + DIExpression Expr; + if (AddrOpsCount == 0) { + Expr = Builder->createExpression(); + } else { + llvm::ArrayRef<int64_t> addr_ops(AddrOps, AddrOpsCount); + Expr = Builder->createExpression(addr_ops); + } +#endif return wrap(Builder->insertDeclare( unwrap(Val), unwrapDI<DIVariable>(VarInfo), +#if LLVM_VERSION_MINOR >= 6 + Expr, +#endif unwrap<Instruction>(InsertBefore))); } -extern "C" LLVMValueRef LLVMDIBuilderCreateEnumerator( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateEnumerator( DIBuilderRef Builder, const char* Name, uint64_t Val) @@ -520,16 +583,16 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateEnumerator( return wrap(Builder->createEnumerator(Name, Val)); } -extern "C" LLVMValueRef LLVMDIBuilderCreateEnumerationType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateEnumerationType( DIBuilderRef Builder, - LLVMValueRef Scope, + LLVMMetadataRef Scope, const char* Name, - LLVMValueRef File, + LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint64_t AlignInBits, - LLVMValueRef Elements, - LLVMValueRef ClassType) + LLVMMetadataRef Elements, + LLVMMetadataRef ClassType) { return wrap(Builder->createEnumerationType( unwrapDI<DIDescriptor>(Scope), @@ -542,16 +605,16 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateEnumerationType( unwrapDI<DIType>(ClassType))); } -extern "C" LLVMValueRef LLVMDIBuilderCreateUnionType( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateUnionType( DIBuilderRef Builder, - LLVMValueRef Scope, + LLVMMetadataRef Scope, const char* Name, - LLVMValueRef File, + LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags, - LLVMValueRef Elements, + LLVMMetadataRef Elements, unsigned RunTimeLang, const char* UniqueId) { @@ -577,12 +640,12 @@ extern "C" void LLVMSetUnnamedAddr(LLVMValueRef Value, LLVMBool Unnamed) { } #endif -extern "C" LLVMValueRef LLVMDIBuilderCreateTemplateTypeParameter( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateTemplateTypeParameter( DIBuilderRef Builder, - LLVMValueRef Scope, + LLVMMetadataRef Scope, const char* Name, - LLVMValueRef Ty, - LLVMValueRef File, + LLVMMetadataRef Ty, + LLVMMetadataRef File, unsigned LineNo, unsigned ColumnNo) { @@ -595,47 +658,21 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateTemplateTypeParameter( ColumnNo)); } -extern "C" LLVMValueRef LLVMDIBuilderCreateOpDeref(LLVMTypeRef IntTy) +extern "C" int64_t LLVMDIBuilderCreateOpDeref() { - return LLVMConstInt(IntTy, DIBuilder::OpDeref, true); + return dwarf::DW_OP_deref; } -extern "C" LLVMValueRef LLVMDIBuilderCreateOpPlus(LLVMTypeRef IntTy) +extern "C" int64_t LLVMDIBuilderCreateOpPlus() { - return LLVMConstInt(IntTy, DIBuilder::OpPlus, true); + return dwarf::DW_OP_plus; } -extern "C" LLVMValueRef LLVMDIBuilderCreateComplexVariable( +extern "C" LLVMMetadataRef LLVMDIBuilderCreateNameSpace( DIBuilderRef Builder, - unsigned Tag, - LLVMValueRef Scope, - const char *Name, - LLVMValueRef File, - unsigned LineNo, - LLVMValueRef Ty, - LLVMValueRef* AddrOps, - unsigned AddrOpsCount, - unsigned ArgNo) -{ - llvm::ArrayRef<llvm::Value*> addr_ops((llvm::Value**)AddrOps, AddrOpsCount); - - return wrap(Builder->createComplexVariable( - Tag, - unwrapDI<DIDescriptor>(Scope), - Name, - unwrapDI<DIFile>(File), - LineNo, - unwrapDI<DIType>(Ty), - addr_ops, - ArgNo - )); -} - -extern "C" LLVMValueRef LLVMDIBuilderCreateNameSpace( - DIBuilderRef Builder, - LLVMValueRef Scope, + LLVMMetadataRef Scope, const char* Name, - LLVMValueRef File, + LLVMMetadataRef File, unsigned LineNo) { return wrap(Builder->createNameSpace( @@ -646,16 +683,39 @@ extern "C" LLVMValueRef LLVMDIBuilderCreateNameSpace( } extern "C" void LLVMDICompositeTypeSetTypeArray( - LLVMValueRef CompositeType, - LLVMValueRef TypeArray) + DIBuilderRef Builder, + LLVMMetadataRef CompositeType, + LLVMMetadataRef TypeArray) { #if LLVM_VERSION_MINOR >= 6 - unwrapDI<DICompositeType>(CompositeType).setArrays(unwrapDI<DIArray>(TypeArray)); + DICompositeType tmp = unwrapDI<DICompositeType>(CompositeType); + Builder->replaceArrays(tmp, unwrapDI<DIArray>(TypeArray)); #else unwrapDI<DICompositeType>(CompositeType).setTypeArray(unwrapDI<DIArray>(TypeArray)); #endif } +extern "C" LLVMValueRef LLVMDIBuilderCreateDebugLocation( + LLVMContextRef Context, + unsigned Line, + unsigned Column, + LLVMMetadataRef Scope, + LLVMMetadataRef InlinedAt) { + + LLVMContext& context = *unwrap(Context); + + DebugLoc debug_loc = DebugLoc::get(Line, + Column, + unwrapDI<MDNode*>(Scope), + unwrapDI<MDNode*>(InlinedAt)); + +#if LLVM_VERSION_MINOR >= 6 + return wrap(MetadataAsValue::get(context, debug_loc.getAsMDNode(context))); +#else + return wrap(debug_loc.getAsMDNode(context)); +#endif +} + extern "C" void LLVMWriteTypeToString(LLVMTypeRef Type, RustStringRef str) { raw_rust_string_ostream os(str); unwrap<llvm::Type>(Type)->print(os); @@ -690,7 +750,14 @@ LLVMRustLinkInExternalBitcode(LLVMModuleRef dst, char *bc, size_t len) { } std::string Err; + +#if LLVM_VERSION_MINOR >= 6 + raw_string_ostream Stream(Err); + DiagnosticPrinterRawOStream DP(Stream); + if (Linker::LinkModules(Dst, *Src, [&](const DiagnosticInfo &DI) { DI.print(DP); })) { +#else if (Linker::LinkModules(Dst, *Src, Linker::DestroySource, &Err)) { +#endif LLVMRustSetLastError(Err.c_str()); return false; } @@ -772,7 +839,7 @@ extern "C" const char* #if LLVM_VERSION_MINOR >= 6 LLVMRustArchiveReadSection(OwningBinary<Archive> *ob, char *name, size_t *size) { - std::unique_ptr<Archive> &ar = ob->getBinary(); + Archive *ar = ob->getBinary(); #else LLVMRustArchiveReadSection(Archive *ar, char *name, size_t *size) { #endif diff --git a/src/rustllvm/llvm-auto-clean-trigger b/src/rustllvm/llvm-auto-clean-trigger index e159e9729b6..c8003bb9581 100644 --- a/src/rustllvm/llvm-auto-clean-trigger +++ b/src/rustllvm/llvm-auto-clean-trigger @@ -1,4 +1,4 @@ # If this file is modified, then llvm will be forcibly cleaned and then rebuilt. # The actual contents of this file do not matter, but to trigger a change on the # build bots then the contents should be changed so git updates the mtime. -2015-01-30 +2015-02-02 diff --git a/src/snapshots.txt b/src/snapshots.txt index 3406a91e718..058e2e6bf7f 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,12 @@ +S 2015-01-31 474b324 + freebsd-x86_64 c5b55eb488790ff8425d74afa3b37c49517bc55f + linux-i386 319f2f3573c058cb2c4dfc75faaf8ea3ae86ef11 + linux-x86_64 7e71108be890adfecc7644ab6ad183e8a657dc97 + macos-i386 b0b2676681c6d8ec8cb85700428555761c7bdbb8 + macos-x86_64 381dd1587920388e2f71e120a1eabac2648d9672 + winnt-i386 5f99509f88355437824a746f7f90fc22233edb9b + winnt-x86_64 382aa20518b1a19d374f06a038025619ba00b77d + S 2015-01-28 a45e117 freebsd-x86_64 08a3ce7331fd1a52466acc0598cf745a009f86f6 linux-i386 66e36a3461c12e2102a7f7f241d1b0e242c704d0 diff --git a/src/test/auxiliary/cci_nested_lib.rs b/src/test/auxiliary/cci_nested_lib.rs index 8494917c615..587af956c77 100644 --- a/src/test/auxiliary/cci_nested_lib.rs +++ b/src/test/auxiliary/cci_nested_lib.rs @@ -35,7 +35,7 @@ pub fn alist_get<A:Clone + 'static, -> B { let eq_fn = lst.eq_fn; let data = lst.data.borrow(); - for entry in (*data).iter() { + for entry in &(*data) { if eq_fn(entry.key.clone(), k.clone()) { return entry.value.clone(); } diff --git a/src/test/bench/msgsend-pipes-shared.rs b/src/test/bench/msgsend-pipes-shared.rs index 6928397566d..259b4d9418d 100644 --- a/src/test/bench/msgsend-pipes-shared.rs +++ b/src/test/bench/msgsend-pipes-shared.rs @@ -75,7 +75,7 @@ fn run(args: &[String]) { server(&from_parent, &to_parent); }); - for r in worker_results.into_iter() { + for r in worker_results { let _ = r.join(); } diff --git a/src/test/bench/msgsend-pipes.rs b/src/test/bench/msgsend-pipes.rs index 9bf0ce1a590..1341c03e505 100644 --- a/src/test/bench/msgsend-pipes.rs +++ b/src/test/bench/msgsend-pipes.rs @@ -82,7 +82,7 @@ fn run(args: &[String]) { server(&from_parent, &to_parent); }); - for r in worker_results.into_iter() { + for r in worker_results { let _ = r.join(); } diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index c344084a4c0..5d17e3a460c 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -99,7 +99,7 @@ fn main() { thread_ring(0, msg_per_task, num_chan, num_port); // synchronize - for f in futures.iter_mut() { + for f in &mut futures { f.get() } }); diff --git a/src/test/bench/noise.rs b/src/test/bench/noise.rs index 664491eed7d..dc5b2f4596e 100644 --- a/src/test/bench/noise.rs +++ b/src/test/bench/noise.rs @@ -45,7 +45,7 @@ impl Noise2DContext { let mut rng = StdRng::new().unwrap(); let mut rgradients = [Vec2 { x: 0.0, y: 0.0 }; 256]; - for x in rgradients.iter_mut() { + for x in &mut rgradients[] { *x = random_gradient(&mut rng); } diff --git a/src/test/bench/shootout-binarytrees.rs b/src/test/bench/shootout-binarytrees.rs index 4182f8b651b..dc65a63c5cb 100644 --- a/src/test/bench/shootout-binarytrees.rs +++ b/src/test/bench/shootout-binarytrees.rs @@ -114,7 +114,7 @@ fn main() { Thread::scoped(move || inner(depth, iterations)) }).collect::<Vec<_>>(); - for message in messages.into_iter() { + for message in messages { println!("{}", message.join().ok().unwrap()); } diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index 15a63e153b9..0835dd9a08e 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -47,8 +47,8 @@ use std::thread::Thread; fn print_complements() { let all = [Blue, Red, Yellow]; - for aa in all.iter() { - for bb in all.iter() { + for aa in &all { + for bb in &all { println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb)); } } @@ -80,7 +80,7 @@ struct CreatureInfo { fn show_color_list(set: Vec<Color>) -> String { let mut out = String::new(); - for col in set.iter() { + for col in &set { out.push(' '); out.push_str(format!("{:?}", col).as_slice()); } diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index 03666c84d57..47613e2d69c 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -171,7 +171,7 @@ fn fannkuch(n: i32) -> (i32, i32) { let mut checksum = 0; let mut maxflips = 0; - for fut in futures.into_iter() { + for fut in futures { let (cs, mf) = fut.join().ok().unwrap(); checksum += cs; maxflips = cmp::max(maxflips, mf); diff --git a/src/test/bench/shootout-fasta-redux.rs b/src/test/bench/shootout-fasta-redux.rs index f32e98ef17d..5386fc0419d 100644 --- a/src/test/bench/shootout-fasta-redux.rs +++ b/src/test/bench/shootout-fasta-redux.rs @@ -92,7 +92,7 @@ static HOMO_SAPIENS: [AminoAcid;4] = [ fn sum_and_scale(a: &'static [AminoAcid]) -> Vec<AminoAcid> { let mut result = Vec::new(); let mut p = 0f32; - for a_i in a.iter() { + for a_i in a { let mut a_i = *a_i; p += a_i.p; a_i.p = p * LOOKUP_SCALE; @@ -180,7 +180,7 @@ impl<'a, W: Writer> RandomFasta<'a, W> { fn nextc(&mut self) -> u8 { let r = self.rng(1.0); - for a in self.lookup.iter() { + for a in &self.lookup[] { if a.p >= r { return a.c; } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 2da276b722e..ad8e6551a03 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -56,14 +56,14 @@ fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> String { let mut pairs = Vec::new(); // map -> [(k,%)] - for (key, &val) in mm.iter() { + for (key, &val) in mm { pairs.push(((*key).clone(), pct(val, total))); } let pairs_sorted = sortKV(pairs); let mut buffer = String::new(); - for &(ref k, v) in pairs_sorted.iter() { + for &(ref k, v) in &pairs_sorted { buffer.push_str(format!("{:?} {:0.3}\n", k.to_ascii_uppercase(), v).as_slice()); diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index 2c3ade63f06..e3f8e60df93 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -264,7 +264,7 @@ fn print_frequencies(frequencies: &Table, frame: uint) { vector.as_mut_slice().sort(); let mut total_count = 0; - for &(count, _) in vector.iter() { + for &(count, _) in &vector { total_count += count; } @@ -308,7 +308,7 @@ fn main() { Thread::scoped(move|| generate_frequencies(input.as_slice(), occ.len())) }).collect(); - for (i, freq) in nb_freqs.into_iter() { + for (i, freq) in nb_freqs { print_frequencies(&freq.join().ok().unwrap(), i); } for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.into_iter()) { diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index 4a9c5a91dcf..a5729c5b5bd 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -48,12 +48,12 @@ use std::simd::f64x2; use std::sync::Arc; use std::thread::Thread; -const ITER: int = 50; +const ITER: usize = 50; const LIMIT: f64 = 2.0; -const WORKERS: uint = 16; +const WORKERS: usize = 16; #[inline(always)] -fn mandelbrot<W: old_io::Writer>(w: uint, mut out: W) -> old_io::IoResult<()> { +fn mandelbrot<W: old_io::Writer>(w: usize, mut out: W) -> old_io::IoResult<()> { assert!(WORKERS % 2 == 0); // Ensure w and h are multiples of 8. @@ -106,7 +106,7 @@ fn mandelbrot<W: old_io::Writer>(w: uint, mut out: W) -> old_io::IoResult<()> { }) }).collect::<Vec<_>>(); - for res in precalc_futures.into_iter() { + for res in precalc_futures { let (rs, is) = res.join().ok().unwrap(); precalc_r.extend(rs.into_iter()); precalc_i.extend(is.into_iter()); @@ -133,7 +133,7 @@ fn mandelbrot<W: old_io::Writer>(w: uint, mut out: W) -> old_io::IoResult<()> { (i + 1) * chunk_size }; - for &init_i in vec_init_i[start..end].iter() { + for &init_i in &vec_init_i[start..end] { write_line(init_i, init_r_slice, &mut res); } @@ -142,7 +142,7 @@ fn mandelbrot<W: old_io::Writer>(w: uint, mut out: W) -> old_io::IoResult<()> { }).collect::<Vec<_>>(); try!(writeln!(&mut out as &mut Writer, "P4\n{} {}", w, h)); - for res in data.into_iter() { + for res in data { try!(out.write(res.join().ok().unwrap().as_slice())); } out.flush() @@ -198,7 +198,6 @@ fn write_line(init_i: f64, vec_init_r: &[f64], res: &mut Vec<u8>) { fn main() { let args = os::args(); - let args = args.as_slice(); let res = if args.len() < 2 { println!("Test mode: do not dump the image because it's not utf8, \ which interferes with the test runner."); diff --git a/src/test/bench/shootout-meteor.rs b/src/test/bench/shootout-meteor.rs index d44948e4ed2..d061403d590 100644 --- a/src/test/bench/shootout-meteor.rs +++ b/src/test/bench/shootout-meteor.rs @@ -116,9 +116,9 @@ fn transform(piece: Vec<(i32, i32)> , all: bool) -> Vec<Vec<(i32, i32)>> { }).collect(); // translating to (0, 0) as minimum coordinates. - for cur_piece in res.iter_mut() { + for cur_piece in &mut res { let (dy, dx) = *cur_piece.iter().min_by(|e| *e).unwrap(); - for &mut (ref mut y, ref mut x) in cur_piece.iter_mut() { + for &mut (ref mut y, ref mut x) in cur_piece { *y -= dy; *x -= dx; } } @@ -135,7 +135,7 @@ fn transform(piece: Vec<(i32, i32)> , all: bool) -> Vec<Vec<(i32, i32)>> { // dx) is on the board. fn mask(dy: i32, dx: i32, id: usize, p: &Vec<(i32, i32)>) -> Option<u64> { let mut m = 1 << (50 + id); - for &(y, x) in p.iter() { + for &(y, x) in p { let x = x + dx + (y + (dy % 2)) / 2; if x < 0 || x > 4 {return None;} let y = y + dy; @@ -184,7 +184,7 @@ fn is_board_unfeasible(board: u64, masks: &Vec<Vec<Vec<u64>>>) -> bool { if board & 1 << i != 0 { continue; } for (cur_id, pos_masks) in masks_at.iter().enumerate() { if board & 1 << (50 + cur_id) != 0 { continue; } - for &cur_m in pos_masks.iter() { + for &cur_m in pos_masks { if cur_m & board != 0 { continue; } coverable |= cur_m; // if every coordinates can be covered and every diff --git a/src/test/bench/shootout-nbody.rs b/src/test/bench/shootout-nbody.rs index b2161000322..a8de1469456 100644 --- a/src/test/bench/shootout-nbody.rs +++ b/src/test/bench/shootout-nbody.rs @@ -109,7 +109,7 @@ fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) { Some(bi) => bi, None => break }; - for bj in b_slice.iter_mut() { + for bj in &mut *b_slice { let dx = bi.x - bj.x; let dy = bi.y - bj.y; let dz = bi.z - bj.z; @@ -158,7 +158,7 @@ fn offset_momentum(bodies: &mut [Planet;N_BODIES]) { let mut px = 0.0; let mut py = 0.0; let mut pz = 0.0; - for bi in bodies.iter() { + for bi in &*bodies { px += bi.vx * bi.mass; py += bi.vy * bi.mass; pz += bi.vz * bi.mass; diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index dd3ae1699a9..ea1d913b3e2 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -82,7 +82,7 @@ fn stress(num_tasks: int) { stress_task(i); })); } - for r in results.into_iter() { + for r in results { let _ = r.join(); } } diff --git a/src/test/compile-fail/associated-types-ICE-when-projecting-out-of-err.rs b/src/test/compile-fail/associated-types-ICE-when-projecting-out-of-err.rs index 183781e9e24..b35d5131c78 100644 --- a/src/test/compile-fail/associated-types-ICE-when-projecting-out-of-err.rs +++ b/src/test/compile-fail/associated-types-ICE-when-projecting-out-of-err.rs @@ -29,6 +29,6 @@ trait Add<RHS=Self> { fn ice<A>(a: A) { let r = loop {}; - r = r + a; // here the type `r` is not yet inferred, hence `r+a` generates an error. - //~^ ERROR type of this value must be known + r = r + a; + //~^ ERROR binary operation `+` cannot be applied to type `A` } diff --git a/src/test/compile-fail/better-expected.rs b/src/test/compile-fail/better-expected.rs index 0d84a5e7d02..e07f4b8e549 100644 --- a/src/test/compile-fail/better-expected.rs +++ b/src/test/compile-fail/better-expected.rs @@ -9,5 +9,5 @@ // except according to those terms. fn main() { - let x: [isize 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `3` + let x: [isize 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `3` } diff --git a/src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs b/src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs index ad77953bdd8..492fd4a2c84 100644 --- a/src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs +++ b/src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs @@ -25,7 +25,7 @@ fn main() { let f = Foo { a: [box 3, box 4, box 5], }; - for &a in f.a.iter() { //~ ERROR cannot move out + for &a in &f.a { //~ ERROR cannot move out } let x = Some(box 1); diff --git a/src/test/compile-fail/borrowck-for-loop-head-linkage.rs b/src/test/compile-fail/borrowck-for-loop-head-linkage.rs index d2f99ea696a..043ea0bf00e 100644 --- a/src/test/compile-fail/borrowck-for-loop-head-linkage.rs +++ b/src/test/compile-fail/borrowck-for-loop-head-linkage.rs @@ -12,7 +12,7 @@ use std::iter::repeat; fn main() { let mut vector = vec![1us, 2]; - for &x in vector.iter() { + for &x in &vector { let cap = vector.capacity(); vector.extend(repeat(0)); //~ ERROR cannot borrow vector[1us] = 5us; //~ ERROR cannot borrow diff --git a/src/test/compile-fail/borrowck-insert-during-each.rs b/src/test/compile-fail/borrowck-insert-during-each.rs index d729af844cb..2c634865983 100644 --- a/src/test/compile-fail/borrowck-insert-during-each.rs +++ b/src/test/compile-fail/borrowck-insert-during-each.rs @@ -17,7 +17,7 @@ struct Foo { impl Foo { pub fn foo<F>(&mut self, mut fun: F) where F: FnMut(&isize) { - for f in self.n.iter() { + for f in &self.n { fun(f); } } diff --git a/src/test/compile-fail/drop-with-active-borrows-1.rs b/src/test/compile-fail/drop-with-active-borrows-1.rs index 5f5fbd0f348..dc8deb04833 100644 --- a/src/test/compile-fail/drop-with-active-borrows-1.rs +++ b/src/test/compile-fail/drop-with-active-borrows-1.rs @@ -12,7 +12,7 @@ fn main() { let a = "".to_string(); let b: Vec<&str> = a.lines().collect(); drop(a); //~ ERROR cannot move out of `a` because it is borrowed - for s in b.iter() { + for s in &b { println!("{}", *s); } } diff --git a/src/test/compile-fail/empty-impl-semicolon.rs b/src/test/compile-fail/empty-impl-semicolon.rs index a598252f1b6..70c7d42feb5 100644 --- a/src/test/compile-fail/empty-impl-semicolon.rs +++ b/src/test/compile-fail/empty-impl-semicolon.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -impl Foo; //~ ERROR expected one of `(`, `+`, `::`, or `{`, found `;` +impl Foo; //~ ERROR expected one of `(`, `+`, `::`, `<`, `for`, `where`, or `{`, found `;` diff --git a/src/test/compile-fail/extern-no-fn.rs b/src/test/compile-fail/extern-no-fn.rs index 164cbe54174..69e2f3ae60b 100644 --- a/src/test/compile-fail/extern-no-fn.rs +++ b/src/test/compile-fail/extern-no-fn.rs @@ -8,9 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern:unexpected token extern { - f(); + f(); //~ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `f` } fn main() { diff --git a/src/test/compile-fail/issue-15480.rs b/src/test/compile-fail/issue-15480.rs index 1e4476e563b..30f58f909a0 100644 --- a/src/test/compile-fail/issue-15480.rs +++ b/src/test/compile-fail/issue-15480.rs @@ -14,7 +14,7 @@ fn main() { //~^ ERROR borrowed value does not live long enough ]; - for &&x in v.iter() { + for &&x in &v { println!("{}", x + 3); } } diff --git a/src/test/compile-fail/issue-18400.rs b/src/test/compile-fail/issue-18400.rs index f3b2b3d5667..015f1fa603a 100644 --- a/src/test/compile-fail/issue-18400.rs +++ b/src/test/compile-fail/issue-18400.rs @@ -22,7 +22,7 @@ impl<'a, T, S> Set<&'a [T]> for S where } fn set(&mut self, bits: &[T]) { - for &bit in bits.iter() { + for &bit in bits { self.set(bit) } } diff --git a/src/test/compile-fail/issue-20711-2.rs b/src/test/compile-fail/issue-20711-2.rs index 9f0e81a662f..a6c4570c60f 100644 --- a/src/test/compile-fail/issue-20711-2.rs +++ b/src/test/compile-fail/issue-20711-2.rs @@ -14,7 +14,7 @@ impl Foo { fn foo() {} #[stable(feature = "rust1", since = "1.0.0")] -} //~ ERROR expected `fn`, found `}` +} //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `}` fn main() {} diff --git a/src/test/compile-fail/issue-20711.rs b/src/test/compile-fail/issue-20711.rs index 5f0f0fc05a9..3b329d78237 100644 --- a/src/test/compile-fail/issue-20711.rs +++ b/src/test/compile-fail/issue-20711.rs @@ -12,6 +12,6 @@ struct Foo; impl Foo { #[stable(feature = "rust1", since = "1.0.0")] -} //~ ERROR expected `fn`, found `}` +} //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `}` fn main() {} diff --git a/src/test/compile-fail/issue-21153.rs b/src/test/compile-fail/issue-21153.rs new file mode 100644 index 00000000000..e2b6deb0ad9 --- /dev/null +++ b/src/test/compile-fail/issue-21153.rs @@ -0,0 +1,13 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +trait MyTrait<T>: Iterator { + Item = T; //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `Item` +} diff --git a/src/test/compile-fail/issue-2149.rs b/src/test/compile-fail/issue-2149.rs index 691660f8971..45b7bebfc28 100644 --- a/src/test/compile-fail/issue-2149.rs +++ b/src/test/compile-fail/issue-2149.rs @@ -15,8 +15,8 @@ trait vec_monad<A> { impl<A> vec_monad<A> for Vec<A> { fn bind<B, F>(&self, mut f: F) where F: FnMut(A) -> Vec<B> { let mut r = panic!(); - for elt in self.iter() { r = r + f(*elt); } - //~^ ERROR the type of this value must be known + for elt in self { r = r + f(*elt); } + //~^ ERROR binary operation `+` cannot be applied to type `collections::vec::Vec<B>` } } fn main() { diff --git a/src/test/compile-fail/issue-2150.rs b/src/test/compile-fail/issue-2150.rs index 68195985eec..a2711d532d2 100644 --- a/src/test/compile-fail/issue-2150.rs +++ b/src/test/compile-fail/issue-2150.rs @@ -16,7 +16,7 @@ fn fail_len(v: Vec<isize> ) -> usize { let mut i = 3; panic!(); - for x in v.iter() { i += 1us; } + for x in &v { i += 1us; } //~^ ERROR: unreachable statement return i; } diff --git a/src/test/compile-fail/issue-5100.rs b/src/test/compile-fail/issue-5100.rs index b051abbc7ff..474274c93fd 100644 --- a/src/test/compile-fail/issue-5100.rs +++ b/src/test/compile-fail/issue-5100.rs @@ -64,7 +64,7 @@ fn main() { ('c', 'd'), ('e', 'f')]; - for &(x,y) in v.iter() {} // should be OK + for &(x,y) in &v {} // should be OK // Make sure none of the errors above were fatal let x: char = true; //~ ERROR mismatched types diff --git a/src/test/compile-fail/issue-7573.rs b/src/test/compile-fail/issue-7573.rs index 897afb1c102..c15c556f5d6 100644 --- a/src/test/compile-fail/issue-7573.rs +++ b/src/test/compile-fail/issue-7573.rs @@ -32,7 +32,7 @@ pub fn remove_package_from_database() { }; list_database(push_id); - for l in lines_to_use.iter() { + for l in &lines_to_use { println!("{}", l.local_path); } @@ -41,7 +41,7 @@ pub fn remove_package_from_database() { pub fn list_database<F>(mut f: F) where F: FnMut(&CrateId) { let stuff = ["foo", "bar"]; - for l in stuff.iter() { + for l in &stuff { f(&CrateId::new(*l)); } } diff --git a/src/test/compile-fail/lint-type-limits.rs b/src/test/compile-fail/lint-type-limits.rs index 3eae12f234f..95d892010e7 100644 --- a/src/test/compile-fail/lint-type-limits.rs +++ b/src/test/compile-fail/lint-type-limits.rs @@ -26,7 +26,7 @@ fn bar() -> i8 { fn baz() -> bool { 128 > bar() //~ ERROR comparison is useless due to type limits - //~^ WARNING literal out of range for its type + //~^ WARNING literal out of range for i8 } fn bleh() { @@ -44,7 +44,7 @@ fn bleh() { fn qux() { let mut i = 1i8; while 200 != i { //~ ERROR comparison is useless due to type limits - //~^ WARNING literal out of range for its type + //~^ WARNING literal out of range for i8 i += 1; } } diff --git a/src/test/compile-fail/lint-type-overflow.rs b/src/test/compile-fail/lint-type-overflow.rs index 47dc93dae13..ed6a0bd37eb 100644 --- a/src/test/compile-fail/lint-type-overflow.rs +++ b/src/test/compile-fail/lint-type-overflow.rs @@ -18,42 +18,43 @@ fn test(x: i8) { #[allow(unused_variables)] fn main() { let x1: u8 = 255; // should be OK - let x1: u8 = 256; //~ error: literal out of range for its type + let x1: u8 = 256; //~ error: literal out of range for u8 let x1 = 255_u8; // should be OK - let x1 = 256_u8; //~ error: literal out of range for its type + let x1 = 256_u8; //~ error: literal out of range for u8 let x2: i8 = -128; // should be OK - let x1: i8 = 128; //~ error: literal out of range for its type - let x2: i8 = --128; //~ error: literal out of range for its type + let x1: i8 = 128; //~ error: literal out of range for i8 + let x2: i8 = --128; //~ error: literal out of range for i8 - let x3: i8 = -129; //~ error: literal out of range for its type - let x3: i8 = -(129); //~ error: literal out of range for its type - let x3: i8 = -{129}; //~ error: literal out of range for its type + let x3: i8 = -129; //~ error: literal out of range for i8 + let x3: i8 = -(129); //~ error: literal out of range for i8 + let x3: i8 = -{129}; //~ error: literal out of range for i8 - test(1000); //~ error: literal out of range for its type + test(1000); //~ error: literal out of range for i8 - let x = 128_i8; //~ error: literal out of range for its type + let x = 128_i8; //~ error: literal out of range for i8 let x = 127_i8; let x = -128_i8; let x = -(128_i8); - let x = -129_i8; //~ error: literal out of range for its type + let x = -129_i8; //~ error: literal out of range for i8 let x: i32 = 2147483647; // should be OK let x = 2147483647_i32; // should be OK - let x: i32 = 2147483648; //~ error: literal out of range for its type - let x = 2147483648_i32; //~ error: literal out of range for its type + let x: i32 = 2147483648; //~ error: literal out of range for i32 + let x = 2147483648_i32; //~ error: literal out of range for i32 let x: i32 = -2147483648; // should be OK let x = -2147483648_i32; // should be OK - let x: i32 = -2147483649; //~ error: literal out of range for its type - let x = -2147483649_i32; //~ error: literal out of range for its type + let x: i32 = -2147483649; //~ error: literal out of range for i32 + let x = -2147483649_i32; //~ error: literal out of range for i32 + let x = 2147483648; //~ error: literal out of range for i32 - let x = 9223372036854775808_i64; //~ error: literal out of range for its type + let x = 9223372036854775808_i64; //~ error: literal out of range for i64 let x = -9223372036854775808_i64; // should be OK - let x = 18446744073709551615_i64; //~ error: literal out of range for its type + let x = 18446744073709551615_i64; //~ error: literal out of range for i64 - let x = -3.40282348e+38_f32; //~ error: literal out of range for its type - let x = 3.40282348e+38_f32; //~ error: literal out of range for its type - let x = -1.7976931348623159e+308_f64; //~ error: literal out of range for its type - let x = 1.7976931348623159e+308_f64; //~ error: literal out of range for its type + let x = -3.40282348e+38_f32; //~ error: literal out of range for f32 + let x = 3.40282348e+38_f32; //~ error: literal out of range for f32 + let x = -1.7976931348623159e+308_f64; //~ error: literal out of range for f64 + let x = 1.7976931348623159e+308_f64; //~ error: literal out of range for f64 } diff --git a/src/test/compile-fail/lint-unknown-feature-default.rs b/src/test/compile-fail/lint-unknown-feature-default.rs index d5e9cc630c3..afd1a3933bf 100644 --- a/src/test/compile-fail/lint-unknown-feature-default.rs +++ b/src/test/compile-fail/lint-unknown-feature-default.rs @@ -10,6 +10,8 @@ // Tests the default for the unused_features lint +#![deny(warnings)] + #![feature(this_is_not_a_feature)] //~ ERROR: unused or unknown feature fn main() { } diff --git a/src/test/compile-fail/liveness-unused.rs b/src/test/compile-fail/liveness-unused.rs index 60c4c246552..d4238120d06 100644 --- a/src/test/compile-fail/liveness-unused.rs +++ b/src/test/compile-fail/liveness-unused.rs @@ -12,7 +12,6 @@ #![deny(unused_assignments)] #![allow(dead_code, non_camel_case_types)] #![feature(core)] -#![feature(os)] fn f1(x: isize) { //~^ ERROR unused variable: `x` @@ -98,7 +97,7 @@ fn f5c() { for (_, x) in [1, 2, 3].iter().enumerate() { //~^ ERROR unused variable: `x` continue; - std::os::set_exit_status(*x); //~ WARNING unreachable statement + drop(*x as i32); //~ WARNING unreachable statement } } diff --git a/src/test/compile-fail/multitrait.rs b/src/test/compile-fail/multitrait.rs index a0e210aed40..f182eb8fa5b 100644 --- a/src/test/compile-fail/multitrait.rs +++ b/src/test/compile-fail/multitrait.rs @@ -12,7 +12,8 @@ struct S { y: isize } -impl Cmp, ToString for S { //~ ERROR: expected one of `(`, `+`, `::`, or `{`, found `,` +impl Cmp, ToString for S { +//~^ ERROR: expected one of `(`, `+`, `::`, `<`, `for`, `where`, or `{`, found `,` fn eq(&&other: S) { false } fn to_string(&self) -> String { "hi".to_string() } } diff --git a/src/test/compile-fail/pat-range-bad-dots.rs b/src/test/compile-fail/pat-range-bad-dots.rs index b48d3e8871b..c52fb8c9b67 100644 --- a/src/test/compile-fail/pat-range-bad-dots.rs +++ b/src/test/compile-fail/pat-range-bad-dots.rs @@ -10,7 +10,7 @@ pub fn main() { match 22 { - 0 .. 3 => {} //~ ERROR expected one of `...`, `=>`, or `|`, found `..` + 0 .. 3 => {} //~ ERROR expected one of `...`, `=>`, `if`, or `|`, found `..` _ => {} } } diff --git a/src/test/compile-fail/removed-syntax-closure-lifetime.rs b/src/test/compile-fail/removed-syntax-closure-lifetime.rs index a07832d5bb7..0cea87dba19 100644 --- a/src/test/compile-fail/removed-syntax-closure-lifetime.rs +++ b/src/test/compile-fail/removed-syntax-closure-lifetime.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -type closure = Box<lt/fn()>; //~ ERROR expected one of `(`, `+`, `,`, `::`, or `>`, found `/` +type closure = Box<lt/fn()>; //~ ERROR expected one of `(`, `+`, `,`, `::`, `<`, or `>`, found `/` diff --git a/src/test/compile-fail/removed-syntax-enum-newtype.rs b/src/test/compile-fail/removed-syntax-enum-newtype.rs index 3b45fd81288..b067cee03d2 100644 --- a/src/test/compile-fail/removed-syntax-enum-newtype.rs +++ b/src/test/compile-fail/removed-syntax-enum-newtype.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum e = isize; //~ ERROR expected one of `<` or `{`, found `=` +enum e = isize; //~ ERROR expected one of `<`, `where`, or `{`, found `=` diff --git a/src/test/compile-fail/removed-syntax-extern-const.rs b/src/test/compile-fail/removed-syntax-extern-const.rs index 98eec0977e0..a0e1d04a3dc 100644 --- a/src/test/compile-fail/removed-syntax-extern-const.rs +++ b/src/test/compile-fail/removed-syntax-extern-const.rs @@ -9,5 +9,6 @@ // except according to those terms. extern { - const i: isize; //~ ERROR unexpected token: `const` + const i: isize; + //~^ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `const` } diff --git a/src/test/compile-fail/removed-syntax-fixed-vec.rs b/src/test/compile-fail/removed-syntax-fixed-vec.rs index 0ca2380ef68..0e8e20b3891 100644 --- a/src/test/compile-fail/removed-syntax-fixed-vec.rs +++ b/src/test/compile-fail/removed-syntax-fixed-vec.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -type v = [isize * 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `*` +type v = [isize * 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `*` diff --git a/src/test/compile-fail/removed-syntax-mut-vec-ty.rs b/src/test/compile-fail/removed-syntax-mut-vec-ty.rs index 0f67a1d04ee..9a7570a92f0 100644 --- a/src/test/compile-fail/removed-syntax-mut-vec-ty.rs +++ b/src/test/compile-fail/removed-syntax-mut-vec-ty.rs @@ -10,4 +10,4 @@ type v = [mut isize]; //~^ ERROR expected identifier, found keyword `mut` - //~^^ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `isize` + //~^^ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `isize` diff --git a/src/test/compile-fail/removed-syntax-ptr-lifetime.rs b/src/test/compile-fail/removed-syntax-ptr-lifetime.rs index d94f2ec1e07..44c65d98c0b 100644 --- a/src/test/compile-fail/removed-syntax-ptr-lifetime.rs +++ b/src/test/compile-fail/removed-syntax-ptr-lifetime.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -type bptr = &lifetime/isize; //~ ERROR expected one of `(`, `+`, `::`, or `;`, found `/` +type bptr = &lifetime/isize; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `<`, found `/` diff --git a/src/test/compile-fail/removed-syntax-static-fn.rs b/src/test/compile-fail/removed-syntax-static-fn.rs index e3e1cb0f3ca..caf939e7b8a 100644 --- a/src/test/compile-fail/removed-syntax-static-fn.rs +++ b/src/test/compile-fail/removed-syntax-static-fn.rs @@ -11,5 +11,6 @@ struct S; impl S { - static fn f() {} //~ ERROR expected `fn`, found `static` + static fn f() {} + //~^ ERROR expected one of `extern`, `fn`, `pub`, `type`, `unsafe`, or `}`, found `static` } diff --git a/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs b/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs index c051059aee6..d1c2fc69f52 100644 --- a/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs +++ b/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs @@ -10,4 +10,4 @@ type mut_box = Box<mut isize>; //~^ ERROR expected identifier, found keyword `mut` - //~^^ ERROR expected one of `(`, `+`, `,`, `::`, or `>`, found `isize` + //~^^ ERROR expected one of `(`, `+`, `,`, `::`, `<`, or `>`, found `isize` diff --git a/src/test/compile-fail/struct-literal-in-match-discriminant.rs b/src/test/compile-fail/struct-literal-in-match-discriminant.rs index 8f50940806a..e6948b7c7c9 100644 --- a/src/test/compile-fail/struct-literal-in-match-discriminant.rs +++ b/src/test/compile-fail/struct-literal-in-match-discriminant.rs @@ -14,7 +14,7 @@ struct Foo { fn main() { match Foo { - x: 3 //~ ERROR expected one of `!`, `=>`, `@`, or `|`, found `:` + x: 3 //~ ERROR expected one of `!`, `=>`, `@`, `if`, or `|`, found `:` } { Foo { x: x diff --git a/src/test/compile-fail/use-as-where-use-ends-with-mod-sep.rs b/src/test/compile-fail/use-as-where-use-ends-with-mod-sep.rs new file mode 100644 index 00000000000..524fd01b94c --- /dev/null +++ b/src/test/compile-fail/use-as-where-use-ends-with-mod-sep.rs @@ -0,0 +1,12 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::any:: as foo; //~ ERROR expected identifier, found keyword `as` +//~^ ERROR: expected one of `::`, `;`, or `as`, found `foo` diff --git a/src/test/compile-fail/use-ends-with-mod-sep.rs b/src/test/compile-fail/use-ends-with-mod-sep.rs new file mode 100644 index 00000000000..a375a5962a5 --- /dev/null +++ b/src/test/compile-fail/use-ends-with-mod-sep.rs @@ -0,0 +1,11 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::any::; //~ ERROR expected identifier or `{` or `*`, found `;` diff --git a/src/test/compile-fail/use-mod-4.rs b/src/test/compile-fail/use-mod-4.rs new file mode 100644 index 00000000000..a8b551b5376 --- /dev/null +++ b/src/test/compile-fail/use-mod-4.rs @@ -0,0 +1,15 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use foo::self; +//~^ ERROR expected identifier, found keyword `self` + +fn main() {} + diff --git a/src/test/compile-fail/use-mod.rs b/src/test/compile-fail/use-mod.rs index 493991835e8..15640e386df 100644 --- a/src/test/compile-fail/use-mod.rs +++ b/src/test/compile-fail/use-mod.rs @@ -19,9 +19,6 @@ use foo::bar::{ use {self}; //~^ ERROR `self` import can only appear in an import list with a non-empty prefix -use foo::self; -//~^ ERROR `self` imports are only allowed within a { } list - mod foo { pub mod bar { pub struct Bar; diff --git a/src/test/compile-fail/vec-mut-iter-borrow.rs b/src/test/compile-fail/vec-mut-iter-borrow.rs index 7dcedc8ecad..023ef72c453 100644 --- a/src/test/compile-fail/vec-mut-iter-borrow.rs +++ b/src/test/compile-fail/vec-mut-iter-borrow.rs @@ -11,7 +11,7 @@ fn main() { let mut xs: Vec<isize> = vec!(); - for x in xs.iter_mut() { + for x in &mut xs { xs.push(1) //~ ERROR cannot borrow `xs` } } diff --git a/src/test/debuginfo/destructured-for-loop-variable.rs b/src/test/debuginfo/destructured-for-loop-variable.rs index 08062ce8966..0d526d60190 100644 --- a/src/test/debuginfo/destructured-for-loop-variable.rs +++ b/src/test/debuginfo/destructured-for-loop-variable.rs @@ -170,14 +170,14 @@ fn main() { z: true }; - for &Struct { x, y, z } in [s].iter() { + for &Struct { x, y, z } in &[s] { zzz(); // #break } let tuple: (i8, u8, i16, u16, i32, u32, i64, u64, f32, f64) = (0x6f, 0x70, -113, 114, -115, 116, -117, 118, 119.5, 120.5); - for &(_i8, _u8, _i16, _u16, _i32, _u32, _i64, _u64, _f32, _f64) in [tuple].iter() { + for &(_i8, _u8, _i16, _u16, _i32, _u32, _i64, _u64, _f32, _f64) in &[tuple] { zzz(); // #break } @@ -215,7 +215,7 @@ fn main() { zzz(); // #break } - for simple_tuple_ident in vec![(34903493u32, 232323i64)].into_iter() { + for simple_tuple_ident in vec![(34903493u32, 232323i64)] { zzz(); // #break } } diff --git a/src/test/debuginfo/lexical-scope-in-for-loop.rs b/src/test/debuginfo/lexical-scope-in-for-loop.rs index 1fa54e47163..fe5983cbb6a 100644 --- a/src/test/debuginfo/lexical-scope-in-for-loop.rs +++ b/src/test/debuginfo/lexical-scope-in-for-loop.rs @@ -94,7 +94,7 @@ fn main() { let x = 1000000; // wan meeeljen doollaars! - for &x in range.iter() { + for &x in &range { zzz(); // #break sentinel(); diff --git a/src/test/debuginfo/unreachable-locals.rs b/src/test/debuginfo/unreachable-locals.rs index 70f8b1ccd96..8bcb54af8ba 100644 --- a/src/test/debuginfo/unreachable-locals.rs +++ b/src/test/debuginfo/unreachable-locals.rs @@ -26,7 +26,7 @@ fn after_return() { match (20i32, 'c') { (a, ref b) => {} } - for a in [111i32].iter() {} + for a in &[111i32] {} } fn after_panic() { @@ -36,7 +36,7 @@ fn after_panic() { match (20i32, 'c') { (a, ref b) => {} } - for a in [111i32].iter() {} + for a in &[111i32] {} } fn after_diverging_function() { @@ -46,7 +46,7 @@ fn after_diverging_function() { match (20i32, 'c') { (a, ref b) => {} } - for a in [111i32].iter() {} + for a in &[111i32] {} } fn after_break() { @@ -57,7 +57,7 @@ fn after_break() { match (20i32, 'c') { (a, ref b) => {} } - for a in [111i32].iter() {} + for a in &[111i32] {} } } @@ -69,7 +69,7 @@ fn after_continue() { match (20i32, 'c') { (a, ref b) => {} } - for a in [111i32].iter() {} + for a in &[111i32] {} } } diff --git a/src/test/pretty/block-comment-wchar.pp b/src/test/pretty/block-comment-wchar.pp index fbdd15b6060..5a55cb4e561 100644 --- a/src/test/pretty/block-comment-wchar.pp +++ b/src/test/pretty/block-comment-wchar.pp @@ -109,7 +109,7 @@ fn main() { '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200A', '\u2028', '\u2029', '\u202F', '\u205F', '\u3000']; - for c in chars.iter() { + for c in &chars { let ws = c.is_whitespace(); println!("{} {}" , c , ws); } diff --git a/src/test/pretty/block-comment-wchar.rs b/src/test/pretty/block-comment-wchar.rs index cc5640ce82a..c82bdcd8dcb 100644 --- a/src/test/pretty/block-comment-wchar.rs +++ b/src/test/pretty/block-comment-wchar.rs @@ -103,7 +103,7 @@ fn main() { '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200A', '\u2028', '\u2029', '\u202F', '\u205F', '\u3000']; - for c in chars.iter() { + for c in &chars { let ws = c.is_whitespace(); println!("{} {}", c , ws); } diff --git a/src/test/pretty/for-comment.rs b/src/test/pretty/for-comment.rs index 2318e783b69..0f2a667e11c 100644 --- a/src/test/pretty/for-comment.rs +++ b/src/test/pretty/for-comment.rs @@ -12,7 +12,7 @@ fn f(v: &[int]) -> int { let mut n = 0; - for e in v.iter() { + for e in v { n = *e; // This comment once triggered pretty printer bug } diff --git a/src/test/run-make/extern-overrides-distribution/Makefile b/src/test/run-make/extern-overrides-distribution/Makefile new file mode 100644 index 00000000000..110db9f068d --- /dev/null +++ b/src/test/run-make/extern-overrides-distribution/Makefile @@ -0,0 +1,5 @@ +-include ../tools.mk + +all: + $(RUSTC) libc.rs + $(RUSTC) main.rs --extern libc=$(TMPDIR)/liblibc.rlib diff --git a/src/test/run-make/extern-overrides-distribution/libc.rs b/src/test/run-make/extern-overrides-distribution/libc.rs new file mode 100644 index 00000000000..a489d834a92 --- /dev/null +++ b/src/test/run-make/extern-overrides-distribution/libc.rs @@ -0,0 +1,13 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![crate_type = "lib"] + +pub fn foo() {} diff --git a/src/test/run-make/extern-overrides-distribution/main.rs b/src/test/run-make/extern-overrides-distribution/main.rs new file mode 100644 index 00000000000..92b353c892a --- /dev/null +++ b/src/test/run-make/extern-overrides-distribution/main.rs @@ -0,0 +1,16 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate libc; + +fn main() { + libc::foo(); +} + diff --git a/src/test/run-make/tools.mk b/src/test/run-make/tools.mk index 1c791f0690c..23c422bc7a7 100644 --- a/src/test/run-make/tools.mk +++ b/src/test/run-make/tools.mk @@ -53,17 +53,21 @@ endif # Extra flags needed to compile a working executable with the standard library ifdef IS_WINDOWS - EXTRACFLAGS := -lws2_32 + EXTRACFLAGS := -lws2_32 -luserenv else ifeq ($(shell uname),Darwin) else ifeq ($(shell uname),FreeBSD) EXTRACFLAGS := -lm -lpthread -lgcc_s else +ifeq ($(shell uname),OpenBSD) + EXTRACFLAGS := -lm -lpthread +else EXTRACFLAGS := -lm -lrt -ldl -lpthread endif endif endif +endif REMOVE_DYLIBS = rm $(TMPDIR)/$(call DYLIB_GLOB,$(1)) REMOVE_RLIBS = rm $(TMPDIR)/$(call RLIB_GLOB,$(1)) diff --git a/src/test/run-pass/auto-loop.rs b/src/test/run-pass/auto-loop.rs index e5f4d078749..2cc7451e138 100644 --- a/src/test/run-pass/auto-loop.rs +++ b/src/test/run-pass/auto-loop.rs @@ -11,7 +11,7 @@ pub fn main() { let mut sum = 0; let xs = vec!(1, 2, 3, 4, 5); - for x in xs.iter() { + for x in &xs { sum += *x; } assert_eq!(sum, 15); diff --git a/src/test/run-pass/block-arg.rs b/src/test/run-pass/block-arg.rs index d017a0dbf9a..2f530331a2b 100644 --- a/src/test/run-pass/block-arg.rs +++ b/src/test/run-pass/block-arg.rs @@ -13,7 +13,7 @@ pub fn main() { let v = vec!(-1.0f64, 0.0, 1.0, 2.0, 3.0); // Statement form does not require parentheses: - for i in v.iter() { + for i in &v { println!("{}", *i); } diff --git a/src/test/run-pass/block-iter-1.rs b/src/test/run-pass/block-iter-1.rs index b5bd4d90c2e..d5d26f42ef0 100644 --- a/src/test/run-pass/block-iter-1.rs +++ b/src/test/run-pass/block-iter-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn iter_vec<T, F>(v: Vec<T> , mut f: F) where F: FnMut(&T) { for x in v.iter() { f(x); } } +fn iter_vec<T, F>(v: Vec<T> , mut f: F) where F: FnMut(&T) { for x in &v { f(x); } } pub fn main() { let v = vec![1i32, 2, 3, 4, 5, 6, 7]; diff --git a/src/test/run-pass/block-iter-2.rs b/src/test/run-pass/block-iter-2.rs index 348d9df6e7e..8c079ca4b07 100644 --- a/src/test/run-pass/block-iter-2.rs +++ b/src/test/run-pass/block-iter-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn iter_vec<T, F>(v: Vec<T>, mut f: F) where F: FnMut(&T) { for x in v.iter() { f(x); } } +fn iter_vec<T, F>(v: Vec<T>, mut f: F) where F: FnMut(&T) { for x in &v { f(x); } } pub fn main() { let v = vec![1i32, 2, 3, 4, 5]; diff --git a/src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs b/src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs index 05dffe91680..94c7c2b13ce 100644 --- a/src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs +++ b/src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs @@ -11,7 +11,7 @@ fn want_slice(v: &[int]) -> int { let mut sum = 0; - for i in v.iter() { sum += *i; } + for i in v { sum += *i; } sum } diff --git a/src/test/run-pass/break.rs b/src/test/run-pass/break.rs index bcfb8f6f914..6498c4b461d 100644 --- a/src/test/run-pass/break.rs +++ b/src/test/run-pass/break.rs @@ -15,7 +15,7 @@ pub fn main() { loop { i += 1; if i == 20 { break; } } assert_eq!(i, 20); let xs = [1, 2, 3, 4, 5, 6]; - for x in xs.iter() { + for x in &xs { if *x == 3 { break; } assert!((*x <= 3)); } i = 0; @@ -26,7 +26,7 @@ pub fn main() { if i >= 10 { break; } } let ys = vec!(1, 2, 3, 4, 5, 6); - for x in ys.iter() { + for x in &ys { if *x % 2 == 0 { continue; } assert!((*x % 2 != 0)); } diff --git a/src/test/run-pass/capture-clauses-boxed-closures.rs b/src/test/run-pass/capture-clauses-boxed-closures.rs index 6e8ed4fd5a1..5e696566bfa 100644 --- a/src/test/run-pass/capture-clauses-boxed-closures.rs +++ b/src/test/run-pass/capture-clauses-boxed-closures.rs @@ -9,7 +9,7 @@ // except according to those terms. fn each<T, F>(x: &[T], mut f: F) where F: FnMut(&T) { - for val in x.iter() { + for val in x { f(val) } } diff --git a/src/test/run-pass/capture-clauses-unboxed-closures.rs b/src/test/run-pass/capture-clauses-unboxed-closures.rs index cd40e2a7843..de1196e10d8 100644 --- a/src/test/run-pass/capture-clauses-unboxed-closures.rs +++ b/src/test/run-pass/capture-clauses-unboxed-closures.rs @@ -11,7 +11,7 @@ #![feature(unboxed_closures)] fn each<'a,T,F:FnMut(&'a T)>(x: &'a [T], mut f: F) { - for val in x.iter() { + for val in x { f(val) } } diff --git a/src/test/run-pass/cleanup-rvalue-for-scope.rs b/src/test/run-pass/cleanup-rvalue-for-scope.rs index 8969cca2610..f69a0332cc4 100644 --- a/src/test/run-pass/cleanup-rvalue-for-scope.rs +++ b/src/test/run-pass/cleanup-rvalue-for-scope.rs @@ -61,7 +61,7 @@ impl Drop for AddFlags { pub fn main() { // The array containing [AddFlags] should not be dropped until // after the for loop: - for x in [AddFlags(1)].iter() { + for x in &[AddFlags(1)] { check_flags(0); } check_flags(1); diff --git a/src/test/run-pass/coerce-reborrow-imm-vec-arg.rs b/src/test/run-pass/coerce-reborrow-imm-vec-arg.rs index f6abfda03e3..b6b30e2fe9b 100644 --- a/src/test/run-pass/coerce-reborrow-imm-vec-arg.rs +++ b/src/test/run-pass/coerce-reborrow-imm-vec-arg.rs @@ -10,7 +10,7 @@ fn sum(x: &[int]) -> int { let mut sum = 0; - for y in x.iter() { sum += *y; } + for y in x { sum += *y; } return sum; } diff --git a/src/test/run-pass/const-vec-of-fns.rs b/src/test/run-pass/const-vec-of-fns.rs index f21f7d1903c..4b07b1d3b07 100644 --- a/src/test/run-pass/const-vec-of-fns.rs +++ b/src/test/run-pass/const-vec-of-fns.rs @@ -22,8 +22,8 @@ static mut closures: &'static mut [S<fn()>] = &mut [S(f as fn()), S(f as fn())]; pub fn main() { unsafe { - for &bare_fn in bare_fns.iter() { bare_fn() } - for closure in closures.iter_mut() { + for &bare_fn in bare_fns { bare_fn() } + for closure in &mut *closures { let S(ref mut closure) = *closure; (*closure)() } diff --git a/src/test/run-pass/env-home-dir.rs b/src/test/run-pass/env-home-dir.rs new file mode 100644 index 00000000000..0e1ab73c02d --- /dev/null +++ b/src/test/run-pass/env-home-dir.rs @@ -0,0 +1,49 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::env::*; + +#[cfg(unix)] +fn main() { + let oldhome = var("HOME"); + + set_var("HOME", "/home/MountainView"); + assert!(home_dir() == Some(Path::new("/home/MountainView"))); + + remove_var("HOME"); + if cfg!(target_os = "android") { + assert!(home_dir().is_none()); + } else { + assert!(home_dir().is_some()); + } +} + +#[cfg(windows)] +fn main() { + let oldhome = var("HOME"); + let olduserprofile = var("USERPROFILE"); + + remove_var("HOME"); + remove_var("USERPROFILE"); + + assert!(home_dir().is_some()); + + set_var("HOME", "/home/MountainView"); + assert!(home_dir() == Some(Path::new("/home/MountainView"))); + + remove_var("HOME"); + + set_var("USERPROFILE", "/home/MountainView"); + assert!(home_dir() == Some(Path::new("/home/MountainView"))); + + set_var("HOME", "/home/MountainView"); + set_var("USERPROFILE", "/home/PaloAlto"); + assert!(home_dir() == Some(Path::new("/home/MountainView"))); +} diff --git a/src/test/run-pass/env-vars.rs b/src/test/run-pass/env-vars.rs new file mode 100644 index 00000000000..892041b9648 --- /dev/null +++ b/src/test/run-pass/env-vars.rs @@ -0,0 +1,22 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::env::*; + +fn main() { + for (k, v) in vars() { + let v2 = var(&k); + // MingW seems to set some funky environment variables like + // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned + // from vars() but not visible from var(). + assert!(v2.is_none() || v2.as_ref().map(|s| &**s) == Some(&*v), + "bad vars->var transition: {:?} {:?} {:?}", k, v, v2); + } +} diff --git a/src/test/run-pass/explicit-self-closures.rs b/src/test/run-pass/explicit-self-closures.rs index c7e5681c0c1..ef9dc377bc7 100644 --- a/src/test/run-pass/explicit-self-closures.rs +++ b/src/test/run-pass/explicit-self-closures.rs @@ -16,7 +16,7 @@ struct Box { impl Box { pub fn set_many(&mut self, xs: &[uint]) { - for x in xs.iter() { self.x = *x; } + for x in xs { self.x = *x; } } } diff --git a/src/test/run-pass/fn-pattern-expected-type-2.rs b/src/test/run-pass/fn-pattern-expected-type-2.rs index 8590c8b90b2..4e2c8facaf8 100644 --- a/src/test/run-pass/fn-pattern-expected-type-2.rs +++ b/src/test/run-pass/fn-pattern-expected-type-2.rs @@ -10,7 +10,7 @@ pub fn main() { let v : &[(int,int)] = &[ (1, 2), (3, 4), (5, 6) ]; - for &(x, y) in v.iter() { + for &(x, y) in v { println!("{}", y); println!("{}", x); } diff --git a/src/test/run-pass/for-destruct.rs b/src/test/run-pass/for-destruct.rs index 7cc8b22e061..7a9b8a45b2a 100644 --- a/src/test/run-pass/for-destruct.rs +++ b/src/test/run-pass/for-destruct.rs @@ -11,7 +11,7 @@ struct Pair { x: int, y: int } pub fn main() { - for elt in (vec!(Pair {x: 10, y: 20}, Pair {x: 30, y: 0})).iter() { + for elt in &(vec!(Pair {x: 10, y: 20}, Pair {x: 30, y: 0})) { assert_eq!(elt.x + elt.y, 30); } } diff --git a/src/test/run-pass/for-loop-goofiness.rs b/src/test/run-pass/for-loop-goofiness.rs index ae509dc0862..7754751120e 100644 --- a/src/test/run-pass/for-loop-goofiness.rs +++ b/src/test/run-pass/for-loop-goofiness.rs @@ -17,7 +17,7 @@ type Iterator = int; pub fn main() { let x = [ 3, 3, 3 ]; - for i in x.iter() { + for i in &x { assert_eq!(*i, 3); } } diff --git a/src/test/run-pass/for-loop-panic.rs b/src/test/run-pass/for-loop-panic.rs index d157da3139f..d2de1ed8c7e 100644 --- a/src/test/run-pass/for-loop-panic.rs +++ b/src/test/run-pass/for-loop-panic.rs @@ -9,4 +9,4 @@ // except according to those terms. -pub fn main() { let x: Vec<int> = Vec::new(); for _ in x.iter() { panic!("moop"); } } +pub fn main() { let x: Vec<int> = Vec::new(); for _ in &x { panic!("moop"); } } diff --git a/src/test/run-pass/foreach-external-iterators-break.rs b/src/test/run-pass/foreach-external-iterators-break.rs index 9cbb4f4107a..e9e8c3f0929 100644 --- a/src/test/run-pass/foreach-external-iterators-break.rs +++ b/src/test/run-pass/foreach-external-iterators-break.rs @@ -11,7 +11,7 @@ pub fn main() { let x = [1; 100]; let mut y = 0; - for i in x.iter() { + for i in &x[] { if y > 10 { break; } diff --git a/src/test/run-pass/foreach-external-iterators-hashmap-break-restart.rs b/src/test/run-pass/foreach-external-iterators-hashmap-break-restart.rs index 891cbf6696b..a4988bf016c 100644 --- a/src/test/run-pass/foreach-external-iterators-hashmap-break-restart.rs +++ b/src/test/run-pass/foreach-external-iterators-hashmap-break-restart.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; pub fn main() { let mut h = HashMap::new(); let kvs = [(1, 10), (2, 20), (3, 30)]; - for &(k,v) in kvs.iter() { + for &(k,v) in &kvs { h.insert(k,v); } let mut x = 0; diff --git a/src/test/run-pass/foreach-external-iterators-hashmap.rs b/src/test/run-pass/foreach-external-iterators-hashmap.rs index 1878997de5a..ed4328d94fe 100644 --- a/src/test/run-pass/foreach-external-iterators-hashmap.rs +++ b/src/test/run-pass/foreach-external-iterators-hashmap.rs @@ -15,12 +15,12 @@ use std::collections::HashMap; pub fn main() { let mut h = HashMap::new(); let kvs = [(1, 10), (2, 20), (3, 30)]; - for &(k,v) in kvs.iter() { + for &(k,v) in &kvs { h.insert(k,v); } let mut x = 0; let mut y = 0; - for (&k,&v) in h.iter() { + for (&k,&v) in &h { x += k; y += v; } diff --git a/src/test/run-pass/foreach-external-iterators-nested.rs b/src/test/run-pass/foreach-external-iterators-nested.rs index 75471991620..6acfbc95317 100644 --- a/src/test/run-pass/foreach-external-iterators-nested.rs +++ b/src/test/run-pass/foreach-external-iterators-nested.rs @@ -13,8 +13,8 @@ pub fn main() { let y = [2; 100]; let mut p = 0; let mut q = 0; - for i in x.iter() { - for j in y.iter() { + for i in &x[] { + for j in &y[] { p += *j; } q += *i + p; diff --git a/src/test/run-pass/foreach-external-iterators.rs b/src/test/run-pass/foreach-external-iterators.rs index ef4692b2b51..2f154be659d 100644 --- a/src/test/run-pass/foreach-external-iterators.rs +++ b/src/test/run-pass/foreach-external-iterators.rs @@ -11,7 +11,7 @@ pub fn main() { let x = [1; 100]; let mut y = 0; - for i in x.iter() { + for i in &x[] { y += *i } assert!(y == 100); diff --git a/src/test/run-pass/generic-static-methods.rs b/src/test/run-pass/generic-static-methods.rs index 90a6349385d..7f84efcdd5d 100644 --- a/src/test/run-pass/generic-static-methods.rs +++ b/src/test/run-pass/generic-static-methods.rs @@ -16,7 +16,7 @@ trait vec_utils<T> { impl<T> vec_utils<T> for Vec<T> { fn map_<U, F>(x: &Vec<T> , mut f: F) -> Vec<U> where F: FnMut(&T) -> U { let mut r = Vec::new(); - for elt in x.iter() { + for elt in x { r.push(f(elt)); } r diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index 0e82ad43782..651ac632439 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -35,7 +35,7 @@ mod map_reduce { enum ctrl_proto { find_reducer(Vec<u8>, Sender<int>), mapper_done, } fn start_mappers(ctrl: Sender<ctrl_proto>, inputs: Vec<String>) { - for i in inputs.iter() { + for i in &inputs { let ctrl = ctrl.clone(); let i = i.clone(); Thread::spawn(move|| map_task(ctrl.clone(), i.clone()) ); diff --git a/src/test/run-pass/intrinsic-alignment.rs b/src/test/run-pass/intrinsic-alignment.rs index da07e9594c0..07f021e48d7 100644 --- a/src/test/run-pass/intrinsic-alignment.rs +++ b/src/test/run-pass/intrinsic-alignment.rs @@ -20,7 +20,8 @@ mod rusti { #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] mod m { #[main] #[cfg(target_arch = "x86")] diff --git a/src/test/run-pass/issue-10396.rs b/src/test/run-pass/issue-10396.rs index 7095812ce4b..b487608d4e6 100644 --- a/src/test/run-pass/issue-10396.rs +++ b/src/test/run-pass/issue-10396.rs @@ -14,7 +14,7 @@ enum Foo<'s> { } fn f(arr: &[&Foo]) { - for &f in arr.iter() { + for &f in arr { println!("{:?}", f); } } diff --git a/src/test/run-pass/issue-17068.rs b/src/test/run-pass/issue-17068.rs index dfbe7406229..a0e6f2c9be9 100644 --- a/src/test/run-pass/issue-17068.rs +++ b/src/test/run-pass/issue-17068.rs @@ -11,7 +11,7 @@ // Test that regionck creates the right region links in the pattern // binding of a for loop fn foo<'a>(v: &'a [uint]) -> &'a uint { - for &ref x in v.iter() { return x; } + for &ref x in v { return x; } unreachable!() } diff --git a/src/test/run-pass/issue-20454.rs b/src/test/run-pass/issue-20454.rs new file mode 100644 index 00000000000..fbc4cca8008 --- /dev/null +++ b/src/test/run-pass/issue-20454.rs @@ -0,0 +1,19 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::thread; + +fn main() { + thread::Thread::spawn(move || { // no need for -> () + loop { + println!("hello"); + } + }); +} diff --git a/src/test/run-pass/issue-21296.rs b/src/test/run-pass/issue-21296.rs new file mode 100644 index 00000000000..f91fb064ae2 --- /dev/null +++ b/src/test/run-pass/issue-21296.rs @@ -0,0 +1,15 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[forbid(raw_pointer_derive)] +#[derive(Copy)] +struct Test(*const i32); + +fn main() {} diff --git a/src/test/run-pass/issue-21634.rs b/src/test/run-pass/issue-21634.rs new file mode 100644 index 00000000000..e5a2790917f --- /dev/null +++ b/src/test/run-pass/issue-21634.rs @@ -0,0 +1,22 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + +fn main() { + if let Ok(x) = "3.1415".parse() { + assert_eq!(false, x <= 0.0); + } + if let Ok(x) = "3.1415".parse() { + assert_eq!(3.1415, x + 0.0); + } + if let Ok(mut x) = "3.1415".parse() { + assert_eq!(8.1415, { x += 5.0; x }); + } +} diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index 8a67d84cb64..b55f3691358 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -66,12 +66,12 @@ fn read_board_grid<rdr:'static + old_io::Reader>(mut input: rdr) let mut line = [0; 10]; input.read(&mut line); let mut row = Vec::new(); - for c in line.iter() { + for c in &line { row.push(square_from_char(*c as char)) } grid.push(row); let width = grid[0].len(); - for row in grid.iter() { assert!(row.len() == width) } + for row in &grid { assert!(row.len() == width) } grid } diff --git a/src/test/run-pass/issue-3389.rs b/src/test/run-pass/issue-3389.rs index 8f6b8137199..26558bdd30c 100644 --- a/src/test/run-pass/issue-3389.rs +++ b/src/test/run-pass/issue-3389.rs @@ -15,7 +15,7 @@ struct trie_node { } fn print_str_vector(vector: Vec<String> ) { - for string in vector.iter() { + for string in &vector { println!("{}", *string); } } diff --git a/src/test/run-pass/issue-3563-2.rs b/src/test/run-pass/issue-3563-2.rs index e688b95f873..2cf29296b85 100644 --- a/src/test/run-pass/issue-3563-2.rs +++ b/src/test/run-pass/issue-3563-2.rs @@ -11,7 +11,7 @@ trait Canvas { fn add_point(&self, point: &int); fn add_points(&self, shapes: &[int]) { - for pt in shapes.iter() { + for pt in shapes { self.add_point(pt) } } diff --git a/src/test/run-pass/issue-3563-3.rs b/src/test/run-pass/issue-3563-3.rs index 426a8ccf7e7..5d02a1b2bd2 100644 --- a/src/test/run-pass/issue-3563-3.rs +++ b/src/test/run-pass/issue-3563-3.rs @@ -122,7 +122,7 @@ trait Canvas { // Unlike interfaces traits support default implementations. // Got an ICE as soon as I added this method. fn add_points(&mut self, shapes: &[Point]) { - for pt in shapes.iter() {self.add_point(*pt)}; + for pt in shapes {self.add_point(*pt)}; } } diff --git a/src/test/run-pass/issue-4241.rs b/src/test/run-pass/issue-4241.rs index 19622cb88e3..89cf2f69b34 100644 --- a/src/test/run-pass/issue-4241.rs +++ b/src/test/run-pass/issue-4241.rs @@ -100,7 +100,7 @@ priv fn cmd_to_string(cmd: ~[String]) -> String { let mut res = "*".to_string(); res.push_str(cmd.len().to_string()); res.push_str("\r\n"); - for s in cmd.iter() { + for s in &cmd { res.push_str(["$".to_string(), s.len().to_string(), "\r\n".to_string(), (*s).clone(), "\r\n".to_string()].concat() ); } diff --git a/src/test/run-pass/issue-4542.rs b/src/test/run-pass/issue-4542.rs index 024ee8c6dfe..ae72de50d26 100644 --- a/src/test/run-pass/issue-4542.rs +++ b/src/test/run-pass/issue-4542.rs @@ -11,7 +11,7 @@ use std::os; pub fn main() { - for arg in os::args().iter() { + for arg in &os::args() { match (*arg).clone() { _s => { } } diff --git a/src/test/run-pass/issue-5666.rs b/src/test/run-pass/issue-5666.rs index e53f4c86923..4f304e3b436 100644 --- a/src/test/run-pass/issue-5666.rs +++ b/src/test/run-pass/issue-5666.rs @@ -31,7 +31,7 @@ pub fn main() { let bubbles = box Dog{name: "bubbles".to_string()}; let barker = [snoopy as Box<Barks>, bubbles as Box<Barks>]; - for pup in barker.iter() { + for pup in &barker { println!("{}", pup.bark()); } } diff --git a/src/test/run-pass/issue-5688.rs b/src/test/run-pass/issue-5688.rs index a4f39884846..9612c4bf181 100644 --- a/src/test/run-pass/issue-5688.rs +++ b/src/test/run-pass/issue-5688.rs @@ -23,7 +23,7 @@ struct X { vec: &'static [int] } static V: &'static [X] = &[X { vec: &[1, 2, 3] }]; pub fn main() { - for &v in V.iter() { + for &v in V { println!("{:?}", v.vec); } } diff --git a/src/test/run-pass/lang-item-public.rs b/src/test/run-pass/lang-item-public.rs index f94f6482759..2d70fa0c819 100644 --- a/src/test/run-pass/lang-item-public.rs +++ b/src/test/run-pass/lang-item-public.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -37,6 +37,10 @@ extern {} #[link(name = "c")] extern {} +#[cfg(target_os = "openbsd")] +#[link(name = "c")] +extern {} + #[cfg(target_os = "macos")] #[link(name = "System")] extern {} diff --git a/src/test/run-pass/linear-for-loop.rs b/src/test/run-pass/linear-for-loop.rs index eda14222e91..22a29279a67 100644 --- a/src/test/run-pass/linear-for-loop.rs +++ b/src/test/run-pass/linear-for-loop.rs @@ -13,7 +13,7 @@ pub fn main() { let x = vec!(1, 2, 3); let mut y = 0; - for i in x.iter() { println!("{}", *i); y += *i; } + for i in &x { println!("{}", *i); y += *i; } println!("{}", y); assert_eq!(y, 6); let s = "hello there".to_string(); diff --git a/src/test/run-pass/loop-label-shadowing.rs b/src/test/run-pass/loop-label-shadowing.rs index cfe51fe7758..686a9a002ce 100644 --- a/src/test/run-pass/loop-label-shadowing.rs +++ b/src/test/run-pass/loop-label-shadowing.rs @@ -12,7 +12,7 @@ fn main() { let mut foo = Vec::new(); - 'foo: for i in [1, 2, 3].iter() { + 'foo: for i in &[1, 2, 3] { foo.push(i); } } diff --git a/src/test/run-pass/loop-scope.rs b/src/test/run-pass/loop-scope.rs index 1dc3700194c..88711a46059 100644 --- a/src/test/run-pass/loop-scope.rs +++ b/src/test/run-pass/loop-scope.rs @@ -11,6 +11,6 @@ pub fn main() { let x = vec!(10, 20, 30); let mut sum = 0; - for x in x.iter() { sum += *x; } + for x in &x { sum += *x; } assert_eq!(sum, 60); } diff --git a/src/test/run-pass/monad.rs b/src/test/run-pass/monad.rs index acd8078b1f4..457c0a35fd7 100644 --- a/src/test/run-pass/monad.rs +++ b/src/test/run-pass/monad.rs @@ -17,7 +17,7 @@ trait vec_monad<A> { impl<A> vec_monad<A> for Vec<A> { fn bind<B, F>(&self, mut f: F) -> Vec<B> where F: FnMut(&A) -> Vec<B> { let mut r = Vec::new(); - for elt in self.iter() { + for elt in self { r.extend(f(elt).into_iter()); } r diff --git a/src/test/run-pass/mutability-inherits-through-fixed-length-vec.rs b/src/test/run-pass/mutability-inherits-through-fixed-length-vec.rs index 7d6bbbe4240..e074c3fb3d7 100644 --- a/src/test/run-pass/mutability-inherits-through-fixed-length-vec.rs +++ b/src/test/run-pass/mutability-inherits-through-fixed-length-vec.rs @@ -16,8 +16,8 @@ fn test1() { fn test2() { let mut ints = [0; 32]; - for i in ints.iter_mut() { *i += 22; } - for i in ints.iter() { assert!(*i == 22); } + for i in &mut ints { *i += 22; } + for i in &ints { assert!(*i == 22); } } pub fn main() { diff --git a/src/test/run-pass/overloaded-index-assoc-list.rs b/src/test/run-pass/overloaded-index-assoc-list.rs index 7e3ff198c43..0064748e883 100644 --- a/src/test/run-pass/overloaded-index-assoc-list.rs +++ b/src/test/run-pass/overloaded-index-assoc-list.rs @@ -32,7 +32,7 @@ impl<K: PartialEq + std::fmt::Debug, V:Clone> Index<K> for AssociationList<K,V> type Output = V; fn index<'a>(&'a self, index: &K) -> &'a V { - for pair in self.pairs.iter() { + for pair in &self.pairs { if pair.key == *index { return &pair.value } diff --git a/src/test/run-pass/packed-struct-vec.rs b/src/test/run-pass/packed-struct-vec.rs index 847688ce045..ede94acd934 100644 --- a/src/test/run-pass/packed-struct-vec.rs +++ b/src/test/run-pass/packed-struct-vec.rs @@ -28,7 +28,7 @@ pub fn main() { assert_eq!(foos[i], Foo { bar: 1, baz: 2}); } - for &foo in foos.iter() { + for &foo in &foos { assert_eq!(foo, Foo { bar: 1, baz: 2 }); } } diff --git a/src/test/run-pass/rec-align-u64.rs b/src/test/run-pass/rec-align-u64.rs index eaf76ef5714..5330490e54f 100644 --- a/src/test/run-pass/rec-align-u64.rs +++ b/src/test/run-pass/rec-align-u64.rs @@ -39,7 +39,8 @@ struct Outer { #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", - target_os = "dragonfly"))] + target_os = "dragonfly", + target_os = "openbsd"))] mod m { #[cfg(target_arch = "x86")] pub mod m { diff --git a/src/test/run-pass/regions-mock-tcx.rs b/src/test/run-pass/regions-mock-tcx.rs index 34ff7acfca4..be7db25201a 100644 --- a/src/test/run-pass/regions-mock-tcx.rs +++ b/src/test/run-pass/regions-mock-tcx.rs @@ -66,7 +66,7 @@ impl<'tcx,'ast> TypeContext<'tcx, 'ast> { } fn add_type(&mut self, s: TypeStructure<'tcx>) -> Type<'tcx> { - for &ty in self.types.iter() { + for &ty in &self.types { if *ty == s { return ty; } diff --git a/src/test/run-pass/repeated-vector-syntax.rs b/src/test/run-pass/repeated-vector-syntax.rs index 6048e0d8673..6a1384ff933 100644 --- a/src/test/run-pass/repeated-vector-syntax.rs +++ b/src/test/run-pass/repeated-vector-syntax.rs @@ -13,7 +13,7 @@ pub fn main() { let y = [ 0; 1 ]; print!("["); - for xi in x.iter() { + for xi in &x[] { print!("{:?}, ", &xi[]); } println!("]"); diff --git a/src/test/run-pass/shadow.rs b/src/test/run-pass/shadow.rs index dbe73d1b94a..6e03c1e4a80 100644 --- a/src/test/run-pass/shadow.rs +++ b/src/test/run-pass/shadow.rs @@ -15,7 +15,7 @@ fn foo(c: Vec<int> ) { match t::none::<int> { t::some::<int>(_) => { - for _i in c.iter() { + for _i in &c { println!("{}", a); let a = 17; b.push(a); diff --git a/src/test/run-pass/static-impl.rs b/src/test/run-pass/static-impl.rs index 44d77e440d1..ff37ccb81ed 100644 --- a/src/test/run-pass/static-impl.rs +++ b/src/test/run-pass/static-impl.rs @@ -47,10 +47,10 @@ trait vec_utils<T> { impl<T> vec_utils<T> for Vec<T> { fn length_(&self) -> uint { self.len() } - fn iter_<F>(&self, mut f: F) where F: FnMut(&T) { for x in self.iter() { f(x); } } + fn iter_<F>(&self, mut f: F) where F: FnMut(&T) { for x in self { f(x); } } fn map_<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U { let mut r = Vec::new(); - for elt in self.iter() { + for elt in self { r.push(f(elt)); } r diff --git a/src/test/run-pass/task-comm-3.rs b/src/test/run-pass/task-comm-3.rs index 306cc0ffcef..90282946838 100644 --- a/src/test/run-pass/task-comm-3.rs +++ b/src/test/run-pass/task-comm-3.rs @@ -51,7 +51,7 @@ fn test00() { // Read from spawned tasks... let mut sum = 0; - for _r in results.iter() { + for _r in &results { i = 0; while i < number_of_messages { let value = rx.recv().unwrap(); @@ -61,7 +61,7 @@ fn test00() { } // Join spawned tasks... - for r in results.into_iter() { r.join(); } + for r in results { r.join(); } println!("Completed: Final number is: "); println!("{}", sum); diff --git a/src/test/run-pass/tcp-stress.rs b/src/test/run-pass/tcp-stress.rs index f5f013d1711..e0527c35871 100644 --- a/src/test/run-pass/tcp-stress.rs +++ b/src/test/run-pass/tcp-stress.rs @@ -1,4 +1,4 @@ -// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -10,6 +10,7 @@ // ignore-linux see joyent/libuv#1189 // ignore-android needs extra network permissions +// ignore-openbsd system ulimit (Too many open files) // exec-env:RUST_LOG=debug #[macro_use] diff --git a/src/test/run-pass/trait-bounds-in-arc.rs b/src/test/run-pass/trait-bounds-in-arc.rs index 0089646d0a1..0b650d97e4f 100644 --- a/src/test/run-pass/trait-bounds-in-arc.rs +++ b/src/test/run-pass/trait-bounds-in-arc.rs @@ -97,20 +97,20 @@ pub fn main() { fn check_legs(arc: Arc<Vec<Box<Pet+Sync+Send>>>) { let mut legs = 0; - for pet in arc.iter() { + for pet in &*arc { legs += pet.num_legs(); } assert!(legs == 12); } fn check_names(arc: Arc<Vec<Box<Pet+Sync+Send>>>) { - for pet in arc.iter() { + for pet in &*arc { pet.name(box |name| { assert!(name.as_bytes()[0] == 'a' as u8 && name.as_bytes()[1] == 'l' as u8); }) } } fn check_pedigree(arc: Arc<Vec<Box<Pet+Sync+Send>>>) { - for pet in arc.iter() { + for pet in &*arc { assert!(pet.of_good_pedigree()); } } diff --git a/src/test/run-pass/trait-generic.rs b/src/test/run-pass/trait-generic.rs index e79b22f70cf..5f4b18df6e1 100644 --- a/src/test/run-pass/trait-generic.rs +++ b/src/test/run-pass/trait-generic.rs @@ -29,7 +29,7 @@ trait map<T> { impl<T> map<T> for Vec<T> { fn map<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U { let mut r = Vec::new(); - for i in self.iter() { + for i in self { r.push(f(i)); } r diff --git a/src/test/run-pass/unboxed-closures-counter-not-moved.rs b/src/test/run-pass/unboxed-closures-counter-not-moved.rs index e921f0c723e..0b85916d224 100644 --- a/src/test/run-pass/unboxed-closures-counter-not-moved.rs +++ b/src/test/run-pass/unboxed-closures-counter-not-moved.rs @@ -21,7 +21,7 @@ fn main() { call(|| { // Move `y`, but do not move `counter`, even though it is read // by value (note that it is also mutated). - for item in y.into_iter() { + for item in y { let v = counter; counter += v; } diff --git a/src/test/run-pass/unboxed-closures-move-some-upvars-in-by-ref-closure.rs b/src/test/run-pass/unboxed-closures-move-some-upvars-in-by-ref-closure.rs index 9534ee6fa12..99663646254 100644 --- a/src/test/run-pass/unboxed-closures-move-some-upvars-in-by-ref-closure.rs +++ b/src/test/run-pass/unboxed-closures-move-some-upvars-in-by-ref-closure.rs @@ -22,7 +22,7 @@ fn main() { // Here: `x` must be captured with a mutable reference in // order for us to append on it, and `y` must be captured by // value. - for item in y.into_iter() { + for item in y { x.push(item); } }); diff --git a/src/test/run-pass/vector-sort-panic-safe.rs b/src/test/run-pass/vector-sort-panic-safe.rs index aaefbc42d70..9d83c0b0079 100644 --- a/src/test/run-pass/vector-sort-panic-safe.rs +++ b/src/test/run-pass/vector-sort-panic-safe.rs @@ -73,7 +73,7 @@ pub fn main() { // ... and then panic on each and every single one. for panic_countdown in 0..count { // refresh the counters. - for c in drop_counts.iter() { + for c in &drop_counts { c.store(0, Ordering::Relaxed); } diff --git a/src/test/run-pass/x86stdcall.rs b/src/test/run-pass/x86stdcall.rs index 15d18525d0a..75a8f6019b8 100644 --- a/src/test/run-pass/x86stdcall.rs +++ b/src/test/run-pass/x86stdcall.rs @@ -1,4 +1,4 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -34,5 +34,6 @@ pub fn main() { target_os = "linux", target_os = "freebsd", target_os = "dragonfly", + target_os = "openbsd", target_os = "android"))] pub fn main() { } |
