diff options
| author | Jeremy Soller <jackpot51@gmail.com> | 2016-11-03 08:52:48 -0600 |
|---|---|---|
| committer | Jeremy Soller <jackpot51@gmail.com> | 2016-11-03 08:52:48 -0600 |
| commit | 74dc845c2de24924f143e345358103102c9f8ed5 (patch) | |
| tree | d6ce59e7b1dec09d462b9a215393ceeac7cf618e | |
| parent | 123d08b3d3901d5725af8303c1329b007089cde5 (diff) | |
| parent | ac919fcd9d4a958baf99b2f2ed5c3d38a2ebf9d0 (diff) | |
| download | rust-74dc845c2de24924f143e345358103102c9f8ed5.tar.gz rust-74dc845c2de24924f143e345358103102c9f8ed5.zip | |
Merge branch 'master' into redox
299 files changed, 2972 insertions, 1276 deletions
diff --git a/.travis.yml b/.travis.yml index c5d8a94f39b..0bc9a4ad419 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,7 +15,7 @@ before_install: script: - docker run -v `pwd`:/build rust sh -c " - ./configure --enable-rustbuild --llvm-root=/usr/lib/llvm-3.7 && + ./configure --enable-rustbuild --llvm-root=/usr/lib/llvm-3.7 --enable-quiet-tests && make tidy && make check -j4 " diff --git a/configure b/configure index 2bc8c72e3ea..cd22229b799 100755 --- a/configure +++ b/configure @@ -507,11 +507,16 @@ case $CFG_CPUTYPE in CFG_CPUTYPE=arm ;; - armv7l) + armv6l) CFG_CPUTYPE=arm CFG_OSTYPE="${CFG_OSTYPE}eabihf" ;; + armv7l) + CFG_CPUTYPE=armv7 + CFG_OSTYPE="${CFG_OSTYPE}eabihf" + ;; + aarch64) CFG_CPUTYPE=aarch64 ;; @@ -610,6 +615,7 @@ opt docs 1 "build standard library documentation" opt compiler-docs 0 "build compiler documentation" opt optimize-tests 1 "build tests with optimizations" opt debuginfo-tests 0 "build tests with debugger metadata" +opt quiet-tests 0 "enable quieter output when running tests" opt libcpp 1 "build llvm with libc++ instead of libstdc++ when using clang" opt llvm-assertions 0 "build LLVM with assertions" opt debug-assertions 0 "build with debugging assertions" diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs index af76a49fed0..0a281b89c57 100644 --- a/src/bootstrap/check.rs +++ b/src/bootstrap/check.rs @@ -187,6 +187,10 @@ pub fn compiletest(build: &Build, cmd.arg("--verbose"); } + if build.config.quiet_tests { + cmd.arg("--quiet"); + } + // Only pass correct values for these flags for the `run-make` suite as it // requires that a C++ compiler was configured which isn't always the case. if suite == "run-make" { @@ -277,7 +281,13 @@ fn markdown_test(build: &Build, compiler: &Compiler, markdown: &Path) { build.add_rustc_lib_path(compiler, &mut cmd); cmd.arg("--test"); cmd.arg(markdown); - cmd.arg("--test-args").arg(build.flags.args.join(" ")); + + let mut test_args = build.flags.args.join(" "); + if build.config.quiet_tests { + test_args.push_str(" --quiet"); + } + cmd.arg("--test-args").arg(test_args); + build.run(&mut cmd); } @@ -367,6 +377,11 @@ pub fn krate(build: &Build, dylib_path.insert(0, build.sysroot_libdir(compiler, target)); cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap()); + if build.config.quiet_tests { + cargo.arg("--"); + cargo.arg("--quiet"); + } + if target.contains("android") { build.run(cargo.arg("--no-run")); krate_android(build, compiler, target, mode); diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 8c0ad1ccf82..abaa9389d80 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -77,6 +77,7 @@ pub struct Config { // misc pub channel: String, + pub quiet_tests: bool, // Fallback musl-root for all targets pub musl_root: Option<PathBuf>, pub prefix: Option<String>, @@ -338,6 +339,7 @@ impl Config { ("RPATH", self.rust_rpath), ("OPTIMIZE_TESTS", self.rust_optimize_tests), ("DEBUGINFO_TESTS", self.rust_debuginfo_tests), + ("QUIET_TESTS", self.quiet_tests), ("LOCAL_REBUILD", self.local_rebuild), ("NINJA", self.ninja), ("CODEGEN_TESTS", self.codegen_tests), diff --git a/src/doc/book/closures.md b/src/doc/book/closures.md index 3ed85c1a90b..b7b67a9f1d0 100644 --- a/src/doc/book/closures.md +++ b/src/doc/book/closures.md @@ -510,12 +510,11 @@ fn factory() -> Box<Fn(i32) -> i32> { Box::new(|x| x + num) } -# fn main() { + let f = factory(); let answer = f(1); assert_eq!(6, answer); -# } ``` There’s just one last problem: @@ -540,12 +539,11 @@ fn factory() -> Box<Fn(i32) -> i32> { Box::new(move |x| x + num) } -fn main() { + let f = factory(); let answer = f(1); assert_eq!(6, answer); -} ``` By making the inner closure a `move Fn`, we create a new stack frame for our diff --git a/src/doc/book/guessing-game.md b/src/doc/book/guessing-game.md index 4e0e3728689..a3ab4803bc4 100644 --- a/src/doc/book/guessing-game.md +++ b/src/doc/book/guessing-game.md @@ -362,7 +362,6 @@ numbers. A bare number like above is actually shorthand for `^0.3.0`, meaning "anything compatible with 0.3.0". If we wanted to use only `0.3.0` exactly, we could say `rand="=0.3.0"` (note the two equal signs). -And if we wanted to use the latest version we could use `rand="*"`. We could also use a range of versions. [Cargo’s documentation][cargodoc] contains more details. diff --git a/src/doc/book/testing.md b/src/doc/book/testing.md index 3bdf1b7b7f2..0e6cdb8f09d 100644 --- a/src/doc/book/testing.md +++ b/src/doc/book/testing.md @@ -24,9 +24,11 @@ Cargo will automatically generate a simple test when you make a new project. Here's the contents of `src/lib.rs`: ```rust -# fn main() {} -#[test] -fn it_works() { +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + } } ``` @@ -36,11 +38,11 @@ currently has no body. That's good enough to pass! We can run the tests with ```bash $ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a + Compiling adder v0.1.0 (file:///home/you/projects/adder) + Running target/debug/deps/adder-91b3e234d4ed382a running 1 test -test it_works ... ok +test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured @@ -56,7 +58,7 @@ for the test we wrote, and another for documentation tests. We'll talk about those later. For now, see this line: ```text -test it_works ... ok +test tests::it_works ... ok ``` Note the `it_works`. This comes from the name of our function: @@ -89,31 +91,30 @@ run our tests again: ```bash $ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a + Compiling adder v0.1.0 (file:///home/you/projects/adder) + Running target/debug/deps/adder-91b3e234d4ed382a running 1 test -test it_works ... FAILED +test tests::it_works ... FAILED failures: ----- it_works stdout ---- - thread 'it_works' panicked at 'assertion failed: false', /home/steve/tmp/adder/src/lib.rs:3 - +---- test::it_works stdout ---- + thread 'tests::it_works' panicked at 'assertion failed: false', src/lib.rs:5 failures: - it_works + tests::it_works test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured -thread 'main' panicked at 'Some tests failed', /home/steve/src/rust/src/libtest/lib.rs:247 +error: test failed ``` Rust indicates that our test failed: ```text -test it_works ... FAILED +test tests::it_works ... FAILED ``` And that's reflected in the summary line: @@ -159,11 +160,11 @@ This test will now succeed if we `panic!` and fail if we complete. Let's try it: ```bash $ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a + Compiling adder v0.1.0 (file:///home/you/projects/adder) + Running target/debug/deps/adder-91b3e234d4ed382a running 1 test -test it_works ... ok +test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured @@ -191,11 +192,11 @@ passes: ```bash $ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a + Compiling adder v0.1.0 (file:///home/you/projects/adder) + Running target/debug/deps/adder-91b3e234d4ed382a running 1 test -test it_works ... ok +test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured @@ -262,8 +263,8 @@ not: ```bash $ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a + Compiling adder v0.1.0 (file:///home/you/projects/adder) + Running target/debug/deps/adder-91b3e234d4ed382a running 2 tests test expensive_test ... ignored @@ -282,7 +283,7 @@ The expensive tests can be run explicitly using `cargo test -- --ignored`: ```bash $ cargo test -- --ignored - Running target/adder-91b3e234d4ed382a + Running target/debug/deps/adder-91b3e234d4ed382a running 1 test test expensive_test ... ok @@ -302,8 +303,11 @@ which is why the command is `cargo test -- --ignored`. # The `tests` module There is one way in which our existing example is not idiomatic: it's -missing the `tests` module. The idiomatic way of writing our example -looks like this: +missing the `tests` module. You might have noticed this test module was +present in the code that was initially generated with `cargo new` but +was missing from our last example. Let's explain what this does. + +The idiomatic way of writing our example looks like this: ```rust,ignore # fn main() {} @@ -356,8 +360,8 @@ Note the different `use` line. Now we run our tests: ```bash $ cargo test Updating registry `https://github.com/rust-lang/crates.io-index` - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a + Compiling adder v0.1.0 (file:///home/you/projects/adder) + Running target/debug/deps/adder-91b3e234d4ed382a running 1 test test tests::it_works ... ok @@ -404,15 +408,15 @@ Let's run them: ```bash $ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a + Compiling adder v0.1.0 (file:///home/you/projects/adder) + Running target/debug/deps/adder-91b3e234d4ed382a running 1 test test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - Running target/lib-c18e7d3494509e74 + Running target/debug/integration_test-68064b69521c828a running 1 test test it_works ... ok @@ -490,15 +494,15 @@ Let's run the tests again: ```bash $ cargo test - Compiling adder v0.0.1 (file:///home/steve/tmp/adder) - Running target/adder-91b3e234d4ed382a + Compiling adder v0.1.0. (file:///home/you/projects/adder) + Running target/debug/deps/adder-91b3e234d4ed382a running 1 test test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - Running target/lib-c18e7d3494509e74 + Running target/debug/integration_test-68064b69521c828a running 1 test test it_works ... ok diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 245579afbba..75796cf94bf 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -1170,7 +1170,7 @@ impl<T> [T] { /// let x = s.into_vec(); /// // `s` cannot be used anymore because it has been converted into `x`. /// - /// assert_eq!(x, vec!(10, 40, 30)); + /// assert_eq!(x, vec![10, 40, 30]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 7fdf7e903d5..d94a27917e8 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -148,7 +148,7 @@ use super::range::RangeArgument; /// [`Index`] trait. An example will be more explicit: /// /// ``` -/// let v = vec!(0, 2, 4, 6); +/// let v = vec![0, 2, 4, 6]; /// println!("{}", v[1]); // it will display '2' /// ``` /// @@ -156,7 +156,7 @@ use super::range::RangeArgument; /// your software will panic! You cannot do this: /// /// ```ignore -/// let v = vec!(0, 2, 4, 6); +/// let v = vec![0, 2, 4, 6]; /// println!("{}", v[6]); // it will panic! /// ``` /// @@ -173,7 +173,7 @@ use super::range::RangeArgument; /// // ... /// } /// -/// let v = vec!(0, 1); +/// let v = vec![0, 1]; /// read_slice(&v); /// /// // ... and that's all! diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index e0f976e4161..0daf658a0f4 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -248,6 +248,80 @@ impl Ordering { Greater => Less, } } + + /// Chains two orderings. + /// + /// Returns `self` when it's not `Equal`. Otherwise returns `other`. + /// # Examples + /// + /// ``` + /// #![feature(ordering_chaining)] + /// + /// use std::cmp::Ordering; + /// + /// let result = Ordering::Equal.then(Ordering::Less); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Less.then(Ordering::Equal); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Less.then(Ordering::Greater); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Equal.then(Ordering::Equal); + /// assert_eq!(result, Ordering::Equal); + /// + /// let x: (i64, i64, i64) = (1, 2, 7); + /// let y: (i64, i64, i64) = (1, 5, 3); + /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2)); + /// + /// assert_eq!(result, Ordering::Less); + /// ``` + #[unstable(feature = "ordering_chaining", issue = "37053")] + pub fn then(self, other: Ordering) -> Ordering { + match self { + Equal => other, + _ => self, + } + } + + /// Chains the ordering with the given function. + /// + /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns + /// the result. + /// + /// # Examples + /// + /// ``` + /// #![feature(ordering_chaining)] + /// + /// use std::cmp::Ordering; + /// + /// let result = Ordering::Equal.then_with(|| Ordering::Less); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Less.then_with(|| Ordering::Equal); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Less.then_with(|| Ordering::Greater); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Equal.then_with(|| Ordering::Equal); + /// assert_eq!(result, Ordering::Equal); + /// + /// let x: (i64, i64, i64) = (1, 2, 7); + /// let y: (i64, i64, i64) = (1, 5, 3); + /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2)); + /// + /// assert_eq!(result, Ordering::Less); + /// ``` + #[unstable(feature = "ordering_chaining", issue = "37053")] + pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering { + match self { + Equal => f(), + _ => self, + } + } } /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order). diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index 5f16a4f2435..830bbc079ad 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -145,7 +145,7 @@ pub trait AsMut<T: ?Sized> { /// /// # Generic Impls /// -/// - `[From<T>][From] for U` implies `Into<U> for T` +/// - [`From<T>`][From]` for U` implies `Into<U> for T` /// - [`into()`] is reflexive, which means that `Into<T> for T` is implemented /// /// [`TryInto`]: trait.TryInto.html @@ -178,14 +178,14 @@ pub trait Into<T>: Sized { /// ``` /// # Generic impls /// -/// - `From<T> for U` implies `[Into<U>] for T` +/// - `From<T> for U` implies [`Into<U>`]` for T` /// - [`from()`] is reflexive, which means that `From<T> for T` is implemented /// /// [`TryFrom`]: trait.TryFrom.html /// [`Option<T>`]: ../../std/option/enum.Option.html /// [`Result<T, E>`]: ../../std/result/enum.Result.html /// [`String`]: ../../std/string/struct.String.html -/// [Into<U>]: trait.Into.html +/// [`Into<U>`]: trait.Into.html /// [`from()`]: trait.From.html#tymethod.from #[stable(feature = "rust1", since = "1.0.0")] pub trait From<T>: Sized { diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index e6c3f549ec8..cae46a0dd0f 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -42,12 +42,13 @@ macro_rules! panic { /// Unsafe code relies on `assert!` to enforce run-time invariants that, if /// violated could lead to unsafety. /// -/// Other use-cases of `assert!` include -/// [testing](https://doc.rust-lang.org/book/testing.html) and enforcing -/// run-time invariants in safe code (whose violation cannot result in unsafety). +/// Other use-cases of `assert!` include [testing] and enforcing run-time +/// invariants in safe code (whose violation cannot result in unsafety). /// /// This macro has a second version, where a custom panic message can be provided. /// +/// [testing]: ../book/testing.html +/// /// # Examples /// /// ``` @@ -316,26 +317,27 @@ macro_rules! try { /// Write formatted data into a buffer /// -/// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list -/// of arguments to format. +/// This macro accepts a 'writer' (any value with a `write_fmt` method), a format string, and a +/// list of arguments to format. /// -/// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or -/// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'. +/// The `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] +/// or [`std::io::Write`][io_write] traits. The term 'writer' refers to an implementation of one of +/// these two traits. /// /// Passed arguments will be formatted according to the specified format string and the resulting /// string will be passed to the writer. /// /// See [`std::fmt`][fmt] for more information on format syntax. /// -/// Return value is completely dependent on the 'write_fmt' method. +/// `write!` returns whatever the 'write_fmt' method returns. /// -/// Common return values are: [`Result`][enum_result], [`io::Result`][type_result] +/// Common return values include: [`fmt::Result`][fmt_result], [`io::Result`][io_result] /// /// [fmt]: ../std/fmt/index.html /// [fmt_write]: ../std/fmt/trait.Write.html /// [io_write]: ../std/io/trait.Write.html -/// [enum_result]: ../std/result/enum.Result.html -/// [type_result]: ../std/io/type.Result.html +/// [fmt_result]: ../std/fmt/type.Result.html +/// [io_result]: ../std/io/type.Result.html /// /// # Examples /// @@ -354,31 +356,32 @@ macro_rules! write { ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*))) } -/// Write formatted data into a buffer, with appending a newline. +/// Write formatted data into a buffer, with a newline appended. /// /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone /// (no additional CARRIAGE RETURN (`\r`/`U+000D`). /// -/// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list -/// of arguments to format. +/// This macro accepts a 'writer' (any value with a `write_fmt` method), a format string, and a +/// list of arguments to format. /// -/// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or -/// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'. +/// The `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] +/// or [`std::io::Write`][io_write] traits. The term 'writer' refers to an implementation of one of +/// these two traits. /// /// Passed arguments will be formatted according to the specified format string and the resulting -/// string will be passed to the writer. +/// string will be passed to the writer, along with the appended newline. /// /// See [`std::fmt`][fmt] for more information on format syntax. /// -/// Return value is completely dependent on the 'write_fmt' method. +/// `write!` returns whatever the 'write_fmt' method returns. /// -/// Common return values are: [`Result`][enum_result], [`io::Result`][type_result] +/// Common return values include: [`fmt::Result`][fmt_result], [`io::Result`][io_result] /// /// [fmt]: ../std/fmt/index.html /// [fmt_write]: ../std/fmt/trait.Write.html /// [io_write]: ../std/io/trait.Write.html -/// [enum_result]: ../std/result/enum.Result.html -/// [type_result]: ../std/io/type.Result.html +/// [fmt_result]: ../std/fmt/type.Result.html +/// [io_result]: ../std/io/type.Result.html /// /// # Examples /// diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs index 03d8af1563d..bdb0dd8e7d1 100644 --- a/src/libcore/marker.rs +++ b/src/libcore/marker.rs @@ -241,8 +241,8 @@ pub trait Unsize<T: ?Sized> { /// compile-time error. Specifically, with structs you'll get [E0204] and with enums you'll get /// [E0205]. /// -/// [E0204]: https://doc.rust-lang.org/error-index.html#E0204 -/// [E0205]: https://doc.rust-lang.org/error-index.html#E0205 +/// [E0204]: ../../error-index.html#E0204 +/// [E0205]: ../../error-index.html#E0205 /// /// ## When *should* my type be `Copy`? /// diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 72e951a7c34..06838ee89bd 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -182,11 +182,11 @@ pub trait Drop { /// After this function is over, the memory of `self` will be deallocated. /// /// This function cannot be called explicitly. This is compiler error - /// [0040]. However, the [`std::mem::drop`] function in the prelude can be + /// [E0040]. However, the [`std::mem::drop`] function in the prelude can be /// used to call the argument's `Drop` implementation. /// - /// [0040]: https://doc.rust-lang.org/error-index.html#E0040 - /// [`std::mem::drop`]: https://doc.rust-lang.org/std/mem/fn.drop.html + /// [E0040]: ../../error-index.html#E0040 + /// [`std::mem::drop`]: ../../std/mem/fn.drop.html /// /// # Panics /// @@ -1645,7 +1645,7 @@ rem_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } #[lang = "bitand_assign"] #[stable(feature = "op_assign_traits", since = "1.8.0")] pub trait BitAndAssign<Rhs=Self> { - /// The method for the `&` operator + /// The method for the `&=` operator #[stable(feature = "op_assign_traits", since = "1.8.0")] fn bitand_assign(&mut self, Rhs); } @@ -1879,10 +1879,18 @@ shr_assign_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize } /// The `Index` trait is used to specify the functionality of indexing operations /// like `container[index]` when used in an immutable context. /// +/// `container[index]` is actually syntactic sugar for `*container.index(index)`, +/// but only when used as an immutable value. If a mutable value is requested, +/// [`IndexMut`] is used instead. This allows nice things such as +/// `let value = v[index]` if `value` implements [`Copy`]. +/// +/// [`IndexMut`]: ../../std/ops/trait.IndexMut.html +/// [`Copy`]: ../../std/marker/trait.Copy.html +/// /// # Examples /// -/// This example implements `Index` on a read-only `NucleotideCount` container, -/// enabling individual counts to be retrieved with index syntax. +/// The following example implements `Index` on a read-only `NucleotideCount` +/// container, enabling individual counts to be retrieved with index syntax. /// /// ``` /// use std::ops::Index; @@ -1934,37 +1942,78 @@ pub trait Index<Idx: ?Sized> { } /// The `IndexMut` trait is used to specify the functionality of indexing -/// operations like `container[index]`, when used in a mutable context. +/// operations like `container[index]` when used in a mutable context. +/// +/// `container[index]` is actually syntactic sugar for +/// `*container.index_mut(index)`, but only when used as a mutable value. If +/// an immutable value is requested, the [`Index`] trait is used instead. This +/// allows nice things such as `v[index] = value` if `value` implements [`Copy`]. +/// +/// [`Index`]: ../../std/ops/trait.Index.html +/// [`Copy`]: ../../std/marker/trait.Copy.html /// /// # Examples /// -/// A trivial implementation of `IndexMut` for a type `Foo`. When `&mut Foo[2]` -/// happens, it ends up calling `index_mut`, and therefore, `main` prints -/// `Mutable indexing with 2!`. +/// A very simple implementation of a `Balance` struct that has two sides, where +/// each can be indexed mutably and immutably. /// /// ``` -/// use std::ops::{Index, IndexMut}; +/// use std::ops::{Index,IndexMut}; /// -/// #[derive(Copy, Clone)] -/// struct Foo; +/// #[derive(Debug)] +/// enum Side { +/// Left, +/// Right, +/// } +/// +/// #[derive(Debug, PartialEq)] +/// enum Weight { +/// Kilogram(f32), +/// Pound(f32), +/// } /// -/// impl Index<usize> for Foo { -/// type Output = Foo; +/// struct Balance { +/// pub left: Weight, +/// pub right:Weight, +/// } /// -/// fn index(&self, _index: usize) -> &Foo { -/// self +/// impl Index<Side> for Balance { +/// type Output = Weight; +/// +/// fn index<'a>(&'a self, index: Side) -> &'a Weight { +/// println!("Accessing {:?}-side of balance immutably", index); +/// match index { +/// Side::Left => &self.left, +/// Side::Right => &self.right, +/// } /// } /// } /// -/// impl IndexMut<usize> for Foo { -/// fn index_mut(&mut self, index: usize) -> &mut Foo { -/// println!("Mutable indexing with {}!", index); -/// self +/// impl IndexMut<Side> for Balance { +/// fn index_mut<'a>(&'a mut self, index: Side) -> &'a mut Weight { +/// println!("Accessing {:?}-side of balance mutably", index); +/// match index { +/// Side::Left => &mut self.left, +/// Side::Right => &mut self.right, +/// } /// } /// } /// /// fn main() { -/// &mut Foo[2]; +/// let mut balance = Balance { +/// right: Weight::Kilogram(2.5), +/// left: Weight::Pound(1.5), +/// }; +/// +/// // In this case balance[Side::Right] is sugar for +/// // *balance.index(Side::Right), since we are only reading +/// // balance[Side::Right], not writing it. +/// assert_eq!(balance[Side::Right],Weight::Kilogram(2.5)); +/// +/// // However in this case balance[Side::Left] is sugar for +/// // *balance.index_mut(Side::Left), since we are writing +/// // balance[Side::Left]. +/// balance[Side::Left] = Weight::Kilogram(3.0); /// } /// ``` #[lang = "index_mut"] @@ -2435,13 +2484,13 @@ impl<'a, T: ?Sized> Deref for &'a mut T { /// impl<T> Deref for DerefMutExample<T> { /// type Target = T; /// -/// fn deref<'a>(&'a self) -> &'a T { +/// fn deref(&self) -> &T { /// &self.value /// } /// } /// /// impl<T> DerefMut for DerefMutExample<T> { -/// fn deref_mut<'a>(&'a mut self) -> &'a mut T { +/// fn deref_mut(&mut self) -> &mut T { /// &mut self.value /// } /// } diff --git a/src/libcore/option.rs b/src/libcore/option.rs index cb18feff734..a74979911d3 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -914,12 +914,12 @@ impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> { /// ``` /// use std::u16; /// - /// let v = vec!(1, 2); + /// let v = vec![1, 2]; /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16| /// if x == u16::MAX { None } /// else { Some(x + 1) } /// ).collect(); - /// assert!(res == Some(vec!(2, 3))); + /// assert!(res == Some(vec![2, 3])); /// ``` #[inline] fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> { diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 78230b60804..9ba5ff7c3a4 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -792,6 +792,44 @@ impl<T: fmt::Debug, E> Result<T, E> { } } +impl<T: Default, E> Result<T, E> { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Ok`, returns the contained + /// value, otherwise if `Err`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// Convert a string to an integer, turning poorly-formed strings + /// into 0 (the default value for integers). [`parse`] converts + /// a string to any other type that implements [`FromStr`], returning an + /// `Err` on error. + /// + /// ``` + /// #![feature(result_unwrap_or_default)] + /// + /// let good_year_from_input = "1909"; + /// let bad_year_from_input = "190blarg"; + /// let good_year = good_year_from_input.parse().unwrap_or_default(); + /// let bad_year = bad_year_from_input.parse().unwrap_or_default(); + /// + /// assert_eq!(1909, good_year); + /// assert_eq!(0, bad_year); + /// + /// [`parse`]: ../../std/primitive.str.html#method.parse + /// [`FromStr`]: ../../std/str/trait.FromStr.html + /// ``` + #[inline] + #[unstable(feature = "result_unwrap_or_default", issue = "37516")] + pub fn unwrap_or_default(self) -> T { + match self { + Ok(x) => x, + Err(_) => Default::default(), + } + } +} + // This is a separate function to reduce the code size of the methods #[inline(never)] #[cold] @@ -977,12 +1015,12 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> { /// ``` /// use std::u32; /// - /// let v = vec!(1, 2); + /// let v = vec![1, 2]; /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32| /// if x == u32::MAX { Err("Overflow!") } /// else { Ok(x + 1) } /// ).collect(); - /// assert!(res == Ok(vec!(2, 3))); + /// assert!(res == Ok(vec![2, 3])); /// ``` #[inline] fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> { diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index d63d2d64fe1..196750254af 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -132,7 +132,7 @@ impl Utf8Error { /// verified. /// /// It is the maximum index such that `from_utf8(input[..index])` - /// would return `Some(_)`. + /// would return `Ok(_)`. /// /// # Examples /// diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs index 657f7e7992f..c10f7e39fc3 100644 --- a/src/libcore/sync/atomic.rs +++ b/src/libcore/sync/atomic.rs @@ -166,6 +166,10 @@ pub enum Ordering { /// sequentially consistent operations in the same order. #[stable(feature = "rust1", since = "1.0.0")] SeqCst, + // Prevent exhaustive matching to allow for future extension + #[doc(hidden)] + #[unstable(feature = "future_atomic_orderings", issue = "0")] + __Nonexhaustive, } /// An `AtomicBool` initialized to `false`. @@ -1277,6 +1281,7 @@ fn strongest_failure_ordering(order: Ordering) -> Ordering { SeqCst => SeqCst, Acquire => Acquire, AcqRel => Acquire, + __Nonexhaustive => __Nonexhaustive, } } @@ -1288,6 +1293,7 @@ unsafe fn atomic_store<T>(dst: *mut T, val: T, order: Ordering) { SeqCst => intrinsics::atomic_store(dst, val), Acquire => panic!("there is no such thing as an acquire store"), AcqRel => panic!("there is no such thing as an acquire/release store"), + __Nonexhaustive => panic!("invalid memory ordering"), } } @@ -1299,6 +1305,7 @@ unsafe fn atomic_load<T>(dst: *const T, order: Ordering) -> T { SeqCst => intrinsics::atomic_load(dst), Release => panic!("there is no such thing as a release load"), AcqRel => panic!("there is no such thing as an acquire/release load"), + __Nonexhaustive => panic!("invalid memory ordering"), } } @@ -1310,6 +1317,7 @@ unsafe fn atomic_swap<T>(dst: *mut T, val: T, order: Ordering) -> T { AcqRel => intrinsics::atomic_xchg_acqrel(dst, val), Relaxed => intrinsics::atomic_xchg_relaxed(dst, val), SeqCst => intrinsics::atomic_xchg(dst, val), + __Nonexhaustive => panic!("invalid memory ordering"), } } @@ -1322,6 +1330,7 @@ unsafe fn atomic_add<T>(dst: *mut T, val: T, order: Ordering) -> T { AcqRel => intrinsics::atomic_xadd_acqrel(dst, val), Relaxed => intrinsics::atomic_xadd_relaxed(dst, val), SeqCst => intrinsics::atomic_xadd(dst, val), + __Nonexhaustive => panic!("invalid memory ordering"), } } @@ -1334,6 +1343,7 @@ unsafe fn atomic_sub<T>(dst: *mut T, val: T, order: Ordering) -> T { AcqRel => intrinsics::atomic_xsub_acqrel(dst, val), Relaxed => intrinsics::atomic_xsub_relaxed(dst, val), SeqCst => intrinsics::atomic_xsub(dst, val), + __Nonexhaustive => panic!("invalid memory ordering"), } } @@ -1354,6 +1364,8 @@ unsafe fn atomic_compare_exchange<T>(dst: *mut T, (AcqRel, Relaxed) => intrinsics::atomic_cxchg_acqrel_failrelaxed(dst, old, new), (SeqCst, Relaxed) => intrinsics::atomic_cxchg_failrelaxed(dst, old, new), (SeqCst, Acquire) => intrinsics::atomic_cxchg_failacq(dst, old, new), + (__Nonexhaustive, _) => panic!("invalid memory ordering"), + (_, __Nonexhaustive) => panic!("invalid memory ordering"), (_, AcqRel) => panic!("there is no such thing as an acquire/release failure ordering"), (_, Release) => panic!("there is no such thing as a release failure ordering"), _ => panic!("a failure ordering can't be stronger than a success ordering"), @@ -1378,6 +1390,8 @@ unsafe fn atomic_compare_exchange_weak<T>(dst: *mut T, (AcqRel, Relaxed) => intrinsics::atomic_cxchgweak_acqrel_failrelaxed(dst, old, new), (SeqCst, Relaxed) => intrinsics::atomic_cxchgweak_failrelaxed(dst, old, new), (SeqCst, Acquire) => intrinsics::atomic_cxchgweak_failacq(dst, old, new), + (__Nonexhaustive, _) => panic!("invalid memory ordering"), + (_, __Nonexhaustive) => panic!("invalid memory ordering"), (_, AcqRel) => panic!("there is no such thing as an acquire/release failure ordering"), (_, Release) => panic!("there is no such thing as a release failure ordering"), _ => panic!("a failure ordering can't be stronger than a success ordering"), @@ -1393,6 +1407,7 @@ unsafe fn atomic_and<T>(dst: *mut T, val: T, order: Ordering) -> T { AcqRel => intrinsics::atomic_and_acqrel(dst, val), Relaxed => intrinsics::atomic_and_relaxed(dst, val), SeqCst => intrinsics::atomic_and(dst, val), + __Nonexhaustive => panic!("invalid memory ordering"), } } @@ -1404,6 +1419,7 @@ unsafe fn atomic_or<T>(dst: *mut T, val: T, order: Ordering) -> T { AcqRel => intrinsics::atomic_or_acqrel(dst, val), Relaxed => intrinsics::atomic_or_relaxed(dst, val), SeqCst => intrinsics::atomic_or(dst, val), + __Nonexhaustive => panic!("invalid memory ordering"), } } @@ -1415,6 +1431,7 @@ unsafe fn atomic_xor<T>(dst: *mut T, val: T, order: Ordering) -> T { AcqRel => intrinsics::atomic_xor_acqrel(dst, val), Relaxed => intrinsics::atomic_xor_relaxed(dst, val), SeqCst => intrinsics::atomic_xor(dst, val), + __Nonexhaustive => panic!("invalid memory ordering"), } } @@ -1448,6 +1465,7 @@ pub fn fence(order: Ordering) { AcqRel => intrinsics::atomic_fence_acqrel(), SeqCst => intrinsics::atomic_fence(), Relaxed => panic!("there is no such thing as a relaxed fence"), + __Nonexhaustive => panic!("invalid memory ordering"), } } } diff --git a/src/libcoretest/cmp.rs b/src/libcoretest/cmp.rs index 051356cad16..e3c65ad8b33 100644 --- a/src/libcoretest/cmp.rs +++ b/src/libcoretest/cmp.rs @@ -42,6 +42,32 @@ fn test_ordering_order() { } #[test] +fn test_ordering_then() { + assert_eq!(Equal.then(Less), Less); + assert_eq!(Equal.then(Equal), Equal); + assert_eq!(Equal.then(Greater), Greater); + assert_eq!(Less.then(Less), Less); + assert_eq!(Less.then(Equal), Less); + assert_eq!(Less.then(Greater), Less); + assert_eq!(Greater.then(Less), Greater); + assert_eq!(Greater.then(Equal), Greater); + assert_eq!(Greater.then(Greater), Greater); +} + +#[test] +fn test_ordering_then_with() { + assert_eq!(Equal.then_with(|| Less), Less); + assert_eq!(Equal.then_with(|| Equal), Equal); + assert_eq!(Equal.then_with(|| Greater), Greater); + assert_eq!(Less.then_with(|| Less), Less); + assert_eq!(Less.then_with(|| Equal), Less); + assert_eq!(Less.then_with(|| Greater), Less); + assert_eq!(Greater.then_with(|| Less), Greater); + assert_eq!(Greater.then_with(|| Equal), Greater); + assert_eq!(Greater.then_with(|| Greater), Greater); +} + +#[test] fn test_user_defined_eq() { // Our type. struct SketchyNum { diff --git a/src/libcoretest/lib.rs b/src/libcoretest/lib.rs index 590bf478aa7..b8c01e570f5 100644 --- a/src/libcoretest/lib.rs +++ b/src/libcoretest/lib.rs @@ -34,6 +34,8 @@ #![feature(unique)] #![feature(iter_max_by)] #![feature(iter_min_by)] +#![feature(ordering_chaining)] +#![feature(result_unwrap_or_default)] extern crate core; extern crate test; diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index 6e9f653dcd8..bc2cd8bbfc6 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -183,3 +183,9 @@ pub fn test_iter_mut() { } assert_eq!(err, Err("error")); } + +#[test] +pub fn test_unwrap_or_default() { + assert_eq!(op1().unwrap_or_default(), 666); + assert_eq!(op2().unwrap_or_default(), 0); +} diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 42200795bb3..4d2f1b999a2 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -1610,8 +1610,8 @@ Options: #[test] fn test_args_with_equals() { - let args = vec!("--one".to_string(), "A=B".to_string(), - "--two=C=D".to_string()); + let args = vec!["--one".to_string(), "A=B".to_string(), + "--two=C=D".to_string()]; let opts = vec![optopt("o", "one", "One", "INFO"), optopt("t", "two", "Two", "INFO")]; let matches = &match getopts(&args, &opts) { diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 95c46ec5715..03057af4a84 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -58,7 +58,7 @@ //! struct Edges(Vec<Ed>); //! //! pub fn render_to<W: Write>(output: &mut W) { -//! let edges = Edges(vec!((0,1), (0,2), (1,3), (2,3), (3,4), (4,4))); +//! let edges = Edges(vec![(0,1), (0,2), (1,3), (2,3), (3,4), (4,4)]); //! dot::render(&edges, output).unwrap() //! } //! @@ -164,8 +164,8 @@ //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> } //! //! pub fn render_to<W: Write>(output: &mut W) { -//! let nodes = vec!("{x,y}","{x}","{y}","{}"); -//! let edges = vec!((0,1), (0,2), (1,3), (2,3)); +//! let nodes = vec!["{x,y}","{x}","{y}","{}"]; +//! let edges = vec![(0,1), (0,2), (1,3), (2,3)]; //! let graph = Graph { nodes: nodes, edges: edges }; //! //! dot::render(&graph, output).unwrap() @@ -226,8 +226,8 @@ //! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> } //! //! pub fn render_to<W: Write>(output: &mut W) { -//! let nodes = vec!("{x,y}","{x}","{y}","{}"); -//! let edges = vec!((0,1), (0,2), (1,3), (2,3)); +//! let nodes = vec!["{x,y}","{x}","{y}","{}"]; +//! let edges = vec![(0,1), (0,2), (1,3), (2,3)]; //! let graph = Graph { nodes: nodes, edges: edges }; //! //! dot::render(&graph, output).unwrap() diff --git a/src/librand/chacha.rs b/src/librand/chacha.rs index 8ca1738bb18..7dc0d19e6a6 100644 --- a/src/librand/chacha.rs +++ b/src/librand/chacha.rs @@ -253,17 +253,17 @@ mod tests { let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, - vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, + vec![0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, - 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2)); + 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2]); let v = (0..16).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, - vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, + vec![0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, - 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b)); + 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b]); let seed: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; @@ -280,10 +280,10 @@ mod tests { } assert_eq!(v, - vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, + vec![0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, - 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4)); + 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4]); } #[test] diff --git a/src/librand/distributions/mod.rs b/src/librand/distributions/mod.rs index c5588d94876..41175c81df8 100644 --- a/src/librand/distributions/mod.rs +++ b/src/librand/distributions/mod.rs @@ -312,37 +312,37 @@ mod tests { }} } - t!(vec!(Weighted { weight: 1, item: 10 }), + t!(vec![Weighted { weight: 1, item: 10 }], [10]); // skip some - t!(vec!(Weighted { weight: 0, item: 20 }, + t!(vec![Weighted { weight: 0, item: 20 }, Weighted { weight: 2, item: 21 }, Weighted { weight: 0, item: 22 }, - Weighted { weight: 1, item: 23 }), + Weighted { weight: 1, item: 23 }], [21, 21, 23]); // different weights - t!(vec!(Weighted { weight: 4, item: 30 }, - Weighted { weight: 3, item: 31 }), + t!(vec![Weighted { weight: 4, item: 30 }, + Weighted { weight: 3, item: 31 }], [30, 30, 30, 30, 31, 31, 31]); // check that we're binary searching // correctly with some vectors of odd // length. - t!(vec!(Weighted { weight: 1, item: 40 }, + t!(vec![Weighted { weight: 1, item: 40 }, Weighted { weight: 1, item: 41 }, Weighted { weight: 1, item: 42 }, Weighted { weight: 1, item: 43 }, - Weighted { weight: 1, item: 44 }), + Weighted { weight: 1, item: 44 }], [40, 41, 42, 43, 44]); - t!(vec!(Weighted { weight: 1, item: 50 }, + t!(vec![Weighted { weight: 1, item: 50 }, Weighted { weight: 1, item: 51 }, Weighted { weight: 1, item: 52 }, Weighted { weight: 1, item: 53 }, Weighted { weight: 1, item: 54 }, Weighted { weight: 1, item: 55 }, - Weighted { weight: 1, item: 56 }), + Weighted { weight: 1, item: 56 }], [50, 51, 52, 53, 54, 55, 56]); } diff --git a/src/librand/isaac.rs b/src/librand/isaac.rs index 974f65ac2c5..69d5015f181 100644 --- a/src/librand/isaac.rs +++ b/src/librand/isaac.rs @@ -662,8 +662,8 @@ mod tests { // Regression test that isaac is actually using the above vector let v = (0..10).map(|_| ra.next_u32()).collect::<Vec<_>>(); assert_eq!(v, - vec!(2558573138, 873787463, 263499565, 2103644246, 3595684709, - 4203127393, 264982119, 2765226902, 2737944514, 3900253796)); + vec![2558573138, 873787463, 263499565, 2103644246, 3595684709, + 4203127393, 264982119, 2765226902, 2737944514, 3900253796]); let seed: &[_] = &[12345, 67890, 54321, 9876]; let mut rb: IsaacRng = SeedableRng::from_seed(seed); @@ -674,8 +674,8 @@ mod tests { let v = (0..10).map(|_| rb.next_u32()).collect::<Vec<_>>(); assert_eq!(v, - vec!(3676831399, 3183332890, 2834741178, 3854698763, 2717568474, - 1576568959, 3507990155, 179069555, 141456972, 2478885421)); + vec![3676831399, 3183332890, 2834741178, 3854698763, 2717568474, + 1576568959, 3507990155, 179069555, 141456972, 2478885421]); } #[test] #[rustfmt_skip] @@ -685,10 +685,10 @@ mod tests { // Regression test that isaac is actually using the above vector let v = (0..10).map(|_| ra.next_u64()).collect::<Vec<_>>(); assert_eq!(v, - vec!(547121783600835980, 14377643087320773276, 17351601304698403469, + vec![547121783600835980, 14377643087320773276, 17351601304698403469, 1238879483818134882, 11952566807690396487, 13970131091560099343, 4469761996653280935, 15552757044682284409, 6860251611068737823, - 13722198873481261842)); + 13722198873481261842]); let seed: &[_] = &[12345, 67890, 54321, 9876]; let mut rb: Isaac64Rng = SeedableRng::from_seed(seed); @@ -699,10 +699,10 @@ mod tests { let v = (0..10).map(|_| rb.next_u64()).collect::<Vec<_>>(); assert_eq!(v, - vec!(18143823860592706164, 8491801882678285927, 2699425367717515619, + vec![18143823860592706164, 8491801882678285927, 2699425367717515619, 17196852593171130876, 2606123525235546165, 15790932315217671084, 596345674630742204, 9947027391921273664, 11788097613744130851, - 10391409374914919106)); + 10391409374914919106]); } diff --git a/src/librustc/cfg/construct.rs b/src/librustc/cfg/construct.rs index 50d4cbc982e..1b2976b7435 100644 --- a/src/librustc/cfg/construct.rs +++ b/src/librustc/cfg/construct.rs @@ -536,7 +536,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { fn add_contained_edge(&mut self, source: CFGIndex, target: CFGIndex) { - let data = CFGEdgeData {exiting_scopes: vec!() }; + let data = CFGEdgeData {exiting_scopes: vec![] }; self.graph.add_edge(source, target, data); } @@ -545,7 +545,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { from_index: CFGIndex, to_loop: LoopScope, to_index: CFGIndex) { - let mut data = CFGEdgeData {exiting_scopes: vec!() }; + let mut data = CFGEdgeData {exiting_scopes: vec![] }; let mut scope = self.tcx.region_maps.node_extent(from_expr.id); let target_scope = self.tcx.region_maps.node_extent(to_loop.loop_id); while scope != target_scope { @@ -559,7 +559,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { _from_expr: &hir::Expr, from_index: CFGIndex) { let mut data = CFGEdgeData { - exiting_scopes: vec!(), + exiting_scopes: vec![], }; for &LoopScope { loop_id: id, .. } in self.loop_scopes.iter().rev() { data.exiting_scopes.push(id); diff --git a/src/librustc/infer/error_reporting.rs b/src/librustc/infer/error_reporting.rs index be659432024..5e3925b0b3c 100644 --- a/src/librustc/infer/error_reporting.rs +++ b/src/librustc/infer/error_reporting.rs @@ -457,7 +457,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { } same_regions.push(SameRegions { scope_id: scope_id, - regions: vec!(sub_fr.bound_region, sup_fr.bound_region) + regions: vec![sub_fr.bound_region, sup_fr.bound_region] }) } } @@ -1359,7 +1359,7 @@ impl<'a, 'gcx, 'tcx> Rebuilder<'a, 'gcx, 'tcx> { region_names: &HashSet<ast::Name>) -> P<hir::Ty> { let mut new_ty = P(ty.clone()); - let mut ty_queue = vec!(ty); + let mut ty_queue = vec![ty]; while !ty_queue.is_empty() { let cur_ty = ty_queue.remove(0); match cur_ty.node { diff --git a/src/librustc/infer/mod.rs b/src/librustc/infer/mod.rs index af994e884fe..4c097965bb0 100644 --- a/src/librustc/infer/mod.rs +++ b/src/librustc/infer/mod.rs @@ -199,9 +199,6 @@ pub enum TypeOrigin { // Computing common supertype of an if expression with no else counter-part IfExpressionWithNoElse(Span), - // Computing common supertype in a range expression - RangeExpression(Span), - // `where a == b` EquatePredicate(Span), @@ -231,7 +228,6 @@ impl TypeOrigin { }, &TypeOrigin::IfExpression(_) => "if and else have incompatible types", &TypeOrigin::IfExpressionWithNoElse(_) => "if may be missing an else clause", - &TypeOrigin::RangeExpression(_) => "start and end of range have incompatible types", &TypeOrigin::EquatePredicate(_) => "equality predicate not satisfied", &TypeOrigin::MainFunctionType(_) => "main function has wrong type", &TypeOrigin::StartFunctionType(_) => "start function has wrong type", @@ -251,7 +247,6 @@ impl TypeOrigin { &TypeOrigin::MatchExpressionArm(..) => "match arms have compatible types", &TypeOrigin::IfExpression(_) => "if and else have compatible types", &TypeOrigin::IfExpressionWithNoElse(_) => "if missing an else returns ()", - &TypeOrigin::RangeExpression(_) => "start and end of range have compatible types", &TypeOrigin::EquatePredicate(_) => "equality where clause is satisfied", &TypeOrigin::MainFunctionType(_) => "`main` function has the correct type", &TypeOrigin::StartFunctionType(_) => "`start` function has the correct type", @@ -1755,7 +1750,6 @@ impl TypeOrigin { TypeOrigin::MatchExpressionArm(match_span, ..) => match_span, TypeOrigin::IfExpression(span) => span, TypeOrigin::IfExpressionWithNoElse(span) => span, - TypeOrigin::RangeExpression(span) => span, TypeOrigin::EquatePredicate(span) => span, TypeOrigin::MainFunctionType(span) => span, TypeOrigin::StartFunctionType(span) => span, diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 81d3d440b56..20463f42d3b 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -127,9 +127,9 @@ impl LintStore { pub fn new() -> LintStore { LintStore { - lints: vec!(), - early_passes: Some(vec!()), - late_passes: Some(vec!()), + lints: vec![], + early_passes: Some(vec![]), + late_passes: Some(vec![]), by_name: FnvHashMap(), levels: FnvHashMap(), future_incompatible: FnvHashMap(), @@ -345,7 +345,7 @@ macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({ // See also the hir version just below. pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec<Result<(InternedString, Level, Span), Span>> { - let mut out = vec!(); + let mut out = vec![]; for attr in attrs { let r = gather_attr(attr); out.extend(r.into_iter()); @@ -355,7 +355,7 @@ pub fn gather_attrs(attrs: &[ast::Attribute]) pub fn gather_attr(attr: &ast::Attribute) -> Vec<Result<(InternedString, Level, Span), Span>> { - let mut out = vec!(); + let mut out = vec![]; let level = match Level::from_str(&attr.name()) { None => return out, @@ -452,8 +452,7 @@ pub fn raw_struct_lint<'a>(sess: &'a Session, } if let Some(span) = def { - let explanation = "lint level defined here"; - err.span_note(span, &explanation); + sess.diag_span_note_once(&mut err, lint, span, "lint level defined here"); } err diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 078cce9c49f..3175230ab6a 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -59,7 +59,7 @@ impl LanguageItems { fn foo(_: LangItem) -> Option<DefId> { None } LanguageItems { - items: vec!($(foo($variant)),*), + items: vec![$(foo($variant)),*], missing: Vec::new(), } } diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 7b5413984a2..87a5c6410a8 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -715,7 +715,7 @@ macro_rules! options { true } v => { - let mut passes = vec!(); + let mut passes = vec![]; if parse_list(&mut passes, v) { *slot = SomePasses(passes); true @@ -1293,7 +1293,7 @@ pub fn build_session_options_and_crate_config(matches: &getopts::Matches) let crate_types = parse_crate_types_from_list(unparsed_crate_types) .unwrap_or_else(|e| early_error(error_format, &e[..])); - let mut lint_opts = vec!(); + let mut lint_opts = vec![]; let mut describe_lints = false; for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] { diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index d002aba595b..1ce5b223fbe 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -17,7 +17,7 @@ use middle::dependency_format; use session::search_paths::PathKind; use session::config::DebugInfoLevel; use ty::tls; -use util::nodemap::{NodeMap, FnvHashMap}; +use util::nodemap::{NodeMap, FnvHashMap, FnvHashSet}; use util::common::duration_to_secs_str; use mir::transform as mir_pass; @@ -75,6 +75,10 @@ pub struct Session { pub working_dir: PathBuf, pub lint_store: RefCell<lint::LintStore>, pub lints: RefCell<NodeMap<Vec<(lint::LintId, Span, String)>>>, + /// Set of (LintId, span, message) tuples tracking lint (sub)diagnostics + /// that have been set once, but should not be set again, in order to avoid + /// redundantly verbose output (Issue #24690). + pub one_time_diagnostics: RefCell<FnvHashSet<(lint::LintId, Span, String)>>, pub plugin_llvm_passes: RefCell<Vec<String>>, pub mir_passes: RefCell<mir_pass::Passes>, pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>, @@ -268,7 +272,7 @@ impl Session { } return; } - lints.insert(id, vec!((lint_id, sp, msg))); + lints.insert(id, vec![(lint_id, sp, msg)]); } pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId { let id = self.next_node_id.get(); @@ -288,6 +292,35 @@ impl Session { pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler { &self.parse_sess.span_diagnostic } + + /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but + /// deduplicates on lint ID, span, and message for this `Session` if we're + /// not outputting in JSON mode. + // + // FIXME: if the need arises for one-time diagnostics other than + // `span_note`, we almost certainly want to generalize this + // "check/insert-into the one-time diagnostics map, then set message if + // it's not already there" code to accomodate all of them + pub fn diag_span_note_once<'a, 'b>(&'a self, + diag_builder: &'b mut DiagnosticBuilder<'a>, + lint: &'static lint::Lint, span: Span, message: &str) { + match self.opts.error_format { + // when outputting JSON for tool consumption, the tool might want + // the duplicates + config::ErrorOutputType::Json => { + diag_builder.span_note(span, &message); + }, + _ => { + let lint_id = lint::LintId::of(lint); + let id_span_message = (lint_id, span, message.to_owned()); + let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message); + if fresh { + diag_builder.span_note(span, &message); + } + } + } + } + pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap { self.parse_sess.codemap() } @@ -561,6 +594,7 @@ pub fn build_session_(sopts: config::Options, working_dir: env::current_dir().unwrap(), lint_store: RefCell::new(lint::LintStore::new()), lints: RefCell::new(NodeMap()), + one_time_diagnostics: RefCell::new(FnvHashSet()), plugin_llvm_passes: RefCell::new(Vec::new()), mir_passes: RefCell::new(mir_pass::Passes::new()), plugin_attributes: RefCell::new(Vec::new()), diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs index f1f1658cc82..ce882c48377 100644 --- a/src/librustc/traits/project.rs +++ b/src/librustc/traits/project.rs @@ -275,7 +275,7 @@ impl<'a, 'b, 'gcx, 'tcx> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> { AssociatedTypeNormalizer { selcx: selcx, cause: cause, - obligations: vec!(), + obligations: vec![], depth: depth, } } @@ -396,7 +396,7 @@ pub fn normalize_projection_type<'a, 'b, 'gcx, 'tcx>( cause, depth + 1, projection.to_predicate()); Normalized { value: ty_var, - obligations: vec!(obligation) + obligations: vec![obligation] } }) } @@ -545,7 +545,7 @@ fn opt_normalize_projection_type<'a, 'b, 'gcx, 'tcx>( projected_ty); let result = Normalized { value: projected_ty, - obligations: vec!() + obligations: vec![] }; infcx.projection_cache.borrow_mut() .complete(projection_ty, &result, true); @@ -604,7 +604,7 @@ fn normalize_to_error<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tc let new_value = selcx.infcx().next_ty_var(); Normalized { value: new_value, - obligations: vec!(trait_obligation) + obligations: vec![trait_obligation] } } diff --git a/src/librustc/traits/specialize/mod.rs b/src/librustc/traits/specialize/mod.rs index e37425901c8..24cafa7f725 100644 --- a/src/librustc/traits/specialize/mod.rs +++ b/src/librustc/traits/specialize/mod.rs @@ -25,7 +25,7 @@ use hir::def_id::DefId; use infer::{InferCtxt, TypeOrigin}; use middle::region; use ty::subst::{Subst, Substs}; -use traits::{self, Reveal, ObligationCause, Normalized}; +use traits::{self, Reveal, ObligationCause}; use ty::{self, TyCtxt, TypeFoldable}; use syntax_pos::DUMMY_SP; @@ -148,6 +148,8 @@ pub fn find_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, pub fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl1_def_id: DefId, impl2_def_id: DefId) -> bool { + debug!("specializes({:?}, {:?})", impl1_def_id, impl2_def_id); + if let Some(r) = tcx.specializes_cache.borrow().check(impl1_def_id, impl2_def_id) { return r; } @@ -177,31 +179,24 @@ pub fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } // create a parameter environment corresponding to a (skolemized) instantiation of impl1 - let mut penv = tcx.construct_parameter_environment(DUMMY_SP, - impl1_def_id, - region::DUMMY_CODE_EXTENT); + let penv = tcx.construct_parameter_environment(DUMMY_SP, + impl1_def_id, + region::DUMMY_CODE_EXTENT); let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id) .unwrap() .subst(tcx, &penv.free_substs); - let result = tcx.infer_ctxt(None, None, Reveal::ExactMatch).enter(|mut infcx| { - // Normalize the trait reference, adding any obligations - // that arise into the impl1 assumptions. - let Normalized { value: impl1_trait_ref, obligations: normalization_obligations } = { - let selcx = &mut SelectionContext::new(&infcx); - traits::normalize(selcx, ObligationCause::dummy(), &impl1_trait_ref) - }; - penv.caller_bounds.extend(normalization_obligations.into_iter().map(|o| { - match tcx.lift_to_global(&o.predicate) { - Some(predicate) => predicate, - None => { - bug!("specializes: obligation `{:?}` has inference types/regions", o); + // Create a infcx, taking the predicates of impl1 as assumptions: + let result = tcx.infer_ctxt(None, Some(penv), Reveal::ExactMatch).enter(|infcx| { + // Normalize the trait reference. The WF rules ought to ensure + // that this always succeeds. + let impl1_trait_ref = + match traits::fully_normalize(&infcx, ObligationCause::dummy(), &impl1_trait_ref) { + Ok(impl1_trait_ref) => impl1_trait_ref, + Err(err) => { + bug!("failed to fully normalize {:?}: {:?}", impl1_trait_ref, err); } - } - })); - - // Install the parameter environment, taking the predicates of impl1 as assumptions: - infcx.parameter_environment = penv; + }; // Attempt to prove that impl2 applies, given all of the above. fulfill_implication(&infcx, impl1_trait_ref, impl2_def_id).is_ok() diff --git a/src/librustc/ty/walk.rs b/src/librustc/ty/walk.rs index dd3a62f7cd2..bebdebf127a 100644 --- a/src/librustc/ty/walk.rs +++ b/src/librustc/ty/walk.rs @@ -22,7 +22,7 @@ pub struct TypeWalker<'tcx> { impl<'tcx> TypeWalker<'tcx> { pub fn new(ty: Ty<'tcx>) -> TypeWalker<'tcx> { - TypeWalker { stack: vec!(ty), last_subtree: 1, } + TypeWalker { stack: vec![ty], last_subtree: 1, } } /// Skips the subtree of types corresponding to the last type diff --git a/src/librustc/ty/wf.rs b/src/librustc/ty/wf.rs index 0557660e98c..1135199d225 100644 --- a/src/librustc/ty/wf.rs +++ b/src/librustc/ty/wf.rs @@ -201,11 +201,11 @@ fn implied_bounds_from_components<'tcx>(sub_region: &'tcx ty::Region, .flat_map(|component| { match component { Component::Region(r) => - vec!(ImpliedBound::RegionSubRegion(sub_region, r)), + vec![ImpliedBound::RegionSubRegion(sub_region, r)], Component::Param(p) => - vec!(ImpliedBound::RegionSubParam(sub_region, p)), + vec![ImpliedBound::RegionSubParam(sub_region, p)], Component::Projection(p) => - vec!(ImpliedBound::RegionSubProjection(sub_region, p)), + vec![ImpliedBound::RegionSubProjection(sub_region, p)], Component::EscapingProjection(_) => // If the projection has escaping regions, don't // try to infer any implied bounds even for its @@ -215,9 +215,9 @@ fn implied_bounds_from_components<'tcx>(sub_region: &'tcx ty::Region, // idea is that the WAY that the caller proves // that may change in the future and we want to // give ourselves room to get smarter here. - vec!(), + vec![], Component::UnresolvedInferenceVariable(..) => - vec!(), + vec![], } }) .collect() diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 5ca56741029..954e3b1fc13 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -59,15 +59,25 @@ fn fn_sig(f: &mut fmt::Formatter, pub fn parameterized(f: &mut fmt::Formatter, substs: &subst::Substs, - did: DefId, + mut did: DefId, projections: &[ty::ProjectionPredicate]) -> fmt::Result { + let key = ty::tls::with(|tcx| tcx.def_key(did)); + let mut item_name = if let Some(name) = key.disambiguated_data.data.get_opt_name() { + Some(name) + } else { + did.index = key.parent.unwrap_or_else( + || bug!("finding type for {:?}, encountered def-id {:?} with no parent", + did, did)); + parameterized(f, substs, did, projections)?; + return write!(f, "::{}", key.disambiguated_data.data.as_interned_str()); + }; + let mut verbose = false; let mut num_supplied_defaults = 0; let mut has_self = false; let mut num_regions = 0; let mut num_types = 0; - let mut item_name = None; let mut is_value_path = false; let fn_trait_kind = ty::tls::with(|tcx| { // Unfortunately, some kinds of items (e.g., closures) don't have @@ -113,9 +123,10 @@ pub fn parameterized(f: &mut fmt::Formatter, write!(f, "<{} as ", substs.type_at(0))?; } - item_name = Some(tcx.item_name(did)); path_def_id = def_id; } else { + item_name = None; + if is_value_path { // Functions. assert_eq!(has_self, false); diff --git a/src/librustc_back/target/dragonfly_base.rs b/src/librustc_back/target/dragonfly_base.rs index e2c4003a8b6..7555181a15c 100644 --- a/src/librustc_back/target/dragonfly_base.rs +++ b/src/librustc_back/target/dragonfly_base.rs @@ -17,7 +17,7 @@ pub fn opts() -> TargetOptions { executables: true, linker_is_gnu: true, has_rpath: true, - pre_link_args: vec!( + pre_link_args: vec![ // GNU-style linkers will use this to omit linking to libraries // which don't actually fulfill any relocations, but only for // libraries which follow this flag. Thus, use it before @@ -26,7 +26,7 @@ pub fn opts() -> TargetOptions { // Always enable NX protection when it is available "-Wl,-z,noexecstack".to_string(), - ), + ], position_independent_executables: true, exe_allocation_crate: super::maybe_jemalloc(), .. Default::default() diff --git a/src/librustc_back/target/freebsd_base.rs b/src/librustc_back/target/freebsd_base.rs index e2c4003a8b6..7555181a15c 100644 --- a/src/librustc_back/target/freebsd_base.rs +++ b/src/librustc_back/target/freebsd_base.rs @@ -17,7 +17,7 @@ pub fn opts() -> TargetOptions { executables: true, linker_is_gnu: true, has_rpath: true, - pre_link_args: vec!( + pre_link_args: vec![ // GNU-style linkers will use this to omit linking to libraries // which don't actually fulfill any relocations, but only for // libraries which follow this flag. Thus, use it before @@ -26,7 +26,7 @@ pub fn opts() -> TargetOptions { // Always enable NX protection when it is available "-Wl,-z,noexecstack".to_string(), - ), + ], position_independent_executables: true, exe_allocation_crate: super::maybe_jemalloc(), .. Default::default() diff --git a/src/librustc_back/target/le32_unknown_nacl.rs b/src/librustc_back/target/le32_unknown_nacl.rs index a98a33feb5e..891e7dda14a 100644 --- a/src/librustc_back/target/le32_unknown_nacl.rs +++ b/src/librustc_back/target/le32_unknown_nacl.rs @@ -15,10 +15,10 @@ pub fn target() -> TargetResult { linker: "pnacl-clang".to_string(), ar: "pnacl-ar".to_string(), - pre_link_args: vec!("--pnacl-exceptions=sjlj".to_string(), + pre_link_args: vec!["--pnacl-exceptions=sjlj".to_string(), "--target=le32-unknown-nacl".to_string(), - "-Wl,--start-group".to_string()), - post_link_args: vec!("-Wl,--end-group".to_string()), + "-Wl,--start-group".to_string()], + post_link_args: vec!["-Wl,--end-group".to_string()], dynamic_linking: false, executables: true, exe_suffix: ".pexe".to_string(), diff --git a/src/librustc_back/target/netbsd_base.rs b/src/librustc_back/target/netbsd_base.rs index cc03ed56aa4..6e038a7ed56 100644 --- a/src/librustc_back/target/netbsd_base.rs +++ b/src/librustc_back/target/netbsd_base.rs @@ -17,7 +17,7 @@ pub fn opts() -> TargetOptions { executables: true, linker_is_gnu: true, has_rpath: true, - pre_link_args: vec!( + pre_link_args: vec![ // GNU-style linkers will use this to omit linking to libraries // which don't actually fulfill any relocations, but only for // libraries which follow this flag. Thus, use it before @@ -26,7 +26,7 @@ pub fn opts() -> TargetOptions { // Always enable NX protection when it is available "-Wl,-z,noexecstack".to_string(), - ), + ], position_independent_executables: true, .. Default::default() } diff --git a/src/librustc_back/target/openbsd_base.rs b/src/librustc_back/target/openbsd_base.rs index 7afdfcd6911..90e6631841b 100644 --- a/src/librustc_back/target/openbsd_base.rs +++ b/src/librustc_back/target/openbsd_base.rs @@ -17,7 +17,7 @@ pub fn opts() -> TargetOptions { executables: true, linker_is_gnu: true, has_rpath: true, - pre_link_args: vec!( + pre_link_args: vec![ // GNU-style linkers will use this to omit linking to libraries // which don't actually fulfill any relocations, but only for // libraries which follow this flag. Thus, use it before @@ -26,7 +26,7 @@ pub fn opts() -> TargetOptions { // Always enable NX protection when it is available "-Wl,-z,noexecstack".to_string(), - ), + ], position_independent_executables: true, exe_allocation_crate: "alloc_system".to_string(), .. Default::default() diff --git a/src/librustc_back/target/windows_base.rs b/src/librustc_back/target/windows_base.rs index c398ee40f2f..19ca0df51b9 100644 --- a/src/librustc_back/target/windows_base.rs +++ b/src/librustc_back/target/windows_base.rs @@ -26,7 +26,7 @@ pub fn opts() -> TargetOptions { no_default_libraries: true, is_like_windows: true, allows_weak_linkage: false, - pre_link_args: vec!( + pre_link_args: vec![ // And here, we see obscure linker flags #45. On windows, it has been // found to be necessary to have this flag to compile liblibc. // @@ -63,26 +63,26 @@ pub fn opts() -> TargetOptions { // Do not use the standard system startup files or libraries when linking "-nostdlib".to_string(), - ), - pre_link_objects_exe: vec!( + ], + pre_link_objects_exe: vec![ "crt2.o".to_string(), // mingw C runtime initialization for executables "rsbegin.o".to_string(), // Rust compiler runtime initialization, see rsbegin.rs - ), - pre_link_objects_dll: vec!( + ], + pre_link_objects_dll: vec![ "dllcrt2.o".to_string(), // mingw C runtime initialization for dlls "rsbegin.o".to_string(), - ), - late_link_args: vec!( + ], + late_link_args: vec![ "-lmingwex".to_string(), "-lmingw32".to_string(), "-lgcc".to_string(), // alas, mingw* libraries above depend on libgcc "-lmsvcrt".to_string(), "-luser32".to_string(), "-lkernel32".to_string(), - ), - post_link_objects: vec!( + ], + post_link_objects: vec![ "rsend.o".to_string() - ), + ], custom_unwind_resume: true, .. Default::default() diff --git a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs index 9fbf1492f5d..47f8d978704 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs @@ -92,7 +92,7 @@ fn group_errors_with_same_origin<'tcx>(errors: &Vec<MoveError<'tcx>>) let move_from_id = error.move_from.id; debug!("append_to_grouped_errors(move_from_id={})", move_from_id); let move_to = if error.move_to.is_some() { - vec!(error.move_to.clone().unwrap()) + vec![error.move_to.clone().unwrap()] } else { Vec::new() }; diff --git a/src/librustc_borrowck/borrowck/mir/abs_domain.rs b/src/librustc_borrowck/borrowck/mir/abs_domain.rs index dc450433ad9..5e61c2ec7a2 100644 --- a/src/librustc_borrowck/borrowck/mir/abs_domain.rs +++ b/src/librustc_borrowck/borrowck/mir/abs_domain.rs @@ -21,13 +21,11 @@ //! `a[x]` would still overlap them both. But that is not this //! representation does today.) -use rustc::mir::{Lvalue, LvalueElem}; -use rustc::mir::{Operand, Projection, ProjectionElem}; +use rustc::mir::LvalueElem; +use rustc::mir::{Operand, ProjectionElem}; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct AbstractOperand; -pub type AbstractProjection<'tcx> = - Projection<'tcx, Lvalue<'tcx>, AbstractOperand>; pub type AbstractElem<'tcx> = ProjectionElem<'tcx, AbstractOperand>; diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index ef6936b6e7d..2f74ea3e475 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -300,8 +300,6 @@ struct BorrowStats { guaranteed_paths: usize } -pub type BckResult<'tcx, T> = Result<T, BckError<'tcx>>; - /////////////////////////////////////////////////////////////////////////// // Loans and loan paths @@ -1064,6 +1062,19 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { db.note("values in a scope are dropped in the opposite order \ they are created"); } + (Some(s1), Some(s2)) if !is_temporary && !is_closure => { + db.span = MultiSpan::from_span(s2); + db.span_label(error_span, &format!("borrow occurs here")); + let msg = match opt_loan_path(&err.cmt) { + None => "borrowed value".to_string(), + Some(lp) => { + format!("`{}`", self.loan_path_to_string(&lp)) + } + }; + db.span_label(s2, + &format!("{} dropped here while still borrowed", msg)); + db.span_label(s1, &format!("{} needs to live until here", value_kind)); + } _ => { match sub_span { Some(s) => { diff --git a/src/librustc_borrowck/borrowck/move_data.rs b/src/librustc_borrowck/borrowck/move_data.rs index e9ba406389f..ba036f1a8b1 100644 --- a/src/librustc_borrowck/borrowck/move_data.rs +++ b/src/librustc_borrowck/borrowck/move_data.rs @@ -331,7 +331,7 @@ impl<'a, 'tcx> MoveData<'tcx> { fn existing_base_paths(&self, lp: &Rc<LoanPath<'tcx>>) -> Vec<MovePathIndex> { - let mut result = vec!(); + let mut result = vec![]; self.add_existing_base_paths(lp, &mut result); result } diff --git a/src/librustc_const_eval/diagnostics.rs b/src/librustc_const_eval/diagnostics.rs index 092638cdee2..db72057636a 100644 --- a/src/librustc_const_eval/diagnostics.rs +++ b/src/librustc_const_eval/diagnostics.rs @@ -454,7 +454,7 @@ loop variable, consider using a `match` or `if let` inside the loop body. For instance: ```compile_fail,E0297 -let xs : Vec<Option<i32>> = vec!(Some(1), None); +let xs : Vec<Option<i32>> = vec![Some(1), None]; // This fails because `None` is not covered. for Some(x) in xs { @@ -465,7 +465,7 @@ for Some(x) in xs { Match inside the loop instead: ``` -let xs : Vec<Option<i32>> = vec!(Some(1), None); +let xs : Vec<Option<i32>> = vec![Some(1), None]; for item in xs { match item { @@ -478,7 +478,7 @@ for item in xs { Or use `if let`: ``` -let xs : Vec<Option<i32>> = vec!(Some(1), None); +let xs : Vec<Option<i32>> = vec![Some(1), None]; for item in xs { if let Some(x) = item { diff --git a/src/librustc_data_structures/obligation_forest/mod.rs b/src/librustc_data_structures/obligation_forest/mod.rs index 5e590cb445f..a2bfa784e8a 100644 --- a/src/librustc_data_structures/obligation_forest/mod.rs +++ b/src/librustc_data_structures/obligation_forest/mod.rs @@ -377,8 +377,16 @@ impl<O: ForestObligation> ObligationForest<O> { { let mut stack = self.scratch.take().unwrap(); - for node in 0..self.nodes.len() { - self.find_cycles_from_node(&mut stack, processor, node); + for index in 0..self.nodes.len() { + // For rustc-benchmarks/inflate-0.1.0 this state test is extremely + // hot and the state is almost always `Pending` or `Waiting`. It's + // a win to handle the no-op cases immediately to avoid the cost of + // the function call. + let state = self.nodes[index].state.get(); + match state { + NodeState::Waiting | NodeState::Pending | NodeState::Done | NodeState::Error => {}, + _ => self.find_cycles_from_node(&mut stack, processor, index), + } } self.scratch = Some(stack); @@ -476,7 +484,18 @@ impl<O: ForestObligation> ObligationForest<O> { trace } - /// Marks all nodes that depend on a pending node as NodeState;:Waiting. + #[inline] + fn mark_neighbors_as_waiting_from(&self, node: &Node<O>) { + if let Some(parent) = node.parent { + self.mark_as_waiting_from(&self.nodes[parent.get()]); + } + + for dependent in &node.dependents { + self.mark_as_waiting_from(&self.nodes[dependent.get()]); + } + } + + /// Marks all nodes that depend on a pending node as NodeState::Waiting. fn mark_as_waiting(&self) { for node in &self.nodes { if node.state.get() == NodeState::Waiting { @@ -486,27 +505,19 @@ impl<O: ForestObligation> ObligationForest<O> { for node in &self.nodes { if node.state.get() == NodeState::Pending { - self.mark_as_waiting_from(node) + self.mark_neighbors_as_waiting_from(node); } } } fn mark_as_waiting_from(&self, node: &Node<O>) { match node.state.get() { - NodeState::Pending | NodeState::Done => {}, NodeState::Waiting | NodeState::Error | NodeState::OnDfsStack => return, - NodeState::Success => { - node.state.set(NodeState::Waiting); - } - } - - if let Some(parent) = node.parent { - self.mark_as_waiting_from(&self.nodes[parent.get()]); + NodeState::Success => node.state.set(NodeState::Waiting), + NodeState::Pending | NodeState::Done => {}, } - for dependent in &node.dependents { - self.mark_as_waiting_from(&self.nodes[dependent.get()]); - } + self.mark_neighbors_as_waiting_from(node); } /// Compresses the vector, removing all popped nodes. This adjusts @@ -532,28 +543,28 @@ impl<O: ForestObligation> ObligationForest<O> { // self.nodes[i..] are unchanged for i in 0..self.nodes.len() { match self.nodes[i].state.get() { + NodeState::Pending | NodeState::Waiting => { + if dead_nodes > 0 { + self.nodes.swap(i, i - dead_nodes); + node_rewrites[i] -= dead_nodes; + } + } NodeState::Done => { self.waiting_cache.remove(self.nodes[i].obligation.as_predicate()); // FIXME(HashMap): why can't I get my key back? self.done_cache.insert(self.nodes[i].obligation.as_predicate().clone()); + node_rewrites[i] = nodes_len; + dead_nodes += 1; } NodeState::Error => { // We *intentionally* remove the node from the cache at this point. Otherwise // tests must come up with a different type on every type error they // check against. self.waiting_cache.remove(self.nodes[i].obligation.as_predicate()); + node_rewrites[i] = nodes_len; + dead_nodes += 1; } - _ => {} - } - - if self.nodes[i].is_popped() { - node_rewrites[i] = nodes_len; - dead_nodes += 1; - } else { - if dead_nodes > 0 { - self.nodes.swap(i, i - dead_nodes); - node_rewrites[i] -= dead_nodes; - } + NodeState::OnDfsStack | NodeState::Success => unreachable!() } } @@ -633,12 +644,4 @@ impl<O> Node<O> { dependents: vec![], } } - - fn is_popped(&self) -> bool { - match self.state.get() { - NodeState::Pending | NodeState::Waiting => false, - NodeState::Error | NodeState::Done => true, - NodeState::OnDfsStack | NodeState::Success => unreachable!() - } - } } diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 10ff7dc89f9..289a7348cc8 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -101,8 +101,8 @@ impl PpMode { pub fn needs_analysis(&self) -> bool { match *self { - PpmMir | PpmMirCFG | PpmFlowGraph(_) => true, - _ => false, + PpmMir | PpmMirCFG | PpmFlowGraph(_) => true, + _ => false, } } } @@ -233,14 +233,11 @@ impl PpSourceMode { arenas, id, |tcx, _, _, _| { - let annotation = TypedAnnotation { - tcx: tcx, - }; + let annotation = TypedAnnotation { tcx: tcx }; let _ignore = tcx.dep_graph.in_ignore(); - f(&annotation, - payload, - ast_map.forest.krate()) - }), sess) + f(&annotation, payload, ast_map.forest.krate()) + }), + sess) } _ => panic!("Should use call_with_pp_support"), } @@ -281,9 +278,11 @@ trait HirPrinterSupport<'ast>: pprust_hir::PpAnn { /// Computes an user-readable representation of a path, if possible. fn node_path(&self, id: ast::NodeId) -> Option<String> { self.ast_map().and_then(|map| map.def_path_from_id(id)).map(|path| { - path.data.into_iter().map(|elem| { - elem.data.to_string() - }).collect::<Vec<_>>().join("::") + path.data + .into_iter() + .map(|elem| elem.data.to_string()) + .collect::<Vec<_>>() + .join("::") }) } } @@ -352,7 +351,8 @@ impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> { } fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { match node { - pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()), + pprust::NodeIdent(_) | + pprust::NodeName(_) => Ok(()), pprust::NodeItem(item) => { pp::space(&mut s.s)?; @@ -617,15 +617,14 @@ impl ReplaceBodyWithLoop { impl fold::Folder for ReplaceBodyWithLoop { fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind { match i { - ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => { + ast::ItemKind::Static(..) | + ast::ItemKind::Const(..) => { self.within_static_or_const = true; let ret = fold::noop_fold_item_kind(i, self); self.within_static_or_const = false; return ret; } - _ => { - fold::noop_fold_item_kind(i, self) - } + _ => fold::noop_fold_item_kind(i, self), } } @@ -656,11 +655,15 @@ impl fold::Folder for ReplaceBodyWithLoop { fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> { fn expr_to_block(rules: ast::BlockCheckMode, e: Option<P<ast::Expr>>) -> P<ast::Block> { P(ast::Block { - stmts: e.map(|e| ast::Stmt { - id: ast::DUMMY_NODE_ID, - span: e.span, - node: ast::StmtKind::Expr(e), - }).into_iter().collect(), + stmts: e.map(|e| { + ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: e.span, + node: ast::StmtKind::Expr(e), + } + }) + .into_iter() + .collect(), rules: rules, id: ast::DUMMY_NODE_ID, span: syntax_pos::DUMMY_SP, @@ -721,9 +724,7 @@ fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>, } blocks::FnLikeCode(fn_like) => { let (bccx, analysis_data) = - borrowck::build_borrowck_dataflow_data_for_fn(tcx, - fn_like.to_fn_parts(), - &cfg); + borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.to_fn_parts(), &cfg); let lcfg = borrowck_dot::DataflowLabeller { inner: lcfg, @@ -756,13 +757,13 @@ pub fn fold_crate(krate: ast::Crate, ppm: PpMode) -> ast::Crate { fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, String) { let src_name = driver::source_name(input); let src = sess.codemap() - .get_filemap(&src_name) - .unwrap() - .src - .as_ref() - .unwrap() - .as_bytes() - .to_vec(); + .get_filemap(&src_name) + .unwrap() + .src + .as_ref() + .unwrap() + .as_bytes() + .to_vec(); (src, src_name) } @@ -795,17 +796,18 @@ pub fn print_after_parsing(sess: &Session, // Silently ignores an identified node. let out: &mut Write = &mut out; s.call_with_pp_support(sess, None, box out, |annotation, out| { - debug!("pretty printing source code {:?}", s); - let sess = annotation.sess(); - pprust::print_crate(sess.codemap(), - sess.diagnostic(), - krate, - src_name.to_string(), - &mut rdr, - out, - annotation.pp_ann(), - false) - }).unwrap() + debug!("pretty printing source code {:?}", s); + let sess = annotation.sess(); + pprust::print_crate(sess.codemap(), + sess.diagnostic(), + krate, + src_name.to_string(), + &mut rdr, + out, + annotation.pp_ann(), + false) + }) + .unwrap() } else { unreachable!(); }; @@ -828,8 +830,15 @@ pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session, let _ignore = dep_graph.in_ignore(); if ppm.needs_analysis() { - print_with_analysis(sess, ast_map, analysis, resolutions, - crate_name, arenas, ppm, opt_uii, ofile); + print_with_analysis(sess, + ast_map, + analysis, + resolutions, + crate_name, + arenas, + ppm, + opt_uii, + ofile); return; } @@ -839,82 +848,82 @@ pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session, let mut out = Vec::new(); match (ppm, opt_uii) { - (PpmSource(s), _) => { - // Silently ignores an identified node. - let out: &mut Write = &mut out; - s.call_with_pp_support(sess, Some(ast_map), box out, |annotation, out| { - debug!("pretty printing source code {:?}", s); - let sess = annotation.sess(); - pprust::print_crate(sess.codemap(), - sess.diagnostic(), - krate, - src_name.to_string(), - &mut rdr, - out, - annotation.pp_ann(), - true) - }) - } + (PpmSource(s), _) => { + // Silently ignores an identified node. + let out: &mut Write = &mut out; + s.call_with_pp_support(sess, Some(ast_map), box out, |annotation, out| { + debug!("pretty printing source code {:?}", s); + let sess = annotation.sess(); + pprust::print_crate(sess.codemap(), + sess.diagnostic(), + krate, + src_name.to_string(), + &mut rdr, + out, + annotation.pp_ann(), + true) + }) + } - (PpmHir(s), None) => { - let out: &mut Write = &mut out; - s.call_with_pp_support_hir(sess, - ast_map, - analysis, - resolutions, - arenas, - crate_name, - box out, - |annotation, out, krate| { - debug!("pretty printing source code {:?}", s); - let sess = annotation.sess(); - pprust_hir::print_crate(sess.codemap(), - sess.diagnostic(), - krate, - src_name.to_string(), - &mut rdr, - out, - annotation.pp_ann(), - true) - }) - } + (PpmHir(s), None) => { + let out: &mut Write = &mut out; + s.call_with_pp_support_hir(sess, + ast_map, + analysis, + resolutions, + arenas, + crate_name, + box out, + |annotation, out, krate| { + debug!("pretty printing source code {:?}", s); + let sess = annotation.sess(); + pprust_hir::print_crate(sess.codemap(), + sess.diagnostic(), + krate, + src_name.to_string(), + &mut rdr, + out, + annotation.pp_ann(), + true) + }) + } - (PpmHir(s), Some(uii)) => { - let out: &mut Write = &mut out; - s.call_with_pp_support_hir(sess, - ast_map, - analysis, - resolutions, - arenas, - crate_name, - (out,uii), - |annotation, (out,uii), _| { - debug!("pretty printing source code {:?}", s); - let sess = annotation.sess(); - let ast_map = annotation.ast_map().expect("--unpretty missing HIR map"); - let mut pp_state = - pprust_hir::State::new_from_input(sess.codemap(), - sess.diagnostic(), - src_name.to_string(), - &mut rdr, - box out, - annotation.pp_ann(), - true, - Some(ast_map.krate())); - for node_id in uii.all_matching_node_ids(ast_map) { - let node = ast_map.get(node_id); - pp_state.print_node(&node)?; - pp::space(&mut pp_state.s)?; - let path = annotation.node_path(node_id) - .expect("--unpretty missing node paths"); - pp_state.synth_comment(path)?; - pp::hardbreak(&mut pp_state.s)?; - } - pp::eof(&mut pp_state.s) - }) - } - _ => unreachable!(), - }.unwrap(); + (PpmHir(s), Some(uii)) => { + let out: &mut Write = &mut out; + s.call_with_pp_support_hir(sess, + ast_map, + analysis, + resolutions, + arenas, + crate_name, + (out, uii), + |annotation, (out, uii), _| { + debug!("pretty printing source code {:?}", s); + let sess = annotation.sess(); + let ast_map = annotation.ast_map().expect("--unpretty missing HIR map"); + let mut pp_state = pprust_hir::State::new_from_input(sess.codemap(), + sess.diagnostic(), + src_name.to_string(), + &mut rdr, + box out, + annotation.pp_ann(), + true, + Some(ast_map.krate())); + for node_id in uii.all_matching_node_ids(ast_map) { + let node = ast_map.get(node_id); + pp_state.print_node(&node)?; + pp::space(&mut pp_state.s)?; + let path = annotation.node_path(node_id) + .expect("--unpretty missing node paths"); + pp_state.synth_comment(path)?; + pp::hardbreak(&mut pp_state.s)?; + } + pp::eof(&mut pp_state.s) + }) + } + _ => unreachable!(), + } + .unwrap(); write_output(out, ofile); } @@ -955,27 +964,28 @@ fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session, let def_id = tcx.map.local_def_id(nodeid); match ppm { PpmMir => write_mir_pretty(tcx, iter::once(def_id), &mut out), - PpmMirCFG => { - write_mir_graphviz(tcx, iter::once(def_id), &mut out) - } + PpmMirCFG => write_mir_graphviz(tcx, iter::once(def_id), &mut out), _ => unreachable!(), }?; } else { match ppm { - PpmMir => write_mir_pretty(tcx, - tcx.mir_map.borrow().keys().into_iter(), - &mut out), - PpmMirCFG => write_mir_graphviz(tcx, - tcx.mir_map.borrow().keys().into_iter(), - &mut out), + PpmMir => { + write_mir_pretty(tcx, tcx.mir_map.borrow().keys().into_iter(), &mut out) + } + PpmMirCFG => { + write_mir_graphviz(tcx, + tcx.mir_map.borrow().keys().into_iter(), + &mut out) + } _ => unreachable!(), }?; } Ok(()) } PpmFlowGraph(mode) => { - let nodeid = nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or \ - unique path suffix (b::c::d)"); + let nodeid = + nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \ + suffix (b::c::d)"); let node = tcx.map.find(nodeid).unwrap_or_else(|| { tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid)) }); @@ -990,8 +1000,8 @@ fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session, print_flowgraph(variants, tcx, code, mode, out) } None => { - let message = format!("--pretty=flowgraph needs block, fn, or method; got \ - {:?}", + let message = format!("--pretty=flowgraph needs block, fn, or method; \ + got {:?}", node); // Point to what was found, if there's an accessible span. @@ -1004,7 +1014,9 @@ fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session, } _ => unreachable!(), } - }), sess).unwrap(); + }), + sess) + .unwrap(); write_output(out, ofile); } diff --git a/src/librustc_driver/target_features.rs b/src/librustc_driver/target_features.rs index f2020303089..ba51947a333 100644 --- a/src/librustc_driver/target_features.rs +++ b/src/librustc_driver/target_features.rs @@ -20,26 +20,11 @@ use libc::c_char; // detection code will walk past the end of the feature array, // leading to crashes. -const ARM_WHITELIST: &'static [&'static str] = &[ - "neon\0", - "vfp2\0", - "vfp3\0", - "vfp4\0", -]; +const ARM_WHITELIST: &'static [&'static str] = &["neon\0", "vfp2\0", "vfp3\0", "vfp4\0"]; -const X86_WHITELIST: &'static [&'static str] = &[ - "avx\0", - "avx2\0", - "bmi\0", - "bmi2\0", - "sse\0", - "sse2\0", - "sse3\0", - "sse4.1\0", - "sse4.2\0", - "ssse3\0", - "tbm\0", -]; +const X86_WHITELIST: &'static [&'static str] = &["avx\0", "avx2\0", "bmi\0", "bmi2\0", "sse\0", + "sse2\0", "sse3\0", "sse4.1\0", "sse4.2\0", + "ssse3\0", "tbm\0"]; /// Add `target_feature = "..."` cfgs for a variety of platform /// specific features (SSE, NEON etc.). @@ -59,7 +44,7 @@ pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session) { for feat in whitelist { assert_eq!(feat.chars().last(), Some('\0')); if unsafe { LLVMRustHasFeature(target_machine, feat.as_ptr() as *const c_char) } { - cfg.push(attr::mk_name_value_item_str(tf.clone(), intern(&feat[..feat.len()-1]))) + cfg.push(attr::mk_name_value_item_str(tf.clone(), intern(&feat[..feat.len() - 1]))) } } } diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 50903c89a58..8dc21550148 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -40,7 +40,7 @@ use syntax_pos::DUMMY_SP; use rustc::hir; -struct Env<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +struct Env<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { infcx: &'a infer::InferCtxt<'a, 'gcx, 'tcx>, } @@ -86,8 +86,7 @@ impl Emitter for ExpectErrorEmitter { fn errors(msgs: &[&str]) -> (Box<Emitter + Send>, usize) { let v = msgs.iter().map(|m| m.to_string()).collect(); - (box ExpectErrorEmitter { messages: v } as Box<Emitter + Send>, - msgs.len()) + (box ExpectErrorEmitter { messages: v } as Box<Emitter + Send>, msgs.len()) } fn test_env<F>(source_string: &str, @@ -103,8 +102,12 @@ fn test_env<F>(source_string: &str, let dep_graph = DepGraph::new(false); let _ignore = dep_graph.in_ignore(); let cstore = Rc::new(CStore::new(&dep_graph)); - let sess = session::build_session_(options, &dep_graph, None, diagnostic_handler, - Rc::new(CodeMap::new()), cstore.clone()); + let sess = session::build_session_(options, + &dep_graph, + None, + diagnostic_handler, + Rc::new(CodeMap::new()), + cstore.clone()); rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess)); let input = config::Input::Str { name: driver::anon_src(), @@ -112,9 +115,15 @@ fn test_env<F>(source_string: &str, }; let krate = driver::phase_1_parse_input(&sess, &input).unwrap(); let driver::ExpansionResult { defs, resolutions, mut hir_forest, .. } = { - driver::phase_2_configure_and_expand( - &sess, &cstore, krate, None, "test", None, MakeGlobMap::No, |_| Ok(()), - ).expect("phase 2 aborted") + driver::phase_2_configure_and_expand(&sess, + &cstore, + krate, + None, + "test", + None, + MakeGlobMap::No, + |_| Ok(())) + .expect("phase 2 aborted") }; let _ignore = dep_graph.in_ignore(); @@ -167,14 +176,22 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { let node = ast::NodeId::from_u32; let dscope = self.infcx - .tcx - .region_maps - .intern_code_extent(CodeExtentData::DestructionScope(node(1)), - region::ROOT_CODE_EXTENT); + .tcx + .region_maps + .intern_code_extent(CodeExtentData::DestructionScope(node(1)), + region::ROOT_CODE_EXTENT); self.create_region_hierarchy(&RH { - id: node(1), - sub: &[RH { id: node(10), sub: &[] }, RH { id: node(11), sub: &[] }], - }, dscope); + id: node(1), + sub: &[RH { + id: node(10), + sub: &[], + }, + RH { + id: node(11), + sub: &[], + }], + }, + dscope); } #[allow(dead_code)] // this seems like it could be useful, even if we don't use it now @@ -213,22 +230,16 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { hir::ItemStatic(..) | hir::ItemFn(..) | hir::ItemForeignMod(..) | - hir::ItemTy(..) => { - None - } + hir::ItemTy(..) => None, hir::ItemEnum(..) | hir::ItemStruct(..) | hir::ItemUnion(..) | hir::ItemTrait(..) | hir::ItemImpl(..) | - hir::ItemDefaultImpl(..) => { - None - } + hir::ItemDefaultImpl(..) => None, - hir::ItemMod(ref m) => { - search_mod(this, m, idx, names) - } + hir::ItemMod(ref m) => search_mod(this, m, idx, names), }; } } @@ -281,10 +292,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { self.infcx.tcx.mk_param(index, token::intern(&name[..])) } - pub fn re_early_bound(&self, - index: u32, - name: &'static str) - -> &'tcx ty::Region { + pub fn re_early_bound(&self, index: u32, name: &'static str) -> &'tcx ty::Region { let name = token::intern(name); self.infcx.tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { index: index, @@ -292,7 +300,9 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { })) } - pub fn re_late_bound_with_debruijn(&self, id: u32, debruijn: ty::DebruijnIndex) + pub fn re_late_bound_with_debruijn(&self, + id: u32, + debruijn: ty::DebruijnIndex) -> &'tcx ty::Region { self.infcx.tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(id))) } @@ -394,9 +404,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { self.assert_eq(t, t_lub); } - Err(ref e) => { - panic!("unexpected error in LUB: {}", e) - } + Err(ref e) => panic!("unexpected error in LUB: {}", e), } } @@ -404,9 +412,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { pub fn check_glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_glb: Ty<'tcx>) { debug!("check_glb(t1={}, t2={}, t_glb={})", t1, t2, t_glb); match self.glb(t1, t2) { - Err(e) => { - panic!("unexpected error computing LUB: {:?}", e) - } + Err(e) => panic!("unexpected error computing LUB: {:?}", e), Ok(InferOk { obligations, value: t }) => { // FIXME(#32730) once obligations are being propagated, assert the right thing. assert!(obligations.is_empty()); diff --git a/src/librustc_incremental/calculate_svh/svh_visitor.rs b/src/librustc_incremental/calculate_svh/svh_visitor.rs index 51c894e1b78..80c41f855ba 100644 --- a/src/librustc_incremental/calculate_svh/svh_visitor.rs +++ b/src/librustc_incremental/calculate_svh/svh_visitor.rs @@ -21,6 +21,7 @@ use self::SawTyComponent::*; use self::SawTraitOrImplItemComponent::*; use syntax::abi::Abi; use syntax::ast::{self, Name, NodeId}; +use syntax::attr; use syntax::parse::token; use syntax_pos::{Span, NO_EXPANSION, COMMAND_LINE_EXPN, BytePos}; use rustc::hir; @@ -53,6 +54,7 @@ pub struct StrictVersionHashVisitor<'a, 'hash: 'a, 'tcx: 'hash> { def_path_hashes: &'a mut DefPathHashes<'hash, 'tcx>, hash_spans: bool, codemap: &'a mut CachingCodemapView<'tcx>, + overflow_checks_enabled: bool, } impl<'a, 'hash, 'tcx> StrictVersionHashVisitor<'a, 'hash, 'tcx> { @@ -62,12 +64,16 @@ impl<'a, 'hash, 'tcx> StrictVersionHashVisitor<'a, 'hash, 'tcx> { codemap: &'a mut CachingCodemapView<'tcx>, hash_spans: bool) -> Self { + let check_overflow = tcx.sess.opts.debugging_opts.force_overflow_checks + .unwrap_or(tcx.sess.opts.debug_assertions); + StrictVersionHashVisitor { st: st, tcx: tcx, def_path_hashes: def_path_hashes, hash_spans: hash_spans, codemap: codemap, + overflow_checks_enabled: check_overflow, } } @@ -83,7 +89,6 @@ impl<'a, 'hash, 'tcx> StrictVersionHashVisitor<'a, 'hash, 'tcx> { // Also note that we are hashing byte offsets for the column, not unicode // codepoint offsets. For the purpose of the hash that's sufficient. fn hash_span(&mut self, span: Span) { - debug_assert!(self.hash_spans); debug!("hash_span: st={:?}", self.st); // If this is not an empty or invalid span, we want to hash the last @@ -241,37 +246,80 @@ enum SawExprComponent<'a> { SawExprRepeat, } -fn saw_expr<'a>(node: &'a Expr_) -> SawExprComponent<'a> { +// The boolean returned indicates whether the span of this expression is always +// significant, regardless of debuginfo. +fn saw_expr<'a>(node: &'a Expr_, + overflow_checks_enabled: bool) + -> (SawExprComponent<'a>, bool) { + let binop_can_panic_at_runtime = |binop| { + match binop { + BiAdd | + BiSub | + BiMul => overflow_checks_enabled, + + BiDiv | + BiRem => true, + + BiAnd | + BiOr | + BiBitXor | + BiBitAnd | + BiBitOr | + BiShl | + BiShr | + BiEq | + BiLt | + BiLe | + BiNe | + BiGe | + BiGt => false + } + }; + + let unop_can_panic_at_runtime = |unop| { + match unop { + UnDeref | + UnNot => false, + UnNeg => overflow_checks_enabled, + } + }; + match *node { - ExprBox(..) => SawExprBox, - ExprArray(..) => SawExprArray, - ExprCall(..) => SawExprCall, - ExprMethodCall(..) => SawExprMethodCall, - ExprTup(..) => SawExprTup, - ExprBinary(op, ..) => SawExprBinary(op.node), - ExprUnary(op, _) => SawExprUnary(op), - ExprLit(ref lit) => SawExprLit(lit.node.clone()), - ExprCast(..) => SawExprCast, - ExprType(..) => SawExprType, - ExprIf(..) => SawExprIf, - ExprWhile(..) => SawExprWhile, - ExprLoop(_, id) => SawExprLoop(id.map(|id| id.node.as_str())), - ExprMatch(..) => SawExprMatch, - ExprClosure(cc, _, _, _) => SawExprClosure(cc), - ExprBlock(..) => SawExprBlock, - ExprAssign(..) => SawExprAssign, - ExprAssignOp(op, ..) => SawExprAssignOp(op.node), - ExprField(_, name) => SawExprField(name.node.as_str()), - ExprTupField(_, id) => SawExprTupField(id.node), - ExprIndex(..) => SawExprIndex, - ExprPath(ref qself, _) => SawExprPath(qself.as_ref().map(|q| q.position)), - ExprAddrOf(m, _) => SawExprAddrOf(m), - ExprBreak(id) => SawExprBreak(id.map(|id| id.node.as_str())), - ExprAgain(id) => SawExprAgain(id.map(|id| id.node.as_str())), - ExprRet(..) => SawExprRet, - ExprInlineAsm(ref a,..) => SawExprInlineAsm(a), - ExprStruct(..) => SawExprStruct, - ExprRepeat(..) => SawExprRepeat, + ExprBox(..) => (SawExprBox, false), + ExprArray(..) => (SawExprArray, false), + ExprCall(..) => (SawExprCall, false), + ExprMethodCall(..) => (SawExprMethodCall, false), + ExprTup(..) => (SawExprTup, false), + ExprBinary(op, ..) => { + (SawExprBinary(op.node), binop_can_panic_at_runtime(op.node)) + } + ExprUnary(op, _) => { + (SawExprUnary(op), unop_can_panic_at_runtime(op)) + } + ExprLit(ref lit) => (SawExprLit(lit.node.clone()), false), + ExprCast(..) => (SawExprCast, false), + ExprType(..) => (SawExprType, false), + ExprIf(..) => (SawExprIf, false), + ExprWhile(..) => (SawExprWhile, false), + ExprLoop(_, id) => (SawExprLoop(id.map(|id| id.node.as_str())), false), + ExprMatch(..) => (SawExprMatch, false), + ExprClosure(cc, _, _, _) => (SawExprClosure(cc), false), + ExprBlock(..) => (SawExprBlock, false), + ExprAssign(..) => (SawExprAssign, false), + ExprAssignOp(op, ..) => { + (SawExprAssignOp(op.node), binop_can_panic_at_runtime(op.node)) + } + ExprField(_, name) => (SawExprField(name.node.as_str()), false), + ExprTupField(_, id) => (SawExprTupField(id.node), false), + ExprIndex(..) => (SawExprIndex, true), + ExprPath(ref qself, _) => (SawExprPath(qself.as_ref().map(|q| q.position)), false), + ExprAddrOf(m, _) => (SawExprAddrOf(m), false), + ExprBreak(id) => (SawExprBreak(id.map(|id| id.node.as_str())), false), + ExprAgain(id) => (SawExprAgain(id.map(|id| id.node.as_str())), false), + ExprRet(..) => (SawExprRet, false), + ExprInlineAsm(ref a,..) => (SawExprInlineAsm(a), false), + ExprStruct(..) => (SawExprStruct, false), + ExprRepeat(..) => (SawExprRepeat, false), } } @@ -421,10 +469,13 @@ macro_rules! hash_attrs { macro_rules! hash_span { ($visitor:expr, $span:expr) => ({ - if $visitor.hash_spans { + hash_span!($visitor, $span, false) + }); + ($visitor:expr, $span:expr, $force:expr) => ({ + if $force || $visitor.hash_spans { $visitor.hash_span($span); } - }) + }); } impl<'a, 'hash, 'tcx> visit::Visitor<'tcx> for StrictVersionHashVisitor<'a, 'hash, 'tcx> { @@ -474,10 +525,12 @@ impl<'a, 'hash, 'tcx> visit::Visitor<'tcx> for StrictVersionHashVisitor<'a, 'has fn visit_expr(&mut self, ex: &'tcx Expr) { debug!("visit_expr: st={:?}", self.st); - SawExpr(saw_expr(&ex.node)).hash(self.st); + let (saw_expr, force_span) = saw_expr(&ex.node, + self.overflow_checks_enabled); + SawExpr(saw_expr).hash(self.st); // No need to explicitly hash the discriminant here, since we are // implicitly hashing the discriminant of SawExprComponent. - hash_span!(self, ex.span); + hash_span!(self, ex.span, force_span); hash_attrs!(self, &ex.attrs); visit::walk_expr(self, ex) } @@ -519,6 +572,9 @@ impl<'a, 'hash, 'tcx> visit::Visitor<'tcx> for StrictVersionHashVisitor<'a, 'has fn visit_item(&mut self, i: &'tcx Item) { debug!("visit_item: {:?} st={:?}", i, self.st); + + self.maybe_enable_overflow_checks(&i.attrs); + SawItem(saw_item(&i.node)).hash(self.st); hash_span!(self, i.span); hash_attrs!(self, &i.attrs); @@ -545,6 +601,9 @@ impl<'a, 'hash, 'tcx> visit::Visitor<'tcx> for StrictVersionHashVisitor<'a, 'has fn visit_trait_item(&mut self, ti: &'tcx TraitItem) { debug!("visit_trait_item: st={:?}", self.st); + + self.maybe_enable_overflow_checks(&ti.attrs); + SawTraitItem(saw_trait_item(&ti.node)).hash(self.st); hash_span!(self, ti.span); hash_attrs!(self, &ti.attrs); @@ -553,6 +612,9 @@ impl<'a, 'hash, 'tcx> visit::Visitor<'tcx> for StrictVersionHashVisitor<'a, 'has fn visit_impl_item(&mut self, ii: &'tcx ImplItem) { debug!("visit_impl_item: st={:?}", self.st); + + self.maybe_enable_overflow_checks(&ii.attrs); + SawImplItem(saw_impl_item(&ii.node)).hash(self.st); hash_span!(self, ii.span); hash_attrs!(self, &ii.attrs); @@ -842,4 +904,10 @@ impl<'a, 'hash, 'tcx> StrictVersionHashVisitor<'a, 'hash, 'tcx> { indices.sort_by_key(|index| get_key(&items[*index])); indices } + + fn maybe_enable_overflow_checks(&mut self, item_attrs: &[ast::Attribute]) { + if attr::contains_name(item_attrs, "rustc_inherit_overflow_checks") { + self.overflow_checks_enabled = true; + } + } } diff --git a/src/librustc_incremental/persist/load.rs b/src/librustc_incremental/persist/load.rs index 1f43e79ace3..7cef246b6cb 100644 --- a/src/librustc_incremental/persist/load.rs +++ b/src/librustc_incremental/persist/load.rs @@ -32,8 +32,6 @@ use super::file_format; pub type DirtyNodes = FnvHashSet<DepNode<DefPathIndex>>; -type CleanEdges = Vec<(DepNode<DefId>, DepNode<DefId>)>; - /// If we are in incremental mode, and a previous dep-graph exists, /// then load up those nodes/edges that are still valid into the /// dep-graph for this session. (This is assumed to be running very diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index eee34324a65..a28109c1471 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -1189,7 +1189,7 @@ impl LateLintPass for MutableTransmutes { fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) { use syntax::abi::Abi::RustIntrinsic; - let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\ + let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \ consider instead using an UnsafeCell"; match get_transmute_from_to(cx, expr) { Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => { diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index f4558a2871d..e72ac841994 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -340,10 +340,10 @@ impl<'a> CrateLoader<'a> { target: &self.sess.target.target, triple: &self.sess.opts.target_triple, root: root, - rejected_via_hash: vec!(), - rejected_via_triple: vec!(), - rejected_via_kind: vec!(), - rejected_via_version: vec!(), + rejected_via_hash: vec![], + rejected_via_triple: vec![], + rejected_via_kind: vec![], + rejected_via_version: vec![], should_match_name: true, }; match self.load(&mut locate_ctxt) { @@ -481,10 +481,10 @@ impl<'a> CrateLoader<'a> { target: &self.sess.host, triple: config::host_triple(), root: &None, - rejected_via_hash: vec!(), - rejected_via_triple: vec!(), - rejected_via_kind: vec!(), - rejected_via_version: vec!(), + rejected_via_hash: vec![], + rejected_via_triple: vec![], + rejected_via_kind: vec![], + rejected_via_version: vec![], should_match_name: true, }; let library = self.load(&mut locate_ctxt).or_else(|| { diff --git a/src/librustc_plugin/registry.rs b/src/librustc_plugin/registry.rs index 9c74a644c3d..88e248e2efa 100644 --- a/src/librustc_plugin/registry.rs +++ b/src/librustc_plugin/registry.rs @@ -73,12 +73,12 @@ impl<'a> Registry<'a> { sess: sess, args_hidden: None, krate_span: krate_span, - syntax_exts: vec!(), - early_lint_passes: vec!(), - late_lint_passes: vec!(), + syntax_exts: vec![], + early_lint_passes: vec![], + late_lint_passes: vec![], lint_groups: HashMap::new(), - llvm_passes: vec!(), - attributes: vec!(), + llvm_passes: vec![], + attributes: vec![], mir_passes: Vec::new(), } } diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 4ffe2fe3856..77b3e76fc54 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -859,9 +859,6 @@ impl<'a, 'tcx, 'v> Visitor<'v> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> // expression/block context can't possibly contain exported things. // (Making them no-ops stops us from traversing the whole AST without // having to be super careful about our `walk_...` calls above.) - // FIXME(#29524): Unfortunately this ^^^ is not true, blocks can contain - // exported items (e.g. impls) and actual code in rustc itself breaks - // if we don't traverse blocks in `EmbargoVisitor` fn visit_block(&mut self, _: &hir::Block) {} fn visit_expr(&mut self, _: &hir::Expr) {} } diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 1fb5db05dd5..5eb269030a0 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -1461,6 +1461,47 @@ match r { ``` "##, +E0532: r##" +Pattern arm did not match expected kind. + +Erroneous code example: + +```compile_fail,E0532 +enum State { + Succeeded, + Failed(String), +} + +fn print_on_failure(state: &State) { + match *state { + // error: expected unit struct/variant or constant, found tuple + // variant `State::Failed` + State::Failed => println!("Failed"), + _ => () + } +} +``` + +To fix this error, ensure the match arm kind is the same as the expression +matched. + +Fixed example: + +``` +enum State { + Succeeded, + Failed(String), +} + +fn print_on_failure(state: &State) { + match *state { + State::Failed(ref msg) => println!("Failed with {}", msg), + _ => () + } +} +``` +"##, + } register_diagnostics! { @@ -1480,6 +1521,5 @@ register_diagnostics! { // E0421, merged into 531 // E0422, merged into 531/532 E0531, // unresolved pattern path kind `name` - E0532, // expected pattern path kind, found another pattern path kind // E0427, merged into 530 } diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index 72e5823598e..ed46c1d96ad 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -12,7 +12,6 @@ use {Module, Resolver}; use build_reduced_graph::BuildReducedGraphVisitor; use rustc::hir::def_id::{CRATE_DEF_INDEX, DefIndex}; use rustc::hir::map::{self, DefCollector}; -use rustc::util::nodemap::FnvHashMap; use std::cell::Cell; use std::rc::Rc; use syntax::ast; @@ -80,8 +79,6 @@ pub struct LegacyBinding<'a> { span: Span, } -pub type LegacyImports = FnvHashMap<ast::Name, (Rc<SyntaxExtension>, Span)>; - impl<'a> base::Resolver for Resolver<'a> { fn next_node_id(&mut self) -> ast::NodeId { self.session.next_node_id() diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 73d0e5e50c6..8a628289b7f 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -153,7 +153,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { // What could go wrong...? if spans.len() < path.segments.len() { if generated_code(path.span) { - return vec!(); + return vec![]; } error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:", path_to_string(path), @@ -167,12 +167,12 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { loc.line); } error!(" master span: {:?}: `{}`", path.span, self.span.snippet(path.span)); - return vec!(); + return vec![]; } - let mut result: Vec<(Span, String)> = vec!(); + let mut result: Vec<(Span, String)> = vec![]; - let mut segs = vec!(); + let mut segs = vec![]; for (i, (seg, span)) in path.segments.iter().zip(&spans).enumerate() { segs.push(seg.clone()); let sub_path = ast::Path { diff --git a/src/librustc_save_analysis/span_utils.rs b/src/librustc_save_analysis/span_utils.rs index 22c087aba80..031b9a6a5aa 100644 --- a/src/librustc_save_analysis/span_utils.rs +++ b/src/librustc_save_analysis/span_utils.rs @@ -225,7 +225,7 @@ impl<'a> SpanUtils<'a> { // Nesting = 0: all idents outside of brackets: [Foo] // Nesting = 1: idents within one level of brackets: [Bar, Bar] pub fn spans_with_brackets(&self, span: Span, nesting: isize, limit: isize) -> Vec<Span> { - let mut result: Vec<Span> = vec!(); + let mut result: Vec<Span> = vec![]; let mut toks = self.retokenise_span(span); // We keep track of how many brackets we're nested in @@ -236,7 +236,7 @@ impl<'a> SpanUtils<'a> { if ts.tok == token::Eof { if bracket_count != 0 { if generated_code(span) { - return vec!(); + return vec![]; } let loc = self.sess.codemap().lookup_char_pos(span.lo); span_bug!(span, diff --git a/src/librustc_trans/adt.rs b/src/librustc_trans/adt.rs index c6f3ef0a5be..4d3361c1873 100644 --- a/src/librustc_trans/adt.rs +++ b/src/librustc_trans/adt.rs @@ -48,7 +48,6 @@ use std; use llvm::{ValueRef, True, IntEQ, IntNE}; use rustc::ty::layout; use rustc::ty::{self, Ty, AdtKind}; -use syntax::attr; use build::*; use common::*; use debuginfo::DebugLoc; @@ -66,8 +65,6 @@ pub enum BranchKind { Single } -type Hint = attr::ReprAttr; - #[derive(Copy, Clone)] pub struct MaybeSizedValue { pub value: ValueRef, @@ -119,9 +116,6 @@ fn compute_fields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, } } -/// This represents the (GEP) indices to follow to get to the discriminant field -pub type DiscrField = Vec<usize>; - /// LLVM-level types are a little complicated. /// /// C-like enums need to be actual ints, not wrapped in a struct, diff --git a/src/librustc_trans/asm.rs b/src/librustc_trans/asm.rs index 308118b1fbc..8c704cc3299 100644 --- a/src/librustc_trans/asm.rs +++ b/src/librustc_trans/asm.rs @@ -61,7 +61,7 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, // Default per-arch clobbers // Basically what clang does let arch_clobbers = match &bcx.sess().target.target.arch[..] { - "x86" | "x86_64" => vec!("~{dirflag}", "~{fpsr}", "~{flags}"), + "x86" | "x86_64" => vec!["~{dirflag}", "~{fpsr}", "~{flags}"], _ => Vec::new() }; diff --git a/src/librustc_trans/back/rpath.rs b/src/librustc_trans/back/rpath.rs index 4ed860bd40d..8758cdcf9d0 100644 --- a/src/librustc_trans/back/rpath.rs +++ b/src/librustc_trans/back/rpath.rs @@ -68,7 +68,7 @@ fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec<String> { let rel_rpaths = get_rpaths_relative_to_output(config, libs); // And a final backup rpath to the global library location. - let fallback_rpaths = vec!(get_install_prefix_rpath(config)); + let fallback_rpaths = vec![get_install_prefix_rpath(config)]; fn log_rpaths(desc: &str, rpaths: &[String]) { debug!("{} rpaths:", desc); diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 04b814e2b97..9012914deeb 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -665,7 +665,7 @@ pub fn run_passes(sess: &Session, // Figure out what we actually need to build. let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone()); - let mut metadata_config = ModuleConfig::new(tm, vec!()); + let mut metadata_config = ModuleConfig::new(tm, vec![]); modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize)); modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize)); diff --git a/src/librustc_trans/cleanup.rs b/src/librustc_trans/cleanup.rs index d368ce47430..b9f24eba9dc 100644 --- a/src/librustc_trans/cleanup.rs +++ b/src/librustc_trans/cleanup.rs @@ -305,7 +305,7 @@ impl<'blk, 'tcx> FunctionContext<'blk, 'tcx> { assert!(orig_scopes_len > 0); // Remove any scopes that do not have cleanups on panic: - let mut popped_scopes = vec!(); + let mut popped_scopes = vec![]; while !self.top_scope(|s| s.needs_invoke()) { debug!("top scope does not need invoke"); popped_scopes.push(self.pop_scope()); @@ -402,7 +402,7 @@ impl<'blk, 'tcx> FunctionContext<'blk, 'tcx> { let orig_scopes_len = self.scopes_len(); let mut prev_llbb; - let mut popped_scopes = vec!(); + let mut popped_scopes = vec![]; let mut skip = 0; // First we pop off all the cleanup stacks that are @@ -585,8 +585,8 @@ impl<'tcx> CleanupScope<'tcx> { fn new(debug_loc: DebugLoc) -> CleanupScope<'tcx> { CleanupScope { debug_loc: debug_loc, - cleanups: vec!(), - cached_early_exits: vec!(), + cleanups: vec![], + cached_early_exits: vec![], cached_landing_pad: None, } } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 8799050b1b9..1aa502fc443 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -171,8 +171,6 @@ struct ConvertedBinding<'tcx> { span: Span, } -type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>); - /// Dummy type used for the `Self` of a `TraitRef` created for converting /// a trait object, and which gets removed in `ExistentialTraitRef`. /// This type must not appear anywhere in other converted types. diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index cbe3893fbf6..7d2547ec17f 100644 --- a/src/librustc_typeck/check/intrinsic.rs +++ b/src/librustc_typeck/check/intrinsic.rs @@ -86,18 +86,18 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { //We only care about the operation here let (n_tps, inputs, output) = match split[1] { - "cxchg" | "cxchgweak" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), + "cxchg" | "cxchgweak" => (1, vec![tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0), - param(ccx, 0)), + param(ccx, 0)], tcx.intern_tup(&[param(ccx, 0), tcx.types.bool])), - "load" => (1, vec!(tcx.mk_imm_ptr(param(ccx, 0))), + "load" => (1, vec![tcx.mk_imm_ptr(param(ccx, 0))], param(ccx, 0)), - "store" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)), + "store" => (1, vec![tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)], tcx.mk_nil()), "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" | "min" | "umax" | "umin" => { - (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)), + (1, vec![tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)], param(ccx, 0)) } "fence" | "singlethreadfence" => { @@ -129,14 +129,14 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { "rustc_peek" => (1, vec![param(ccx, 0)], param(ccx, 0)), "init" => (1, Vec::new(), param(ccx, 0)), "uninit" => (1, Vec::new(), param(ccx, 0)), - "forget" => (1, vec!( param(ccx, 0) ), tcx.mk_nil()), - "transmute" => (2, vec!( param(ccx, 0) ), param(ccx, 1)), + "forget" => (1, vec![ param(ccx, 0) ], tcx.mk_nil()), + "transmute" => (2, vec![ param(ccx, 0) ], param(ccx, 1)), "move_val_init" => { (1, - vec!( + vec![ tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0) - ), + ], tcx.mk_nil()) } "drop_in_place" => { @@ -148,13 +148,13 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { "type_id" => (1, Vec::new(), ccx.tcx.types.u64), "offset" | "arith_offset" => { (1, - vec!( + vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(ccx, 0), mutbl: hir::MutImmutable }), ccx.tcx.types.isize - ), + ], tcx.mk_ptr(ty::TypeAndMut { ty: param(ccx, 0), mutbl: hir::MutImmutable @@ -162,7 +162,7 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { } "copy" | "copy_nonoverlapping" => { (1, - vec!( + vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(ccx, 0), mutbl: hir::MutImmutable @@ -172,12 +172,12 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { mutbl: hir::MutMutable }), tcx.types.usize, - ), + ], tcx.mk_nil()) } "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => { (1, - vec!( + vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(ccx, 0), mutbl: hir::MutMutable @@ -187,93 +187,93 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { mutbl: hir::MutImmutable }), tcx.types.usize, - ), + ], tcx.mk_nil()) } "write_bytes" | "volatile_set_memory" => { (1, - vec!( + vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(ccx, 0), mutbl: hir::MutMutable }), tcx.types.u8, tcx.types.usize, - ), + ], tcx.mk_nil()) } - "sqrtf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "sqrtf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), + "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "powif32" => { (0, - vec!( tcx.types.f32, tcx.types.i32 ), + vec![ tcx.types.f32, tcx.types.i32 ], tcx.types.f32) } "powif64" => { (0, - vec!( tcx.types.f64, tcx.types.i32 ), + vec![ tcx.types.f64, tcx.types.i32 ], tcx.types.f64) } - "sinf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "sinf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "cosf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "cosf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), + "sinf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "sinf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "cosf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "cosf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "powf32" => { (0, - vec!( tcx.types.f32, tcx.types.f32 ), + vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32) } "powf64" => { (0, - vec!( tcx.types.f64, tcx.types.f64 ), + vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64) } - "expf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "expf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "exp2f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "exp2f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "logf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "logf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "log10f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "log10f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "log2f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "log2f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), + "expf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "expf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "exp2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "exp2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "logf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "logf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "log10f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "log10f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "log2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "log2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "fmaf32" => { (0, - vec!( tcx.types.f32, tcx.types.f32, tcx.types.f32 ), + vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ], tcx.types.f32) } "fmaf64" => { (0, - vec!( tcx.types.f64, tcx.types.f64, tcx.types.f64 ), + vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ], tcx.types.f64) } - "fabsf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "fabsf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "copysignf32" => (0, vec!( tcx.types.f32, tcx.types.f32 ), tcx.types.f32), - "copysignf64" => (0, vec!( tcx.types.f64, tcx.types.f64 ), tcx.types.f64), - "floorf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "floorf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "ceilf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "ceilf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "truncf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "truncf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "rintf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "rintf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "nearbyintf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "nearbyintf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "roundf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "roundf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), + "fabsf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "fabsf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "copysignf32" => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32), + "copysignf64" => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64), + "floorf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "floorf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "ceilf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "ceilf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "truncf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "truncf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "rintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "rintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), + "roundf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), + "roundf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "volatile_load" => - (1, vec!( tcx.mk_imm_ptr(param(ccx, 0)) ), param(ccx, 0)), + (1, vec![ tcx.mk_imm_ptr(param(ccx, 0)) ], param(ccx, 0)), "volatile_store" => - (1, vec!( tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0) ), tcx.mk_nil()), + (1, vec![ tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0) ], tcx.mk_nil()), - "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec!(param(ccx, 0)), param(ccx, 0)), + "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec![param(ccx, 0)], param(ccx, 0)), "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => - (1, vec!(param(ccx, 0), param(ccx, 0)), + (1, vec![param(ccx, 0), param(ccx, 0)], tcx.intern_tup(&[param(ccx, 0), tcx.types.bool])), "unchecked_div" | "unchecked_rem" => diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 40b19b01cd9..202e176df0d 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1387,7 +1387,7 @@ fn convert_trait_predicates<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, it: &hir::Item) let bounds = match trait_item.node { hir::TypeTraitItem(ref bounds, _) => bounds, _ => { - return vec!().into_iter(); + return vec![].into_iter(); } }; diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 7752690e534..d636baca248 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -194,12 +194,12 @@ fn require_c_abi_if_variadic(tcx: TyCtxt, fn require_same_types<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, origin: TypeOrigin, - t1: Ty<'tcx>, - t2: Ty<'tcx>) + expected: Ty<'tcx>, + actual: Ty<'tcx>) -> bool { ccx.tcx.infer_ctxt(None, None, Reveal::NotSpecializable).enter(|infcx| { - if let Err(err) = infcx.eq_types(false, origin.clone(), t1, t2) { - infcx.report_mismatched_types(origin, t1, t2, err); + if let Err(err) = infcx.eq_types(false, origin.clone(), expected, actual) { + infcx.report_mismatched_types(origin, expected, actual, err); false } else { true @@ -248,8 +248,8 @@ fn check_main_fn_ty(ccx: &CrateCtxt, require_same_types( ccx, TypeOrigin::MainFunctionType(main_span), - main_t, - se_ty); + se_ty, + main_t); } _ => { span_bug!(main_span, @@ -291,10 +291,10 @@ fn check_start_fn_ty(ccx: &CrateCtxt, unsafety: hir::Unsafety::Normal, abi: Abi::Rust, sig: ty::Binder(ty::FnSig { - inputs: vec!( + inputs: vec![ tcx.types.isize, tcx.mk_imm_ptr(tcx.mk_imm_ptr(tcx.types.u8)) - ), + ], output: tcx.types.isize, variadic: false, }), @@ -303,8 +303,8 @@ fn check_start_fn_ty(ccx: &CrateCtxt, require_same_types( ccx, TypeOrigin::StartFunctionType(start_span), - start_t, - se_ty); + se_ty, + start_t); } _ => { span_bug!(start_span, diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 5ce75810006..f03b6a5ab3f 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -143,8 +143,8 @@ pub fn run_core(search_paths: SearchPaths, let sessopts = config::Options { maybe_sysroot: maybe_sysroot, search_paths: search_paths, - crate_types: vec!(config::CrateTypeRlib), - lint_opts: vec!((warning_lint, lint::Allow)), + crate_types: vec![config::CrateTypeRlib], + lint_opts: vec![(warning_lint, lint::Allow)], lint_cap: Some(lint::Allow), externs: externs, target_triple: triple.unwrap_or(config::host_triple().to_string()), diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index f12349e5b7c..67cf12f4f4a 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -644,7 +644,7 @@ mod tests { t("test_harness", false, false, false, true, true, false, Vec::new()); t("compile_fail", false, true, false, true, false, true, Vec::new()); t("E0450", false, false, false, true, false, false, - vec!("E0450".to_owned())); + vec!["E0450".to_owned()]); t("{.no_run .example}", false, true, false, true, false, false, Vec::new()); t("{.sh .should_panic}", true, false, false, true, false, false, Vec::new()); t("{.example .rust}", false, false, false, true, false, false, Vec::new()); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 77a5ff3243a..a848a011f88 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1260,7 +1260,7 @@ impl Context { item.name = Some(krate.name); // render the crate documentation - let mut work = vec!((self, item)); + let mut work = vec![(self, item)]; while let Some((mut cx, item)) = work.pop() { cx.item(item, |cx, item| { diff --git a/src/librustdoc/html/toc.rs b/src/librustdoc/html/toc.rs index 305e6258baa..a7da1c5cca4 100644 --- a/src/librustdoc/html/toc.rs +++ b/src/librustdoc/html/toc.rs @@ -247,7 +247,7 @@ mod tests { macro_rules! toc { ($(($level: expr, $name: expr, $(($sub: tt))* )),*) => { Toc { - entries: vec!( + entries: vec![ $( TocEntry { level: $level, @@ -257,7 +257,7 @@ mod tests { children: toc!($($sub),*) } ),* - ) + ] } } } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 0be36eb3a85..cf5e8e5e34a 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -111,7 +111,7 @@ fn unstable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::unstable(g) pub fn opts() -> Vec<RustcOptGroup> { use getopts::*; - vec!( + vec![ stable(optflag("h", "help", "show this help message")), stable(optflag("V", "version", "print rustdoc's version")), stable(optflag("v", "verbose", "use verbose output")), @@ -162,7 +162,7 @@ pub fn opts() -> Vec<RustcOptGroup> { unstable(optmulti("Z", "", "internal and debugging options (only on nightly build)", "FLAG")), stable(optopt("", "sysroot", "Override the system root", "PATH")), - ) + ] } pub fn usage(argv0: &str) { diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 45c3d413500..1bbd67fb9be 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -66,7 +66,7 @@ pub fn run(input: &str, maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap() .parent().unwrap().to_path_buf()), search_paths: libs.clone(), - crate_types: vec!(config::CrateTypeDylib), + crate_types: vec![config::CrateTypeDylib], externs: externs.clone(), unstable_features: UnstableFeatures::from_environment(), ..config::basic_options().clone() @@ -185,7 +185,7 @@ fn runtest(test: &str, cratename: &str, cfgs: Vec<String>, libs: SearchPaths, maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap() .parent().unwrap().to_path_buf()), search_paths: libs, - crate_types: vec!(config::CrateTypeExecutable), + crate_types: vec![config::CrateTypeExecutable], output_types: outputs, externs: externs, cg: config::CodegenOptions { diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 3e976c90628..239d32c8fc8 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -3880,8 +3880,8 @@ mod tests { use std::collections::{HashMap,BTreeMap}; use super::ToJson; - let array2 = Array(vec!(U64(1), U64(2))); - let array3 = Array(vec!(U64(1), U64(2), U64(3))); + let array2 = Array(vec![U64(1), U64(2)]); + let array3 = Array(vec![U64(1), U64(2), U64(3)]); let object = { let mut tree_map = BTreeMap::new(); tree_map.insert("a".to_string(), U64(1)); @@ -3915,7 +3915,7 @@ mod tests { assert_eq!([1_usize, 2_usize].to_json(), array2); assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3); assert_eq!((vec![1_usize, 2_usize]).to_json(), array2); - assert_eq!(vec!(1_usize, 2_usize, 3_usize).to_json(), array3); + assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3); let mut tree_map = BTreeMap::new(); tree_map.insert("a".to_string(), 1 as usize); tree_map.insert("b".to_string(), 2); diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index b357bc3552a..a784d8e50f9 100644 --- a/src/libstd/collections/hash/table.rs +++ b/src/libstd/collections/hash/table.rs @@ -21,7 +21,18 @@ use ptr::{self, Unique, Shared}; use self::BucketState::*; -const EMPTY_BUCKET: u64 = 0; +/// Integer type used for stored hash values. +/// +/// No more than bit_width(usize) bits are needed to select a bucket. +/// +/// The most significant bit is ours to use for tagging `SafeHash`. +/// +/// (Even if we could have usize::MAX bytes allocated for buckets, +/// each bucket stores at least a `HashUint`, so there can be no more than +/// usize::MAX / size_of(usize) buckets.) +type HashUint = usize; + +const EMPTY_BUCKET: HashUint = 0; /// The raw hashtable, providing safe-ish access to the unzipped and highly /// optimized arrays of hashes, and key-value pairs. @@ -64,7 +75,7 @@ const EMPTY_BUCKET: u64 = 0; pub struct RawTable<K, V> { capacity: usize, size: usize, - hashes: Unique<u64>, + hashes: Unique<HashUint>, // Because K/V do not appear directly in any of the types in the struct, // inform rustc that in fact instances of K and V are reachable from here. @@ -75,7 +86,7 @@ unsafe impl<K: Send, V: Send> Send for RawTable<K, V> {} unsafe impl<K: Sync, V: Sync> Sync for RawTable<K, V> {} struct RawBucket<K, V> { - hash: *mut u64, + hash: *mut HashUint, // We use *const to ensure covariance with respect to K and V pair: *const (K, V), _marker: marker::PhantomData<(K, V)>, @@ -113,10 +124,6 @@ pub struct FullBucket<K, V, M> { table: M, } -pub type EmptyBucketImm<'table, K, V> = EmptyBucket<K, V, &'table RawTable<K, V>>; -pub type FullBucketImm<'table, K, V> = FullBucket<K, V, &'table RawTable<K, V>>; - -pub type EmptyBucketMut<'table, K, V> = EmptyBucket<K, V, &'table mut RawTable<K, V>>; pub type FullBucketMut<'table, K, V> = FullBucket<K, V, &'table mut RawTable<K, V>>; pub enum BucketState<K, V, M> { @@ -136,15 +143,27 @@ pub struct GapThenFull<K, V, M> { /// buckets. #[derive(PartialEq, Copy, Clone)] pub struct SafeHash { - hash: u64, + hash: HashUint, } impl SafeHash { /// Peek at the hash value, which is guaranteed to be non-zero. #[inline(always)] - pub fn inspect(&self) -> u64 { + pub fn inspect(&self) -> HashUint { self.hash } + + #[inline(always)] + pub fn new(hash: u64) -> Self { + // We need to avoid 0 in order to prevent collisions with + // EMPTY_HASH. We can maintain our precious uniform distribution + // of initial indexes by unconditionally setting the MSB, + // effectively reducing the hashes by one bit. + // + // Truncate hash to fit in `HashUint`. + let hash_bits = size_of::<HashUint>() * 8; + SafeHash { hash: (1 << (hash_bits - 1)) | (hash as HashUint) } + } } /// We need to remove hashes of 0. That's reserved for empty buckets. @@ -156,25 +175,21 @@ pub fn make_hash<T: ?Sized, S>(hash_state: &S, t: &T) -> SafeHash { let mut state = hash_state.build_hasher(); t.hash(&mut state); - // We need to avoid 0 in order to prevent collisions with - // EMPTY_HASH. We can maintain our precious uniform distribution - // of initial indexes by unconditionally setting the MSB, - // effectively reducing 64-bits hashes to 63 bits. - SafeHash { hash: 0x8000_0000_0000_0000 | state.finish() } + SafeHash::new(state.finish()) } -// `replace` casts a `*u64` to a `*SafeHash`. Since we statically +// `replace` casts a `*HashUint` to a `*SafeHash`. Since we statically // ensure that a `FullBucket` points to an index with a non-zero hash, -// and a `SafeHash` is just a `u64` with a different name, this is +// and a `SafeHash` is just a `HashUint` with a different name, this is // safe. // // This test ensures that a `SafeHash` really IS the same size as a -// `u64`. If you need to change the size of `SafeHash` (and +// `HashUint`. If you need to change the size of `SafeHash` (and // consequently made this test fail), `replace` needs to be // modified to no longer assume this. #[test] -fn can_alias_safehash_as_u64() { - assert_eq!(size_of::<SafeHash>(), size_of::<u64>()) +fn can_alias_safehash_as_hash() { + assert_eq!(size_of::<SafeHash>(), size_of::<HashUint>()) } impl<K, V> RawBucket<K, V> { @@ -605,14 +620,14 @@ impl<K, V> RawTable<K, V> { return RawTable { size: 0, capacity: 0, - hashes: Unique::new(EMPTY as *mut u64), + hashes: Unique::new(EMPTY as *mut HashUint), marker: marker::PhantomData, }; } // No need for `checked_mul` before a more restrictive check performed // later in this method. - let hashes_size = capacity.wrapping_mul(size_of::<u64>()); + let hashes_size = capacity.wrapping_mul(size_of::<HashUint>()); let pairs_size = capacity.wrapping_mul(size_of::<(K, V)>()); // Allocating hashmaps is a little tricky. We need to allocate two @@ -624,13 +639,13 @@ impl<K, V> RawTable<K, V> { // right is a little subtle. Therefore, calculating offsets has been // factored out into a different function. let (alignment, hash_offset, size, oflo) = calculate_allocation(hashes_size, - align_of::<u64>(), + align_of::<HashUint>(), pairs_size, align_of::<(K, V)>()); assert!(!oflo, "capacity overflow"); // One check for overflow that covers calculation and rounding of size. - let size_of_bucket = size_of::<u64>().checked_add(size_of::<(K, V)>()).unwrap(); + let size_of_bucket = size_of::<HashUint>().checked_add(size_of::<(K, V)>()).unwrap(); assert!(size >= capacity.checked_mul(size_of_bucket) .expect("capacity overflow"), @@ -641,7 +656,7 @@ impl<K, V> RawTable<K, V> { ::alloc::oom() } - let hashes = buffer.offset(hash_offset as isize) as *mut u64; + let hashes = buffer.offset(hash_offset as isize) as *mut HashUint; RawTable { capacity: capacity, @@ -652,7 +667,7 @@ impl<K, V> RawTable<K, V> { } fn first_bucket_raw(&self) -> RawBucket<K, V> { - let hashes_size = self.capacity * size_of::<u64>(); + let hashes_size = self.capacity * size_of::<HashUint>(); let pairs_size = self.capacity * size_of::<(K, V)>(); let buffer = *self.hashes as *mut u8; @@ -756,7 +771,7 @@ impl<K, V> RawTable<K, V> { /// this interface is safe, it's not used outside this module. struct RawBuckets<'a, K, V> { raw: RawBucket<K, V>, - hashes_end: *mut u64, + hashes_end: *mut HashUint, // Strictly speaking, this should be &'a (K,V), but that would // require that K:'a, and we often use RawBuckets<'static...> for @@ -802,7 +817,7 @@ impl<'a, K, V> Iterator for RawBuckets<'a, K, V> { /// the table's remaining entries. It's used in the implementation of Drop. struct RevMoveBuckets<'a, K, V> { raw: RawBucket<K, V>, - hashes_end: *mut u64, + hashes_end: *mut HashUint, elems_left: usize, // As above, `&'a (K,V)` would seem better, but we often use @@ -1036,10 +1051,10 @@ impl<K, V> Drop for RawTable<K, V> { } } - let hashes_size = self.capacity * size_of::<u64>(); + let hashes_size = self.capacity * size_of::<HashUint>(); let pairs_size = self.capacity * size_of::<(K, V)>(); let (align, _, size, oflo) = calculate_allocation(hashes_size, - align_of::<u64>(), + align_of::<HashUint>(), pairs_size, align_of::<(K, V)>()); diff --git a/src/libstd/error.rs b/src/libstd/error.rs index a1909b0f957..454fa47cfbc 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -69,7 +69,9 @@ pub trait Error: Debug + Display { /// It should not contain newlines or sentence-ending punctuation, /// to facilitate embedding in larger user-facing strings. /// For showing formatted error messages with more information see - /// [Display](https://doc.rust-lang.org/std/fmt/trait.Display.html). + /// [`Display`]. + /// + /// [`Display`]: ../fmt/trait.Display.html /// /// # Examples /// diff --git a/src/libstd/num/f32.rs b/src/libstd/f32.rs index 7a676c041ad..7a676c041ad 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/f32.rs diff --git a/src/libstd/num/f64.rs b/src/libstd/f64.rs index 67a1c302483..67a1c302483 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/f64.rs diff --git a/src/libstd/io/cursor.rs b/src/libstd/io/cursor.rs index ca9452ffe3e..1b5023380a7 100644 --- a/src/libstd/io/cursor.rs +++ b/src/libstd/io/cursor.rs @@ -23,7 +23,7 @@ use io::{self, SeekFrom, Error, ErrorKind}; /// /// The standard library implements some I/O traits on various types which /// are commonly used as a buffer, like `Cursor<`[`Vec`]`<u8>>` and -/// `Cursor<`[`&[u8]`]`>`. +/// `Cursor<`[`&[u8]`][bytes]`>`. /// /// # Examples /// @@ -35,7 +35,7 @@ use io::{self, SeekFrom, Error, ErrorKind}; /// [`Read`]: ../../std/io/trait.Read.html /// [`Write`]: ../../std/io/trait.Write.html /// [`Vec`]: ../../std/vec/struct.Vec.html -/// [`&[u8]`]: ../../std/primitive.slice.html +/// [bytes]: ../../std/primitive.slice.html /// [`File`]: ../fs/struct.File.html /// /// ```no_run @@ -392,7 +392,7 @@ mod tests { #[test] fn test_mem_reader() { - let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7)); + let mut reader = Cursor::new(vec![0, 1, 2, 3, 4, 5, 6, 7]); let mut buf = []; assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.position(), 0); @@ -414,7 +414,7 @@ mod tests { #[test] fn test_boxed_slice_reader() { - let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7).into_boxed_slice()); + let mut reader = Cursor::new(vec![0, 1, 2, 3, 4, 5, 6, 7].into_boxed_slice()); let mut buf = []; assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.position(), 0); @@ -436,7 +436,7 @@ mod tests { #[test] fn read_to_end() { - let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7)); + let mut reader = Cursor::new(vec![0, 1, 2, 3, 4, 5, 6, 7]); let mut v = Vec::new(); reader.read_to_end(&mut v).unwrap(); assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7]); @@ -512,7 +512,7 @@ mod tests { assert_eq!(r.seek(SeekFrom::Start(10)).unwrap(), 10); assert_eq!(r.read(&mut [0]).unwrap(), 0); - let mut r = Cursor::new(vec!(10)); + let mut r = Cursor::new(vec![10]); assert_eq!(r.seek(SeekFrom::Start(10)).unwrap(), 10); assert_eq!(r.read(&mut [0]).unwrap(), 0); @@ -532,14 +532,14 @@ mod tests { let mut r = Cursor::new(&buf[..]); assert!(r.seek(SeekFrom::End(-2)).is_err()); - let mut r = Cursor::new(vec!(10)); + let mut r = Cursor::new(vec![10]); assert!(r.seek(SeekFrom::End(-2)).is_err()); let mut buf = [0]; let mut r = Cursor::new(&mut buf[..]); assert!(r.seek(SeekFrom::End(-2)).is_err()); - let mut r = Cursor::new(vec!(10).into_boxed_slice()); + let mut r = Cursor::new(vec![10].into_boxed_slice()); assert!(r.seek(SeekFrom::End(-2)).is_err()); } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 37c3f70d54d..193f396c0d4 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -289,7 +289,7 @@ mod lazy; mod util; mod stdio; -const DEFAULT_BUF_SIZE: usize = 8 * 1024; +const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE; // A few methods below (read_to_string, read_line) will append data into a // `String` buffer, but we need to be pretty careful when doing this. The diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index c24ee8ff303..1777b79ea1b 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -214,15 +214,7 @@ pub fn stdin() -> Stdin { _ => Maybe::Fake }; - // The default buffer capacity is 64k, but apparently windows - // doesn't like 64k reads on stdin. See #13304 for details, but the - // idea is that on windows we use a slightly smaller buffer that's - // been seen to be acceptable. - Arc::new(Mutex::new(if cfg!(windows) { - BufReader::with_capacity(8 * 1024, stdin) - } else { - BufReader::new(stdin) - })) + Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin))) } } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 82a719693ec..8d973fc1ade 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -210,14 +210,34 @@ test(no_crate_inject, attr(deny(warnings))), test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))] +// Don't link to std. We are std. +#![no_std] + +#![deny(missing_docs)] + +// Tell the compiler to link to either panic_abort or panic_unwind #![needs_panic_runtime] +// Always use alloc_system during stage0 since jemalloc might be unavailable or +// disabled (Issue #30592) +#![cfg_attr(stage0, feature(alloc_system))] + +// Turn warnings into errors, but only after stage0, where it can be useful for +// code to emit warnings during language transitions +#![cfg_attr(not(stage0), deny(warnings))] + +// std may use features in a platform-specific way +#![allow(unused_features)] + +// std is implemented with unstable features, many of which are internal +// compiler details that will never be stable #![feature(alloc)] #![feature(allow_internal_unstable)] #![feature(asm)] #![feature(associated_consts)] #![feature(borrow_state)] #![feature(box_syntax)] +#![feature(cfg_target_has_atomic)] #![feature(cfg_target_thread_local)] #![feature(cfg_target_vendor)] #![feature(char_escape_debug)] @@ -240,13 +260,13 @@ #![feature(heap_api)] #![feature(inclusive_range)] #![feature(int_error_internals)] +#![feature(integer_atomics)] #![feature(into_cow)] #![feature(lang_items)] #![feature(libc)] #![feature(link_args)] #![feature(linkage)] #![feature(macro_reexport)] -#![cfg_attr(test, feature(map_values_mut))] #![feature(needs_panic_runtime)] #![feature(num_bits_bytes)] #![feature(old_wrapping)] @@ -282,21 +302,13 @@ #![feature(zero_one)] #![cfg_attr(test, feature(update_panic_count))] -// Issue# 30592: Systematically use alloc_system during stage0 since jemalloc -// might be unavailable or disabled -#![cfg_attr(stage0, feature(alloc_system))] - -// Don't link to std. We are std. -#![no_std] - -#![deny(missing_docs)] -#![allow(unused_features)] // std may use features in a platform-specific way -#![cfg_attr(not(stage0), deny(warnings))] - +// Explicitly import the prelude. The compiler uses this same unstable attribute +// to import the prelude implicitly when building crates that depend on std. #[prelude_import] #[allow(unused)] use prelude::v1::*; +// Access to Bencher, etc. #[cfg(test)] extern crate test; // We want to reexport a few macros from core but libcore has already been @@ -324,11 +336,22 @@ extern crate alloc_system; // compiler-rt intrinsics extern crate compiler_builtins; -// Make std testable by not duplicating lang items and other globals. See #2912 +// During testing, this crate is not actually the "real" std library, but rather +// it links to the real std library, which was compiled from this same source +// code. So any lang items std defines are conditionally excluded (or else they +// wolud generate duplicate lang item errors), and any globals it defines are +// _not_ the globals used by "real" std. So this import, defined only during +// testing gives test-std access to real-std lang items and globals. See #2912 #[cfg(test)] extern crate std as realstd; -// NB: These reexports are in the order they should be listed in rustdoc +// The standard macros that are not built-in to the compiler. +#[macro_use] +mod macros; + +// The Rust prelude +pub mod prelude; +// Public module declarations and reexports #[stable(feature = "rust1", since = "1.0.0")] pub use core::any; #[stable(feature = "rust1", since = "1.0.0")] @@ -361,48 +384,6 @@ pub use core::raw; pub use core::result; #[stable(feature = "rust1", since = "1.0.0")] pub use core::option; - -pub mod error; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::boxed; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::rc; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use core_collections::borrow; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core_collections::fmt; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core_collections::slice; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core_collections::str; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core_collections::string; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core_collections::vec; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use rustc_unicode::char; - -/* Exported macros */ - -#[macro_use] -mod macros; - -mod rtdeps; - -/* The Prelude. */ - -pub mod prelude; - - -/* Primitive types */ - -// NB: slice and str are primitive types too, but their module docs + primitive -// doc pages are inlined from the public re-exports of core_collections::{slice, -// str} above. - #[stable(feature = "rust1", since = "1.0.0")] pub use core::isize; #[stable(feature = "rust1", since = "1.0.0")] @@ -413,7 +394,6 @@ pub use core::i16; pub use core::i32; #[stable(feature = "rust1", since = "1.0.0")] pub use core::i64; - #[stable(feature = "rust1", since = "1.0.0")] pub use core::usize; #[stable(feature = "rust1", since = "1.0.0")] @@ -424,48 +404,62 @@ pub use core::u16; pub use core::u32; #[stable(feature = "rust1", since = "1.0.0")] pub use core::u64; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc::boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc::rc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core_collections::borrow; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core_collections::fmt; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core_collections::slice; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core_collections::str; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core_collections::string; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core_collections::vec; +#[stable(feature = "rust1", since = "1.0.0")] +pub use rustc_unicode::char; -#[path = "num/f32.rs"] pub mod f32; -#[path = "num/f64.rs"] pub mod f64; - -pub mod ascii; - -/* Common traits */ - -pub mod num; - -/* Runtime and platform support */ +pub mod f32; +pub mod f64; #[macro_use] pub mod thread; - +pub mod ascii; pub mod collections; pub mod env; +pub mod error; pub mod ffi; pub mod fs; pub mod io; pub mod net; +pub mod num; pub mod os; pub mod panic; pub mod path; pub mod process; pub mod sync; pub mod time; -mod memchr; +// Platform-abstraction modules #[macro_use] -#[path = "sys/common/mod.rs"] mod sys_common; - -#[cfg(redox)] -#[path = "sys/redox/mod.rs"] mod sys; -#[cfg(unix)] -#[path = "sys/unix/mod.rs"] mod sys; -#[cfg(windows)] -#[path = "sys/windows/mod.rs"] mod sys; +mod sys_common; +mod sys; -pub mod rt; +// Private support modules mod panicking; mod rand; +mod memchr; + +// This module just defines per-platform native library dependencies +mod rtdeps; + +// The runtime entry point and a few unstable public functions used by the +// compiler +pub mod rt; // Some external utilities of the standard library rely on randomness (aka // rustc_back::TempDir and tests) and need a way to get at the OS rng we've got diff --git a/src/libstd/num/mod.rs b/src/libstd/num.rs index d1c2fc3d3fc..d1c2fc3d3fc 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num.rs diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs index 3788568a2fd..a7e8c4fab37 100644 --- a/src/libstd/panic.rs +++ b/src/libstd/panic.rs @@ -18,7 +18,7 @@ use ops::{Deref, DerefMut}; use panicking; use ptr::{Unique, Shared}; use rc::Rc; -use sync::{Arc, Mutex, RwLock}; +use sync::{Arc, Mutex, RwLock, atomic}; use thread::Result; #[stable(feature = "panic_hooks", since = "1.10.0")] @@ -231,6 +231,46 @@ impl<T: ?Sized> RefUnwindSafe for Mutex<T> {} #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")] impl<T: ?Sized> RefUnwindSafe for RwLock<T> {} +#[cfg(target_has_atomic = "ptr")] +#[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")] +impl RefUnwindSafe for atomic::AtomicIsize {} +#[cfg(target_has_atomic = "8")] +#[unstable(feature = "integer_atomics", issue = "32976")] +impl RefUnwindSafe for atomic::AtomicI8 {} +#[cfg(target_has_atomic = "16")] +#[unstable(feature = "integer_atomics", issue = "32976")] +impl RefUnwindSafe for atomic::AtomicI16 {} +#[cfg(target_has_atomic = "32")] +#[unstable(feature = "integer_atomics", issue = "32976")] +impl RefUnwindSafe for atomic::AtomicI32 {} +#[cfg(target_has_atomic = "64")] +#[unstable(feature = "integer_atomics", issue = "32976")] +impl RefUnwindSafe for atomic::AtomicI64 {} + +#[cfg(target_has_atomic = "ptr")] +#[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")] +impl RefUnwindSafe for atomic::AtomicUsize {} +#[cfg(target_has_atomic = "8")] +#[unstable(feature = "integer_atomics", issue = "32976")] +impl RefUnwindSafe for atomic::AtomicU8 {} +#[cfg(target_has_atomic = "16")] +#[unstable(feature = "integer_atomics", issue = "32976")] +impl RefUnwindSafe for atomic::AtomicU16 {} +#[cfg(target_has_atomic = "32")] +#[unstable(feature = "integer_atomics", issue = "32976")] +impl RefUnwindSafe for atomic::AtomicU32 {} +#[cfg(target_has_atomic = "64")] +#[unstable(feature = "integer_atomics", issue = "32976")] +impl RefUnwindSafe for atomic::AtomicU64 {} + +#[cfg(target_has_atomic = "8")] +#[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")] +impl RefUnwindSafe for atomic::AtomicBool {} + +#[cfg(target_has_atomic = "ptr")] +#[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")] +impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {} + #[stable(feature = "catch_unwind", since = "1.9.0")] impl<T> Deref for AssertUnwindSafe<T> { type Target = T; diff --git a/src/libstd/path.rs b/src/libstd/path.rs index a55318d3883..9b7f9980cc0 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -914,6 +914,7 @@ impl<'a> cmp::Ord for Components<'a> { /// [`Path`]: struct.Path.html /// [`push`]: struct.PathBuf.html#method.push /// [`set_extension`]: struct.PathBuf.html#method.set_extension +/// [`Deref`]: ../ops/trait.Deref.html /// /// More details about the overall approach can be found in /// the module documentation. diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index 69cd37651d5..f48325218fb 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -245,7 +245,7 @@ mod tests { #[cfg_attr(target_os = "emscripten", ignore)] fn test_os_rng_tasks() { - let mut txs = vec!(); + let mut txs = vec![]; for _ in 0..20 { let (tx, rx) = channel(); txs.push(tx); diff --git a/src/libstd/sys/mod.rs b/src/libstd/sys/mod.rs new file mode 100644 index 00000000000..c196bf39432 --- /dev/null +++ b/src/libstd/sys/mod.rs @@ -0,0 +1,45 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Platform-dependent platform abstraction +//! +//! The `std::sys` module is the abstracted interface through which +//! `std` talks to the underlying operating system. It has different +//! implementations for different operating system families, today +//! just Unix and Windows. +//! +//! The centralization of platform-specific code in this module is +//! enforced by the "platform abstraction layer" tidy script in +//! `tools/tidy/pal.rs`. +//! +//! This module is closely related to the platform-independent system +//! integration code in `std::sys_common`. See that module's +//! documentation for details. +//! +//! In the future it would be desirable for the indepedent +//! implementations of this module to be extracted to their own crates +//! that `std` can link to, thus enabling their implementation +//! out-of-tree via crate replacement. Though due to the complex +//! inter-dependencies within `std` that will be a challenging goal to +//! achieve. + +pub use self::imp::*; + +#[cfg(redox)] +#[path = "redox/mod.rs"] +mod imp; + +#[cfg(unix)] +#[path = "unix/mod.rs"] +mod imp; + +#[cfg(windows)] +#[path = "windows/mod.rs"] +mod imp; diff --git a/src/libstd/sys/unix/fast_thread_local.rs b/src/libstd/sys/unix/fast_thread_local.rs new file mode 100644 index 00000000000..0c625e7add9 --- /dev/null +++ b/src/libstd/sys/unix/fast_thread_local.rs @@ -0,0 +1,167 @@ +// 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. + +#![cfg(target_thread_local)] +#![unstable(feature = "thread_local_internals", issue = "0")] + +use cell::{Cell, UnsafeCell}; +use intrinsics; +use ptr; + +pub struct Key<T> { + inner: UnsafeCell<Option<T>>, + + // Metadata to keep track of the state of the destructor. Remember that + // these variables are thread-local, not global. + dtor_registered: Cell<bool>, + dtor_running: Cell<bool>, +} + +unsafe impl<T> ::marker::Sync for Key<T> { } + +impl<T> Key<T> { + pub const fn new() -> Key<T> { + Key { + inner: UnsafeCell::new(None), + dtor_registered: Cell::new(false), + dtor_running: Cell::new(false) + } + } + + pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> { + unsafe { + if intrinsics::needs_drop::<T>() && self.dtor_running.get() { + return None + } + self.register_dtor(); + } + Some(&self.inner) + } + + unsafe fn register_dtor(&self) { + if !intrinsics::needs_drop::<T>() || self.dtor_registered.get() { + return + } + + register_dtor(self as *const _ as *mut u8, + destroy_value::<T>); + self.dtor_registered.set(true); + } +} + +#[cfg(any(target_os = "linux", target_os = "fuchsia"))] +unsafe fn register_dtor_fallback(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { + // The fallback implementation uses a vanilla OS-based TLS key to track + // the list of destructors that need to be run for this thread. The key + // then has its own destructor which runs all the other destructors. + // + // The destructor for DTORS is a little special in that it has a `while` + // loop to continuously drain the list of registered destructors. It + // *should* be the case that this loop always terminates because we + // provide the guarantee that a TLS key cannot be set after it is + // flagged for destruction. + use sys_common::thread_local as os; + + static DTORS: os::StaticKey = os::StaticKey::new(Some(run_dtors)); + type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; + if DTORS.get().is_null() { + let v: Box<List> = box Vec::new(); + DTORS.set(Box::into_raw(v) as *mut u8); + } + let list: &mut List = &mut *(DTORS.get() as *mut List); + list.push((t, dtor)); + + unsafe extern fn run_dtors(mut ptr: *mut u8) { + while !ptr.is_null() { + let list: Box<List> = Box::from_raw(ptr as *mut List); + for &(ptr, dtor) in list.iter() { + dtor(ptr); + } + ptr = DTORS.get(); + DTORS.set(ptr::null_mut()); + } + } +} + +// Since what appears to be glibc 2.18 this symbol has been shipped which +// GCC and clang both use to invoke destructors in thread_local globals, so +// let's do the same! +// +// Note, however, that we run on lots older linuxes, as well as cross +// compiling from a newer linux to an older linux, so we also have a +// fallback implementation to use as well. +// +// Due to rust-lang/rust#18804, make sure this is not generic! +#[cfg(target_os = "linux")] +unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { + use mem; + use libc; + + extern { + #[linkage = "extern_weak"] + static __dso_handle: *mut u8; + #[linkage = "extern_weak"] + static __cxa_thread_atexit_impl: *const libc::c_void; + } + if !__cxa_thread_atexit_impl.is_null() { + type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8), + arg: *mut u8, + dso_handle: *mut u8) -> libc::c_int; + mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl) + (dtor, t, &__dso_handle as *const _ as *mut _); + return + } + register_dtor_fallback(t, dtor); +} + +// OSX's analog of the above linux function is this _tlv_atexit function. +// The disassembly of thread_local globals in C++ (at least produced by +// clang) will have this show up in the output. +#[cfg(target_os = "macos")] +unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { + extern { + fn _tlv_atexit(dtor: unsafe extern fn(*mut u8), + arg: *mut u8); + } + _tlv_atexit(dtor, t); +} + +// Just use the thread_local fallback implementation, at least until there's +// a more direct implementation. +#[cfg(target_os = "fuchsia")] +unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { + register_dtor_fallback(t, dtor); +} + +pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { + let ptr = ptr as *mut Key<T>; + // Right before we run the user destructor be sure to flag the + // destructor as running for this thread so calls to `get` will return + // `None`. + (*ptr).dtor_running.set(true); + + // The OSX implementation of TLS apparently had an odd aspect to it + // where the pointer we have may be overwritten while this destructor + // is running. Specifically if a TLS destructor re-accesses TLS it may + // trigger a re-initialization of all TLS variables, paving over at + // least some destroyed ones with initial values. + // + // This means that if we drop a TLS value in place on OSX that we could + // revert the value to its original state halfway through the + // destructor, which would be bad! + // + // Hence, we use `ptr::read` on OSX (to move to a "safe" location) + // instead of drop_in_place. + if cfg!(target_os = "macos") { + ptr::read((*ptr).inner.get()); + } else { + ptr::drop_in_place((*ptr).inner.get()); + } +} diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index 66bc9d4a491..fd7dc17cccd 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -38,6 +38,7 @@ pub mod backtrace; pub mod condvar; pub mod env; pub mod ext; +pub mod fast_thread_local; pub mod fd; pub mod fs; pub mod memchr; @@ -162,3 +163,14 @@ pub fn cvt_r<T, F>(mut f: F) -> io::Result<T> } } } + +// On Unix-like platforms, libc::abort will unregister signal handlers +// including the SIGABRT handler, preventing the abort from being blocked, and +// fclose streams, with the side effect of flushing them so libc bufferred +// output will be printed. Additionally the shell will generally print a more +// understandable error message like "Abort trap" rather than "Illegal +// instruction" that intrinsics::abort would cause, as intrinsics::abort is +// implemented as an illegal instruction. +pub unsafe fn abort_internal() -> ! { + ::libc::abort() +} diff --git a/src/libstd/sys/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs index 947ba2cc752..273341b1918 100644 --- a/src/libstd/sys/unix/stdio.rs +++ b/src/libstd/sys/unix/stdio.rs @@ -67,3 +67,4 @@ impl io::Write for Stderr { } pub const EBADF_ERR: i32 = ::libc::EBADF as i32; +pub const STDIN_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE; diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 9cd6e6ca176..defc41c5f46 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -179,7 +179,7 @@ pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] { } } -trait IsZero { +pub trait IsZero { fn is_zero(&self) -> bool; } @@ -193,7 +193,7 @@ macro_rules! impl_is_zero { impl_is_zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } -fn cvt<I: IsZero>(i: I) -> io::Result<I> { +pub fn cvt<I: IsZero>(i: I) -> io::Result<I> { if i.is_zero() { Err(io::Error::last_os_error()) } else { @@ -201,7 +201,7 @@ fn cvt<I: IsZero>(i: I) -> io::Result<I> { } } -fn dur2timeout(dur: Duration) -> c::DWORD { +pub fn dur2timeout(dur: Duration) -> c::DWORD { // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the // timeouts in windows APIs are typically u32 milliseconds. To translate, we // have two pieces to take care of: @@ -221,3 +221,17 @@ fn dur2timeout(dur: Duration) -> c::DWORD { } }).unwrap_or(c::INFINITE) } + +// On Windows, use the processor-specific __fastfail mechanism. In Windows 8 +// and later, this will terminate the process immediately without running any +// in-process exception handlers. In earlier versions of Windows, this +// sequence of instructions will be treated as an access violation, +// terminating the process but without necessarily bypassing all exception +// handlers. +// +// https://msdn.microsoft.com/en-us/library/dn774154.aspx +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +pub unsafe fn abort_internal() -> ! { + asm!("int $$0x29" :: "{ecx}"(7) ::: volatile); // 7 is FAST_FAIL_FATAL_APP_EXIT + ::intrinsics::unreachable(); +} diff --git a/src/libstd/sys/windows/stdio.rs b/src/libstd/sys/windows/stdio.rs index 5f097d2631d..72788776ded 100644 --- a/src/libstd/sys/windows/stdio.rs +++ b/src/libstd/sys/windows/stdio.rs @@ -207,3 +207,8 @@ fn invalid_encoding() -> io::Error { } pub const EBADF_ERR: i32 = ::sys::c::ERROR_INVALID_HANDLE as i32; +// The default buffer capacity is 64k, but apparently windows +// doesn't like 64k reads on stdin. See #13304 for details, but the +// idea is that on windows we use a slightly smaller buffer that's +// been seen to be acceptable. +pub const STDIN_BUF_SIZE: usize = 8 * 1024; diff --git a/src/libstd/sys/common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs index ce6fd4cb075..ce6fd4cb075 100644 --- a/src/libstd/sys/common/at_exit_imp.rs +++ b/src/libstd/sys_common/at_exit_imp.rs diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys_common/backtrace.rs index a8540fed928..a8540fed928 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys_common/backtrace.rs diff --git a/src/libstd/sys/common/condvar.rs b/src/libstd/sys_common/condvar.rs index b6f29dd5fc3..b6f29dd5fc3 100644 --- a/src/libstd/sys/common/condvar.rs +++ b/src/libstd/sys_common/condvar.rs diff --git a/src/libstd/sys/common/gnu/libbacktrace.rs b/src/libstd/sys_common/gnu/libbacktrace.rs index b5802afc109..b5802afc109 100644 --- a/src/libstd/sys/common/gnu/libbacktrace.rs +++ b/src/libstd/sys_common/gnu/libbacktrace.rs diff --git a/src/libstd/sys/common/gnu/mod.rs b/src/libstd/sys_common/gnu/mod.rs index 3a8cf2d8425..3a8cf2d8425 100644 --- a/src/libstd/sys/common/gnu/mod.rs +++ b/src/libstd/sys_common/gnu/mod.rs diff --git a/src/libstd/sys/common/io.rs b/src/libstd/sys_common/io.rs index 0483725dd83..23daeeb5187 100644 --- a/src/libstd/sys/common/io.rs +++ b/src/libstd/sys_common/io.rs @@ -12,6 +12,8 @@ use io::ErrorKind; use io::Read; use slice::from_raw_parts_mut; +pub const DEFAULT_BUF_SIZE: usize = 8 * 1024; + // Provides read_to_end functionality over an uninitialized buffer. // This function is unsafe because it calls the underlying // read function with a slice into uninitialized memory. The default diff --git a/src/libstd/sys/common/memchr.rs b/src/libstd/sys_common/memchr.rs index 3824a5fb528..3824a5fb528 100644 --- a/src/libstd/sys/common/memchr.rs +++ b/src/libstd/sys_common/memchr.rs diff --git a/src/libstd/sys/common/mod.rs b/src/libstd/sys_common/mod.rs index 274f3c10d9c..bbd2f679bca 100644 --- a/src/libstd/sys/common/mod.rs +++ b/src/libstd/sys_common/mod.rs @@ -8,23 +8,25 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +//! Platform-independent platform abstraction +//! +//! This is the platform-independent portion of the standard libraries +//! platform abstraction layer, whereas `std::sys` is the +//! platform-specific portion. +//! +//! The relationship between `std::sys_common`, `std::sys` and the +//! rest of `std` is complex, with dependencies going in all +//! directions: `std` depending on `sys_common`, `sys_common` +//! depending on `sys`, and `sys` depending on `sys_common` and `std`. +//! Ideally `sys_common` would be split into two and the dependencies +//! between them all would form a dag, facilitating the extraction of +//! `std::sys` from the standard library. + #![allow(missing_docs)] use sync::Once; use sys; -macro_rules! rtabort { - ($($t:tt)*) => (::sys_common::util::abort(format_args!($($t)*))) -} - -macro_rules! rtassert { - ($e:expr) => ({ - if !$e { - rtabort!(concat!("assertion failed: ", stringify!($e))) - } - }) -} - pub mod at_exit_imp; #[cfg(any(not(cargobuild), feature = "backtrace"))] pub mod backtrace; @@ -92,6 +94,10 @@ pub fn at_exit<F: FnOnce() + Send + 'static>(f: F) -> Result<(), ()> { if at_exit_imp::push(Box::new(f)) {Ok(())} else {Err(())} } +macro_rules! rtabort { + ($($t:tt)*) => (::sys_common::util::abort(format_args!($($t)*))) +} + /// One-time runtime cleanup. pub fn cleanup() { static CLEANUP: Once = Once::new(); diff --git a/src/libstd/sys/common/mutex.rs b/src/libstd/sys_common/mutex.rs index d1a738770d3..d1a738770d3 100644 --- a/src/libstd/sys/common/mutex.rs +++ b/src/libstd/sys_common/mutex.rs diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys_common/net.rs index 10ad61f4c80..10ad61f4c80 100644 --- a/src/libstd/sys/common/net.rs +++ b/src/libstd/sys_common/net.rs diff --git a/src/libstd/sys/common/poison.rs b/src/libstd/sys_common/poison.rs index bdc727f1dfc..bdc727f1dfc 100644 --- a/src/libstd/sys/common/poison.rs +++ b/src/libstd/sys_common/poison.rs diff --git a/src/libstd/sys/common/remutex.rs b/src/libstd/sys_common/remutex.rs index 4d0407ccf6c..4d0407ccf6c 100644 --- a/src/libstd/sys/common/remutex.rs +++ b/src/libstd/sys_common/remutex.rs diff --git a/src/libstd/sys/common/rwlock.rs b/src/libstd/sys_common/rwlock.rs index 71a4f01ec4c..71a4f01ec4c 100644 --- a/src/libstd/sys/common/rwlock.rs +++ b/src/libstd/sys_common/rwlock.rs diff --git a/src/libstd/sys/common/thread.rs b/src/libstd/sys_common/thread.rs index 3ee160da5fa..3ee160da5fa 100644 --- a/src/libstd/sys/common/thread.rs +++ b/src/libstd/sys_common/thread.rs diff --git a/src/libstd/sys/common/thread_info.rs b/src/libstd/sys_common/thread_info.rs index 95d8b6cc951..95d8b6cc951 100644 --- a/src/libstd/sys/common/thread_info.rs +++ b/src/libstd/sys_common/thread_info.rs diff --git a/src/libstd/sys/common/thread_local.rs b/src/libstd/sys_common/thread_local.rs index 25a9d5720d9..25a9d5720d9 100644 --- a/src/libstd/sys/common/thread_local.rs +++ b/src/libstd/sys_common/thread_local.rs diff --git a/src/libstd/sys/common/util.rs b/src/libstd/sys_common/util.rs index dda0abb4c0c..daa0c15920b 100644 --- a/src/libstd/sys/common/util.rs +++ b/src/libstd/sys_common/util.rs @@ -33,38 +33,6 @@ pub fn dumb_print(args: fmt::Arguments) { let _ = Stderr::new().map(|mut stderr| stderr.write_fmt(args)); } -// On Redox, use an illegal instruction -#[cfg(redox)] -unsafe fn abort_internal() -> ! { - ::intrinsics::abort() -} - -// On Unix-like platforms, libc::abort will unregister signal handlers -// including the SIGABRT handler, preventing the abort from being blocked, and -// fclose streams, with the side effect of flushing them so libc bufferred -// output will be printed. Additionally the shell will generally print a more -// understandable error message like "Abort trap" rather than "Illegal -// instruction" that intrinsics::abort would cause, as intrinsics::abort is -// implemented as an illegal instruction. -#[cfg(unix)] -unsafe fn abort_internal() -> ! { - ::libc::abort() -} - -// On Windows, use the processor-specific __fastfail mechanism. In Windows 8 -// and later, this will terminate the process immediately without running any -// in-process exception handlers. In earlier versions of Windows, this -// sequence of instructions will be treated as an access violation, -// terminating the process but without necessarily bypassing all exception -// handlers. -// -// https://msdn.microsoft.com/en-us/library/dn774154.aspx -#[cfg(all(windows, any(target_arch = "x86", target_arch = "x86_64")))] -unsafe fn abort_internal() -> ! { - asm!("int $$0x29" :: "{ecx}"(7) ::: volatile); // 7 is FAST_FAIL_FATAL_APP_EXIT - ::intrinsics::unreachable(); -} - // Other platforms should use the appropriate platform-specific mechanism for // aborting the process. If no platform-specific mechanism is available, // ::intrinsics::abort() may be used instead. The above implementations cover @@ -72,7 +40,7 @@ unsafe fn abort_internal() -> ! { pub fn abort(args: fmt::Arguments) -> ! { dumb_print(format_args!("fatal runtime error: {}\n", args)); - unsafe { abort_internal(); } + unsafe { ::sys::abort_internal(); } } #[allow(dead_code)] // stack overflow detection not enabled on all platforms diff --git a/src/libstd/sys/common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index 0a94ff1e958..0a94ff1e958 100644 --- a/src/libstd/sys/common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index a1ae2c1cb42..f74dd592495 100644 --- a/src/libstd/thread/local.rs +++ b/src/libstd/thread/local.rs @@ -166,8 +166,8 @@ macro_rules! __thread_local_inner { { #[thread_local] #[cfg(target_thread_local)] - static __KEY: $crate::thread::__ElfLocalKeyInner<$t> = - $crate::thread::__ElfLocalKeyInner::new(); + static __KEY: $crate::thread::__FastLocalKeyInner<$t> = + $crate::thread::__FastLocalKeyInner::new(); #[cfg(not(target_thread_local))] static __KEY: $crate::thread::__OsLocalKeyInner<$t> = @@ -310,165 +310,6 @@ impl<T: 'static> LocalKey<T> { } } -#[cfg(target_thread_local)] -#[doc(hidden)] -pub mod elf { - use cell::{Cell, UnsafeCell}; - use intrinsics; - use ptr; - - pub struct Key<T> { - inner: UnsafeCell<Option<T>>, - - // Metadata to keep track of the state of the destructor. Remember that - // these variables are thread-local, not global. - dtor_registered: Cell<bool>, - dtor_running: Cell<bool>, - } - - unsafe impl<T> ::marker::Sync for Key<T> { } - - impl<T> Key<T> { - pub const fn new() -> Key<T> { - Key { - inner: UnsafeCell::new(None), - dtor_registered: Cell::new(false), - dtor_running: Cell::new(false) - } - } - - pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> { - unsafe { - if intrinsics::needs_drop::<T>() && self.dtor_running.get() { - return None - } - self.register_dtor(); - } - Some(&self.inner) - } - - unsafe fn register_dtor(&self) { - if !intrinsics::needs_drop::<T>() || self.dtor_registered.get() { - return - } - - register_dtor(self as *const _ as *mut u8, - destroy_value::<T>); - self.dtor_registered.set(true); - } - } - - #[cfg(any(target_os = "linux", target_os = "fuchsia", target_os = "redox"))] - unsafe fn register_dtor_fallback(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { - // The fallback implementation uses a vanilla OS-based TLS key to track - // the list of destructors that need to be run for this thread. The key - // then has its own destructor which runs all the other destructors. - // - // The destructor for DTORS is a little special in that it has a `while` - // loop to continuously drain the list of registered destructors. It - // *should* be the case that this loop always terminates because we - // provide the guarantee that a TLS key cannot be set after it is - // flagged for destruction. - use sys_common::thread_local as os; - - static DTORS: os::StaticKey = os::StaticKey::new(Some(run_dtors)); - type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; - if DTORS.get().is_null() { - let v: Box<List> = box Vec::new(); - DTORS.set(Box::into_raw(v) as *mut u8); - } - let list: &mut List = &mut *(DTORS.get() as *mut List); - list.push((t, dtor)); - - unsafe extern fn run_dtors(mut ptr: *mut u8) { - while !ptr.is_null() { - let list: Box<List> = Box::from_raw(ptr as *mut List); - for &(ptr, dtor) in list.iter() { - dtor(ptr); - } - ptr = DTORS.get(); - DTORS.set(ptr::null_mut()); - } - } - } - - // Since what appears to be glibc 2.18 this symbol has been shipped which - // GCC and clang both use to invoke destructors in thread_local globals, so - // let's do the same! - // - // Note, however, that we run on lots older linuxes, as well as cross - // compiling from a newer linux to an older linux, so we also have a - // fallback implementation to use as well. - // - // Due to rust-lang/rust#18804, make sure this is not generic! - #[cfg(target_os = "linux")] - unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { - use mem; - use libc; - - extern { - #[linkage = "extern_weak"] - static __dso_handle: *mut u8; - #[linkage = "extern_weak"] - static __cxa_thread_atexit_impl: *const libc::c_void; - } - if !__cxa_thread_atexit_impl.is_null() { - type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8), - arg: *mut u8, - dso_handle: *mut u8) -> libc::c_int; - mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl) - (dtor, t, &__dso_handle as *const _ as *mut _); - return - } - register_dtor_fallback(t, dtor); - } - - // OSX's analog of the above linux function is this _tlv_atexit function. - // The disassembly of thread_local globals in C++ (at least produced by - // clang) will have this show up in the output. - #[cfg(target_os = "macos")] - unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { - extern { - fn _tlv_atexit(dtor: unsafe extern fn(*mut u8), - arg: *mut u8); - } - _tlv_atexit(dtor, t); - } - - // Just use the thread_local fallback implementation, at least until there's - // a more direct implementation. - #[cfg(any(target_os = "fuchsia", target_os = "redox"))] - unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { - register_dtor_fallback(t, dtor); - } - - pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { - let ptr = ptr as *mut Key<T>; - // Right before we run the user destructor be sure to flag the - // destructor as running for this thread so calls to `get` will return - // `None`. - (*ptr).dtor_running.set(true); - - // The OSX implementation of TLS apparently had an odd aspect to it - // where the pointer we have may be overwritten while this destructor - // is running. Specifically if a TLS destructor re-accesses TLS it may - // trigger a re-initialization of all TLS variables, paving over at - // least some destroyed ones with initial values. - // - // This means that if we drop a TLS value in place on OSX that we could - // revert the value to its original state halfway through the - // destructor, which would be bad! - // - // Hence, we use `ptr::read` on OSX (to move to a "safe" location) - // instead of drop_in_place. - if cfg!(target_os = "macos") { - ptr::read((*ptr).inner.get()); - } else { - ptr::drop_in_place((*ptr).inner.get()); - } - } -} - #[doc(hidden)] pub mod os { use cell::{Cell, UnsafeCell}; diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 150482e4af4..255cd2a9bc0 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -181,9 +181,18 @@ use time::Duration; #[stable(feature = "rust1", since = "1.0.0")] pub use self::local::{LocalKey, LocalKeyState}; +// The types used by the thread_local! macro to access TLS keys. Note that there +// are two types, the "OS" type and the "fast" type. The OS thread local key +// type is accessed via platform-specific API calls and is slow, while the fast +// key type is accessed via code generated via LLVM, where TLS keys are set up +// by the elf linker. Note that the OS TLS type is always available: on macOS +// the standard library is compiled with support for older platform versions +// where fast TLS was not available; end-user code is compiled with fast TLS +// where available, but both are needed. + #[unstable(feature = "libstd_thread_internals", issue = "0")] #[cfg(target_thread_local)] -#[doc(hidden)] pub use self::local::elf::Key as __ElfLocalKeyInner; +#[doc(hidden)] pub use sys::fast_thread_local::Key as __FastLocalKeyInner; #[unstable(feature = "libstd_thread_internals", issue = "0")] #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 8864694c932..f077ead1f8e 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -161,12 +161,12 @@ impl Path { Path { span: s, global: false, - segments: vec!( + segments: vec![ PathSegment { identifier: identifier, parameters: PathParameters::none() } - ), + ], } } } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 0ef47bd6daa..37bd83be7b4 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -312,7 +312,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new()) } fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path { - self.path(span, vec!(id)) + self.path(span, vec![id]) } fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path { self.path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new()) @@ -443,7 +443,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { true, self.std_path(&["option", "Option"]), Vec::new(), - vec!( ty ), + vec![ ty ], Vec::new())) } @@ -477,7 +477,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn ty_vars_global(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> { ty_params .iter() - .map(|p| self.ty_path(self.path_global(DUMMY_SP, vec!(p.ident)))) + .map(|p| self.ty_path(self.path_global(DUMMY_SP, vec![p.ident]))) .collect() } @@ -770,7 +770,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { let some = self.std_path(&["option", "Option", "Some"]); - self.expr_call_global(sp, some, vec!(expr)) + self.expr_call_global(sp, some, vec![expr]) } fn expr_none(&self, sp: Span) -> P<ast::Expr> { @@ -794,14 +794,14 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let expr_file = self.expr_str(span, token::intern_and_get_ident(&loc.file.name)); let expr_line = self.expr_u32(span, loc.line as u32); - let expr_file_line_tuple = self.expr_tuple(span, vec!(expr_file, expr_line)); + let expr_file_line_tuple = self.expr_tuple(span, vec![expr_file, expr_line]); let expr_file_line_ptr = self.expr_addr_of(span, expr_file_line_tuple); self.expr_call_global( span, self.std_path(&["rt", "begin_panic"]), - vec!( + vec![ self.expr_str(span, msg), - expr_file_line_ptr)) + expr_file_line_ptr]) } fn expr_unreachable(&self, span: Span) -> P<ast::Expr> { @@ -812,12 +812,12 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { let ok = self.std_path(&["result", "Result", "Ok"]); - self.expr_call_global(sp, ok, vec!(expr)) + self.expr_call_global(sp, ok, vec![expr]) } fn expr_err(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { let err = self.std_path(&["result", "Result", "Err"]); - self.expr_call_global(sp, err, vec!(expr)) + self.expr_call_global(sp, err, vec![expr]) } fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> { @@ -836,17 +836,17 @@ impl<'a> AstBuilder for ExtCtxt<'a> { // Err(__try_var) (pattern and expression resp.) let err_pat = self.pat_tuple_struct(sp, err_path.clone(), vec![binding_pat]); let err_inner_expr = self.expr_call(sp, self.expr_path(err_path), - vec!(binding_expr.clone())); + vec![binding_expr.clone()]); // return Err(__try_var) let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr))); // Ok(__try_var) => __try_var - let ok_arm = self.arm(sp, vec!(ok_pat), binding_expr); + let ok_arm = self.arm(sp, vec![ok_pat], binding_expr); // Err(__try_var) => return Err(__try_var) - let err_arm = self.arm(sp, vec!(err_pat), err_expr); + let err_arm = self.arm(sp, vec![err_pat], err_expr); // match head { Ok() => ..., Err() => ... } - self.expr_match(sp, head, vec!(ok_arm, err_arm)) + self.expr_match(sp, head, vec![ok_arm, err_arm]) } @@ -912,7 +912,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn arm(&self, _span: Span, pats: Vec<P<ast::Pat>>, expr: P<ast::Expr>) -> ast::Arm { ast::Arm { - attrs: vec!(), + attrs: vec![], pats: pats, guard: None, body: expr @@ -920,7 +920,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn arm_unreachable(&self, span: Span) -> ast::Arm { - self.arm(span, vec!(self.pat_wild(span)), self.expr_unreachable(span)) + self.arm(span, vec![self.pat_wild(span)], self.expr_unreachable(span)) } fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm>) -> P<Expr> { @@ -970,7 +970,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn lambda1(&self, span: Span, blk: P<ast::Block>, ident: ast::Ident) -> P<ast::Expr> { - self.lambda(span, vec!(ident), blk) + self.lambda(span, vec![ident], blk) } fn lambda_expr(&self, span: Span, ids: Vec<ast::Ident>, diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index f3497c130bf..f21360755bc 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -46,7 +46,7 @@ pub mod rt { impl ToTokens for TokenTree { fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { - vec!(self.clone()) + vec![self.clone()] } } @@ -416,7 +416,7 @@ pub fn expand_quote_expr<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'cx> { - let expanded = expand_parse_call(cx, sp, "parse_expr_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_expr_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -424,7 +424,7 @@ pub fn expand_quote_item<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'cx> { - let expanded = expand_parse_call(cx, sp, "parse_item_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_item_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -432,7 +432,7 @@ pub fn expand_quote_pat<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'cx> { - let expanded = expand_parse_call(cx, sp, "parse_pat_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_pat_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -440,7 +440,7 @@ pub fn expand_quote_arm(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'static> { - let expanded = expand_parse_call(cx, sp, "parse_arm_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_arm_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -448,7 +448,7 @@ pub fn expand_quote_ty(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'static> { - let expanded = expand_parse_call(cx, sp, "parse_ty_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_ty_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -456,7 +456,7 @@ pub fn expand_quote_stmt(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'static> { - let expanded = expand_parse_call(cx, sp, "parse_stmt_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_stmt_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -465,7 +465,7 @@ pub fn expand_quote_attr(cx: &mut ExtCtxt, tts: &[TokenTree]) -> Box<base::MacResult+'static> { let expanded = expand_parse_call(cx, sp, "parse_attribute_panic", - vec!(cx.expr_bool(sp, true)), tts); + vec![cx.expr_bool(sp, true)], tts); base::MacEager::expr(expanded) } @@ -474,7 +474,7 @@ pub fn expand_quote_arg(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'static> { - let expanded = expand_parse_call(cx, sp, "parse_arg_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_arg_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -482,7 +482,7 @@ pub fn expand_quote_block(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'static> { - let expanded = expand_parse_call(cx, sp, "parse_block_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_block_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -490,7 +490,7 @@ pub fn expand_quote_meta_item(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<base::MacResult+'static> { - let expanded = expand_parse_call(cx, sp, "parse_meta_item_panic", vec!(), tts); + let expanded = expand_parse_call(cx, sp, "parse_meta_item_panic", vec![], tts); base::MacEager::expr(expanded) } @@ -499,7 +499,7 @@ pub fn expand_quote_path(cx: &mut ExtCtxt, tts: &[TokenTree]) -> Box<base::MacResult+'static> { let mode = mk_parser_path(cx, sp, &["PathStyle", "Type"]); - let expanded = expand_parse_call(cx, sp, "parse_path_panic", vec!(mode), tts); + let expanded = expand_parse_call(cx, sp, "parse_path_panic", vec![mode], tts); base::MacEager::expr(expanded) } @@ -531,7 +531,7 @@ fn mk_ident(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> { cx.expr_method_call(sp, cx.expr_ident(sp, id_ext("ext_cx")), id_ext("ident_of"), - vec!(e_str)) + vec![e_str]) } // Lift a name to the expr that evaluates to that name @@ -540,16 +540,16 @@ fn mk_name(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> { cx.expr_method_call(sp, cx.expr_ident(sp, id_ext("ext_cx")), id_ext("name_of"), - vec!(e_str)) + vec![e_str]) } fn mk_tt_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> { - let idents = vec!(id_ext("syntax"), id_ext("tokenstream"), id_ext("TokenTree"), id_ext(name)); + let idents = vec![id_ext("syntax"), id_ext("tokenstream"), id_ext("TokenTree"), id_ext(name)]; cx.expr_path(cx.path_global(sp, idents)) } fn mk_token_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> { - let idents = vec!(id_ext("syntax"), id_ext("parse"), id_ext("token"), id_ext(name)); + let idents = vec![id_ext("syntax"), id_ext("parse"), id_ext("token"), id_ext(name)]; cx.expr_path(cx.path_global(sp, idents)) } @@ -599,11 +599,11 @@ fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> { } match *tok { token::BinOp(binop) => { - return cx.expr_call(sp, mk_token_path(cx, sp, "BinOp"), vec!(mk_binop(cx, sp, binop))); + return cx.expr_call(sp, mk_token_path(cx, sp, "BinOp"), vec![mk_binop(cx, sp, binop)]); } token::BinOpEq(binop) => { return cx.expr_call(sp, mk_token_path(cx, sp, "BinOpEq"), - vec!(mk_binop(cx, sp, binop))); + vec![mk_binop(cx, sp, binop)]); } token::OpenDelim(delim) => { @@ -653,13 +653,13 @@ fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> { token::Lifetime(ident) => { return cx.expr_call(sp, mk_token_path(cx, sp, "Lifetime"), - vec!(mk_ident(cx, sp, ident))); + vec![mk_ident(cx, sp, ident)]); } token::DocComment(ident) => { return cx.expr_call(sp, mk_token_path(cx, sp, "DocComment"), - vec!(mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident)))); + vec![mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident))]); } token::MatchNt(name, kind) => { @@ -714,7 +714,7 @@ fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, matcher: bool) -> Vec<ast::Stm cx.expr_method_call(sp, cx.expr_ident(sp, ident), id_ext("to_tokens"), - vec!(cx.expr_ident(sp, id_ext("ext_cx")))); + vec![cx.expr_ident(sp, id_ext("ext_cx"))]); let e_to_toks = cx.expr_method_call(sp, e_to_toks, id_ext("into_iter"), vec![]); @@ -722,9 +722,9 @@ fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, matcher: bool) -> Vec<ast::Stm cx.expr_method_call(sp, cx.expr_ident(sp, id_ext("tt")), id_ext("extend"), - vec!(e_to_toks)); + vec![e_to_toks]); - vec!(cx.stmt_expr(e_push)) + vec![cx.stmt_expr(e_push)] } ref tt @ TokenTree::Token(_, MatchNt(..)) if !matcher => { let mut seq = vec![]; @@ -737,13 +737,13 @@ fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, matcher: bool) -> Vec<ast::Stm let e_sp = cx.expr_ident(sp, id_ext("_sp")); let e_tok = cx.expr_call(sp, mk_tt_path(cx, sp, "Token"), - vec!(e_sp, expr_mk_token(cx, sp, tok))); + vec![e_sp, expr_mk_token(cx, sp, tok)]); let e_push = cx.expr_method_call(sp, cx.expr_ident(sp, id_ext("tt")), id_ext("push"), - vec!(e_tok)); - vec!(cx.stmt_expr(e_push)) + vec![e_tok]); + vec![cx.stmt_expr(e_push)] }, TokenTree::Delimited(_, ref delimed) => { statements_mk_tt(cx, &delimed.open_tt(), matcher).into_iter() @@ -796,13 +796,13 @@ fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, matcher: bool) -> Vec<ast::Stm vec![e_seq_struct]); let e_tok = cx.expr_call(sp, mk_tt_path(cx, sp, "Sequence"), - vec!(e_sp, e_rc_new)); + vec![e_sp, e_rc_new]); let e_push = cx.expr_method_call(sp, cx.expr_ident(sp, id_ext("tt")), id_ext("push"), - vec!(e_tok)); - vec!(cx.stmt_expr(e_push)) + vec![e_tok]); + vec![cx.stmt_expr(e_push)] } } } @@ -867,7 +867,7 @@ fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<ast::Stmt> { let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp)); - vec!(stmt_let_sp, stmt_let_tt) + vec![stmt_let_sp, stmt_let_tt] } fn statements_mk_tts(cx: &ExtCtxt, tts: &[TokenTree], matcher: bool) -> Vec<ast::Stmt> { @@ -923,7 +923,7 @@ fn expand_parse_call(cx: &ExtCtxt, let new_parser_call = cx.expr_call(sp, cx.expr_ident(sp, id_ext("new_parser_from_tts")), - vec!(parse_sess_call(), tts_expr)); + vec![parse_sess_call(), tts_expr]); let path = vec![id_ext("syntax"), id_ext("ext"), id_ext("quote"), id_ext(parse_method)]; let mut args = vec![cx.expr_mut_addr_of(sp, new_parser_call)]; diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 7b67c23e102..12408c7d3c9 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -624,12 +624,12 @@ mod tests { node: ast::ExprKind::Path(None, ast::Path { span: sp(0, 1), global: false, - segments: vec!( + segments: vec![ ast::PathSegment { identifier: str_to_ident("a"), parameters: ast::PathParameters::none(), } - ), + ], }), span: sp(0, 1), attrs: ThinVec::new(), @@ -643,7 +643,7 @@ mod tests { node: ast::ExprKind::Path(None, ast::Path { span: sp(0, 6), global: true, - segments: vec!( + segments: vec![ ast::PathSegment { identifier: str_to_ident("a"), parameters: ast::PathParameters::none(), @@ -652,7 +652,7 @@ mod tests { identifier: str_to_ident("b"), parameters: ast::PathParameters::none(), } - ) + ] }), span: sp(0, 6), attrs: ThinVec::new(), @@ -763,12 +763,12 @@ mod tests { node:ast::ExprKind::Path(None, ast::Path{ span: sp(7, 8), global: false, - segments: vec!( + segments: vec![ ast::PathSegment { identifier: str_to_ident("d"), parameters: ast::PathParameters::none(), } - ), + ], }), span:sp(7,8), attrs: ThinVec::new(), @@ -786,12 +786,12 @@ mod tests { node: ast::ExprKind::Path(None, ast::Path { span:sp(0,1), global:false, - segments: vec!( + segments: vec![ ast::PathSegment { identifier: str_to_ident("b"), parameters: ast::PathParameters::none(), } - ), + ], }), span: sp(0,1), attrs: ThinVec::new()})), @@ -828,18 +828,18 @@ mod tests { attrs:Vec::new(), id: ast::DUMMY_NODE_ID, node: ast::ItemKind::Fn(P(ast::FnDecl { - inputs: vec!(ast::Arg{ + inputs: vec![ast::Arg{ ty: P(ast::Ty{id: ast::DUMMY_NODE_ID, node: ast::TyKind::Path(None, ast::Path{ span:sp(10,13), global:false, - segments: vec!( + segments: vec![ ast::PathSegment { identifier: str_to_ident("i32"), parameters: ast::PathParameters::none(), } - ), + ], }), span:sp(10,13) }), @@ -855,7 +855,7 @@ mod tests { span: sp(6,7) }), id: ast::DUMMY_NODE_ID - }), + }], output: ast::FunctionRetTy::Default(sp(15, 15)), variadic: false }), @@ -875,14 +875,14 @@ mod tests { span: syntax_pos::DUMMY_SP, }, P(ast::Block { - stmts: vec!(ast::Stmt { + stmts: vec![ast::Stmt { node: ast::StmtKind::Semi(P(ast::Expr{ id: ast::DUMMY_NODE_ID, node: ast::ExprKind::Path(None, ast::Path{ span:sp(17,18), global:false, - segments: vec!( + segments: vec![ ast::PathSegment { identifier: str_to_ident( @@ -890,12 +890,12 @@ mod tests { parameters: ast::PathParameters::none(), } - ), + ], }), span: sp(17,18), attrs: ThinVec::new()})), id: ast::DUMMY_NODE_ID, - span: sp(17,19)}), + span: sp(17,19)}], id: ast::DUMMY_NODE_ID, rules: ast::BlockCheckMode::Default, // no idea span: sp(15,21), diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index a75937759a2..b80aa667be6 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -848,7 +848,7 @@ impl<'a> Parser<'a> { Fe: FnMut(DiagnosticBuilder) { let mut first: bool = true; - let mut v = vec!(); + let mut v = vec![]; while !kets.contains(&&self.token) { match sep.sep { Some(ref t) => { @@ -2224,13 +2224,13 @@ impl<'a> Parser<'a> { SeqSep::trailing_allowed(token::Comma), |p| Ok(p.parse_expr()?) )?; - let mut exprs = vec!(first_expr); + let mut exprs = vec![first_expr]; exprs.extend(remaining_exprs); ex = ExprKind::Vec(exprs); } else { // Vector with one element. self.expect(&token::CloseDelim(token::Bracket))?; - ex = ExprKind::Vec(vec!(first_expr)); + ex = ExprKind::Vec(vec![first_expr]); } } hi = self.prev_span.hi; @@ -4224,7 +4224,7 @@ impl<'a> Parser<'a> { mode: BoundParsingMode) -> PResult<'a, TyParamBounds> { - let mut result = vec!(); + let mut result = vec![]; loop { let question_span = self.span; let ate_question = self.eat(&token::Question); diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 149112133b2..b0bd6446743 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -2277,7 +2277,7 @@ impl<'a> State<'a> { Ok(()) })); - let mut options = vec!(); + let mut options = vec![]; if a.volatile { options.push("volatile"); } diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index fdc1f45623d..618878c1f79 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -430,7 +430,7 @@ fn mk_std(cx: &TestCtxt) -> P<ast::Item> { let (vi, vis, ident) = if cx.is_test_crate { (ast::ItemKind::Use( P(nospan(ast::ViewPathSimple(id_test, - path_node(vec!(id_test)))))), + path_node(vec![id_test]))))), ast::Visibility::Public, keywords::Invalid.ident()) } else { (ast::ItemKind::ExternCrate(None), ast::Visibility::Inherited, id_test) diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index 57258c76335..9be7dbd6817 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -105,7 +105,7 @@ impl<T> SmallVector<T> { One(..) => { let one = mem::replace(&mut self.repr, Zero); match one { - One(v1) => mem::replace(&mut self.repr, Many(vec!(v1, v))), + One(v1) => mem::replace(&mut self.repr, Many(vec![v1, v])), _ => unreachable!() }; } @@ -314,12 +314,12 @@ mod tests { #[test] #[should_panic] fn test_expect_one_many() { - SmallVector::many(vec!(1, 2)).expect_one(""); + SmallVector::many(vec![1, 2]).expect_one(""); } #[test] fn test_expect_one_one() { assert_eq!(1, SmallVector::one(1).expect_one("")); - assert_eq!(1, SmallVector::many(vec!(1)).expect_one("")); + assert_eq!(1, SmallVector::many(vec![1]).expect_one("")); } } diff --git a/src/libsyntax_ext/deriving/cmp/partial_eq.rs b/src/libsyntax_ext/deriving/cmp/partial_eq.rs index 64b8829dad7..c46d4b34173 100644 --- a/src/libsyntax_ext/deriving/cmp/partial_eq.rs +++ b/src/libsyntax_ext/deriving/cmp/partial_eq.rs @@ -65,12 +65,12 @@ pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt, macro_rules! md { ($name:expr, $f:ident) => { { let inline = cx.meta_word(span, InternedString::new("inline")); - let attrs = vec!(cx.attribute(span, inline)); + let attrs = vec![cx.attribute(span, inline)]; MethodDef { name: $name, generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), - args: vec!(borrowed_self()), + args: vec![borrowed_self()], ret_ty: Literal(path_local!(bool)), attributes: attrs, is_unsafe: false, diff --git a/src/libsyntax_ext/deriving/cmp/partial_ord.rs b/src/libsyntax_ext/deriving/cmp/partial_ord.rs index 99d60c43c54..597ff306b3d 100644 --- a/src/libsyntax_ext/deriving/cmp/partial_ord.rs +++ b/src/libsyntax_ext/deriving/cmp/partial_ord.rs @@ -28,12 +28,12 @@ pub fn expand_deriving_partial_ord(cx: &mut ExtCtxt, macro_rules! md { ($name:expr, $op:expr, $equal:expr) => { { let inline = cx.meta_word(span, InternedString::new("inline")); - let attrs = vec!(cx.attribute(span, inline)); + let attrs = vec![cx.attribute(span, inline)]; MethodDef { name: $name, generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), - args: vec!(borrowed_self()), + args: vec![borrowed_self()], ret_ty: Literal(path_local!(bool)), attributes: attrs, is_unsafe: false, diff --git a/src/libsyntax_ext/deriving/decodable.rs b/src/libsyntax_ext/deriving/decodable.rs index 22b9eb8e754..10db56d46f6 100644 --- a/src/libsyntax_ext/deriving/decodable.rs +++ b/src/libsyntax_ext/deriving/decodable.rs @@ -79,9 +79,9 @@ fn expand_deriving_decodable_imp(cx: &mut ExtCtxt, ret_ty: Literal(Path::new_(pathvec_std!(cx, core::result::Result), None, - vec!(Box::new(Self_), Box::new(Literal(Path::new_( + vec![Box::new(Self_), Box::new(Literal(Path::new_( vec![typaram, "Error"], None, vec![], false - )))), + )))], true)), attributes: Vec::new(), is_unsafe: false, diff --git a/src/libsyntax_ext/deriving/encodable.rs b/src/libsyntax_ext/deriving/encodable.rs index a4074184b6e..640296d7f06 100644 --- a/src/libsyntax_ext/deriving/encodable.rs +++ b/src/libsyntax_ext/deriving/encodable.rs @@ -139,23 +139,23 @@ fn expand_deriving_encodable_imp(cx: &mut ExtCtxt, generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: false, - methods: vec!( + methods: vec![ MethodDef { name: "encode", generics: LifetimeBounds { lifetimes: Vec::new(), bounds: vec![(typaram, - vec![Path::new_(vec![krate, "Encoder"], None, vec!(), true)])] + vec![Path::new_(vec![krate, "Encoder"], None, vec![], true)])] }, explicit_self: borrowed_explicit_self(), - args: vec!(Ptr(Box::new(Literal(Path::new_local(typaram))), - Borrowed(None, Mutability::Mutable))), + args: vec![Ptr(Box::new(Literal(Path::new_local(typaram))), + Borrowed(None, Mutability::Mutable))], ret_ty: Literal(Path::new_( pathvec_std!(cx, core::result::Result), None, - vec!(Box::new(Tuple(Vec::new())), Box::new(Literal(Path::new_( + vec![Box::new(Tuple(Vec::new())), Box::new(Literal(Path::new_( vec![typaram, "Error"], None, vec![], false - )))), + )))], true )), attributes: Vec::new(), @@ -165,7 +165,7 @@ fn expand_deriving_encodable_imp(cx: &mut ExtCtxt, encodable_substructure(a, b, c, krate) })), } - ), + ], associated_types: Vec::new(), }; diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 687f8c902f2..e6b63be3efc 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -1546,7 +1546,7 @@ impl<'a> TraitDef<'a> { cx.span_bug(sp, "a braced struct with unnamed fields in `derive`"); } codemap::Spanned { - span: pat.span, + span: Span { expn_id: self.span.expn_id, ..pat.span }, node: ast::FieldPat { ident: ident.unwrap(), pat: pat, @@ -1577,7 +1577,8 @@ impl<'a> TraitDef<'a> { mutbl: ast::Mutability) -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>, &'a [ast::Attribute])>) { let variant_ident = variant.node.name; - let variant_path = cx.path(variant.span, vec![enum_ident, variant_ident]); + let sp = Span { expn_id: self.span.expn_id, ..variant.span }; + let variant_path = cx.path(sp, vec![enum_ident, variant_ident]); self.create_struct_pattern(cx, variant_path, &variant.node.data, prefix, mutbl) } } diff --git a/src/libsyntax_ext/deriving/mod.rs b/src/libsyntax_ext/deriving/mod.rs index 67747173353..c2bfead5686 100644 --- a/src/libsyntax_ext/deriving/mod.rs +++ b/src/libsyntax_ext/deriving/mod.rs @@ -28,7 +28,7 @@ macro_rules! pathvec { macro_rules! path { ($($x:tt)*) => ( - ::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) ) + ::ext::deriving::generic::ty::Path::new( pathvec![ $($x)* ] ) ) } @@ -40,7 +40,7 @@ macro_rules! path_local { macro_rules! pathvec_std { ($cx:expr, $first:ident :: $($rest:ident)::+) => ({ - let mut v = pathvec!($($rest)::+); + let mut v = pathvec![$($rest)::+]; if let Some(s) = $cx.crate_root { v.insert(0, s); } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 8b0fd1ca0cb..95ae6eb2efe 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -336,7 +336,7 @@ pub type OptRes = Result<TestOpts, String>; #[cfg_attr(rustfmt, rustfmt_skip)] fn optgroups() -> Vec<getopts::OptGroup> { - vec!(getopts::optflag("", "ignored", "Run ignored tests"), + vec![getopts::optflag("", "ignored", "Run ignored tests"), getopts::optflag("", "test", "Run tests and not benchmarks"), getopts::optflag("", "bench", "Run benchmarks instead of tests"), getopts::optflag("h", "help", "Display this message (longer with --help)"), @@ -352,7 +352,7 @@ fn optgroups() -> Vec<getopts::OptGroup> { getopts::optopt("", "color", "Configure coloring of output: auto = colorize if stdout is a tty and tests are run on serially (default); always = always colorize output; - never = never colorize output;", "auto|always|never")) + never = never colorize output;", "auto|always|never")] } fn usage(binary: &str) { diff --git a/src/test/compile-fail/E0297.rs b/src/test/compile-fail/E0297.rs index 32c129b22a1..5792ba06eb0 100644 --- a/src/test/compile-fail/E0297.rs +++ b/src/test/compile-fail/E0297.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let xs : Vec<Option<i32>> = vec!(Some(1), None); + let xs : Vec<Option<i32>> = vec![Some(1), None]; for Some(x) in xs {} //~^ ERROR E0297 diff --git a/src/test/compile-fail/auto-ref-slice-plus-ref.rs b/src/test/compile-fail/auto-ref-slice-plus-ref.rs index f0f0bdfb38e..324e9259647 100644 --- a/src/test/compile-fail/auto-ref-slice-plus-ref.rs +++ b/src/test/compile-fail/auto-ref-slice-plus-ref.rs @@ -14,7 +14,7 @@ fn main() { // Testing that method lookup does not automatically borrow // vectors to slices then automatically create a self reference. - let mut a = vec!(0); + let mut a = vec![0]; a.test_mut(); //~ ERROR no method named `test_mut` found a.test(); //~ ERROR no method named `test` found diff --git a/src/test/compile-fail/borrowck/borrowck-assign-comp-idx.rs b/src/test/compile-fail/borrowck/borrowck-assign-comp-idx.rs index b18df7f3db6..1e665a12a19 100644 --- a/src/test/compile-fail/borrowck/borrowck-assign-comp-idx.rs +++ b/src/test/compile-fail/borrowck/borrowck-assign-comp-idx.rs @@ -14,7 +14,7 @@ struct Point { } fn a() { - let mut p = vec!(1); + let mut p = vec![1]; // Create an immutable pointer into p's contents: let q: &isize = &p[0]; @@ -30,7 +30,7 @@ fn b() { // here we alias the mutable vector into an imm slice and try to // modify the original: - let mut p = vec!(1); + let mut p = vec![1]; borrow( &p, @@ -40,7 +40,7 @@ fn b() { fn c() { // Legal because the scope of the borrow does not include the // modification: - let mut p = vec!(1); + let mut p = vec![1]; borrow(&p, ||{}); p[0] = 5; } diff --git a/src/test/compile-fail/borrowck/borrowck-borrowed-uniq-rvalue-2.rs b/src/test/compile-fail/borrowck/borrowck-borrowed-uniq-rvalue-2.rs index 7b811f581c1..9178aadeeeb 100644 --- a/src/test/compile-fail/borrowck/borrowck-borrowed-uniq-rvalue-2.rs +++ b/src/test/compile-fail/borrowck/borrowck-borrowed-uniq-rvalue-2.rs @@ -29,6 +29,6 @@ fn defer<'r>(x: &'r [&'r str]) -> defer<'r> { } fn main() { - let x = defer(&vec!("Goodbye", "world!")); + let x = defer(&vec!["Goodbye", "world!"]); x.x[0]; } diff --git a/src/test/compile-fail/borrowck/borrowck-loan-vec-content.rs b/src/test/compile-fail/borrowck/borrowck-loan-vec-content.rs index 21d9dea77b2..c5de95f8fc0 100644 --- a/src/test/compile-fail/borrowck/borrowck-loan-vec-content.rs +++ b/src/test/compile-fail/borrowck/borrowck-loan-vec-content.rs @@ -17,12 +17,12 @@ fn takes_imm_elt<F>(_v: &isize, f: F) where F: FnOnce() { } fn has_mut_vec_and_does_not_try_to_change_it() { - let mut v: Vec<isize> = vec!(1, 2, 3); + let mut v: Vec<isize> = vec![1, 2, 3]; takes_imm_elt(&v[0], || {}) } fn has_mut_vec_but_tries_to_change_it() { - let mut v: Vec<isize> = vec!(1, 2, 3); + let mut v: Vec<isize> = vec![1, 2, 3]; takes_imm_elt( &v[0], || { //~ ERROR cannot borrow `v` as mutable diff --git a/src/test/compile-fail/borrowck/borrowck-move-out-of-overloaded-auto-deref.rs b/src/test/compile-fail/borrowck/borrowck-move-out-of-overloaded-auto-deref.rs index 27cef1f3c60..bf4c7474136 100644 --- a/src/test/compile-fail/borrowck/borrowck-move-out-of-overloaded-auto-deref.rs +++ b/src/test/compile-fail/borrowck/borrowck-move-out-of-overloaded-auto-deref.rs @@ -11,6 +11,6 @@ use std::rc::Rc; pub fn main() { - let _x = Rc::new(vec!(1, 2)).into_iter(); + let _x = Rc::new(vec![1, 2]).into_iter(); //~^ ERROR cannot move out of borrowed content } diff --git a/src/test/compile-fail/borrowck/borrowck-move-out-of-vec-tail.rs b/src/test/compile-fail/borrowck/borrowck-move-out-of-vec-tail.rs index 51e00a0ad2c..311208f07b8 100644 --- a/src/test/compile-fail/borrowck/borrowck-move-out-of-vec-tail.rs +++ b/src/test/compile-fail/borrowck/borrowck-move-out-of-vec-tail.rs @@ -18,11 +18,11 @@ struct Foo { } pub fn main() { - let x = vec!( + let x = vec![ Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } - ); + ]; let x: &[Foo] = &x; match *x { [_, ref tail..] => { diff --git a/src/test/compile-fail/borrowck/borrowck-mut-slice-of-imm-vec.rs b/src/test/compile-fail/borrowck/borrowck-mut-slice-of-imm-vec.rs index 9341758afd8..4e0304e20c0 100644 --- a/src/test/compile-fail/borrowck/borrowck-mut-slice-of-imm-vec.rs +++ b/src/test/compile-fail/borrowck/borrowck-mut-slice-of-imm-vec.rs @@ -13,6 +13,6 @@ fn write(v: &mut [isize]) { } fn main() { - let v = vec!(1, 2, 3); + let v = vec![1, 2, 3]; write(&mut v); //~ ERROR cannot borrow } diff --git a/src/test/compile-fail/borrowck/borrowck-overloaded-index-move-from-vec.rs b/src/test/compile-fail/borrowck/borrowck-overloaded-index-move-from-vec.rs index 1b62d9c326d..df72c2b0af7 100644 --- a/src/test/compile-fail/borrowck/borrowck-overloaded-index-move-from-vec.rs +++ b/src/test/compile-fail/borrowck/borrowck-overloaded-index-move-from-vec.rs @@ -25,7 +25,7 @@ impl<T> Index<usize> for MyVec<T> { } fn main() { - let v = MyVec::<Box<_>> { data: vec!(box 1, box 2, box 3) }; + let v = MyVec::<Box<_>> { data: vec![box 1, box 2, box 3] }; let good = &v[0]; // Shouldn't fail here let bad = v[0]; //~^ ERROR cannot move out of indexed content diff --git a/src/test/compile-fail/borrowck/borrowck-vec-pattern-element-loan.rs b/src/test/compile-fail/borrowck/borrowck-vec-pattern-element-loan.rs index 63e80b90ac8..eb5d69d49bd 100644 --- a/src/test/compile-fail/borrowck/borrowck-vec-pattern-element-loan.rs +++ b/src/test/compile-fail/borrowck/borrowck-vec-pattern-element-loan.rs @@ -12,7 +12,7 @@ #![feature(slice_patterns)] fn a<'a>() -> &'a [isize] { - let vec = vec!(1, 2, 3, 4); + let vec = vec![1, 2, 3, 4]; let vec: &[isize] = &vec; //~ ERROR does not live long enough let tail = match vec { &[_, ref tail..] => tail, @@ -22,7 +22,7 @@ fn a<'a>() -> &'a [isize] { } fn b<'a>() -> &'a [isize] { - let vec = vec!(1, 2, 3, 4); + let vec = vec![1, 2, 3, 4]; let vec: &[isize] = &vec; //~ ERROR does not live long enough let init = match vec { &[ref init.., _] => init, @@ -32,7 +32,7 @@ fn b<'a>() -> &'a [isize] { } fn c<'a>() -> &'a [isize] { - let vec = vec!(1, 2, 3, 4); + let vec = vec![1, 2, 3, 4]; let vec: &[isize] = &vec; //~ ERROR does not live long enough let slice = match vec { &[_, ref slice.., _] => slice, diff --git a/src/test/compile-fail/borrowck/borrowck-vec-pattern-loan-from-mut.rs b/src/test/compile-fail/borrowck/borrowck-vec-pattern-loan-from-mut.rs index 9dfd4d77928..505c8c6d535 100644 --- a/src/test/compile-fail/borrowck/borrowck-vec-pattern-loan-from-mut.rs +++ b/src/test/compile-fail/borrowck/borrowck-vec-pattern-loan-from-mut.rs @@ -11,7 +11,7 @@ #![feature(slice_patterns)] fn a() { - let mut v = vec!(1, 2, 3); + let mut v = vec![1, 2, 3]; let vb: &mut [isize] = &mut v; match vb { &mut [_a, ref tail..] => { diff --git a/src/test/compile-fail/borrowck/borrowck-vec-pattern-nesting.rs b/src/test/compile-fail/borrowck/borrowck-vec-pattern-nesting.rs index ae001e4e34d..d26364efdbc 100644 --- a/src/test/compile-fail/borrowck/borrowck-vec-pattern-nesting.rs +++ b/src/test/compile-fail/borrowck/borrowck-vec-pattern-nesting.rs @@ -25,7 +25,7 @@ fn a() { } fn b() { - let mut vec = vec!(box 1, box 2, box 3); + let mut vec = vec![box 1, box 2, box 3]; let vec: &mut [Box<isize>] = &mut vec; match vec { &mut [ref _b..] => { @@ -37,7 +37,7 @@ fn b() { } fn c() { - let mut vec = vec!(box 1, box 2, box 3); + let mut vec = vec![box 1, box 2, box 3]; let vec: &mut [Box<isize>] = &mut vec; match vec { &mut [_a, //~ ERROR cannot move out @@ -59,7 +59,7 @@ fn c() { } fn d() { - let mut vec = vec!(box 1, box 2, box 3); + let mut vec = vec![box 1, box 2, box 3]; let vec: &mut [Box<isize>] = &mut vec; match vec { &mut [ //~ ERROR cannot move out @@ -73,7 +73,7 @@ fn d() { } fn e() { - let mut vec = vec!(box 1, box 2, box 3); + let mut vec = vec![box 1, box 2, box 3]; let vec: &mut [Box<isize>] = &mut vec; match vec { &mut [_a, _b, _c] => {} //~ ERROR cannot move out diff --git a/src/test/compile-fail/borrowck/borrowck-vec-pattern-tail-element-loan.rs b/src/test/compile-fail/borrowck/borrowck-vec-pattern-tail-element-loan.rs index a849e4e2faf..cd8f3ebefe6 100644 --- a/src/test/compile-fail/borrowck/borrowck-vec-pattern-tail-element-loan.rs +++ b/src/test/compile-fail/borrowck/borrowck-vec-pattern-tail-element-loan.rs @@ -11,7 +11,7 @@ #![feature(slice_patterns)] fn a<'a>() -> &'a isize { - let vec = vec!(1, 2, 3, 4); + let vec = vec![1, 2, 3, 4]; let vec: &[isize] = &vec; //~ ERROR `vec` does not live long enough let tail = match vec { &[_a, ref tail..] => &tail[0], diff --git a/src/test/compile-fail/drop-with-active-borrows-2.rs b/src/test/compile-fail/drop-with-active-borrows-2.rs index e6e1364dd2c..33e4d3e62c4 100644 --- a/src/test/compile-fail/drop-with-active-borrows-2.rs +++ b/src/test/compile-fail/drop-with-active-borrows-2.rs @@ -9,7 +9,7 @@ // except according to those terms. fn read_lines_borrowed<'a>() -> Vec<&'a str> { - let raw_lines: Vec<String> = vec!("foo ".to_string(), " bar".to_string()); + let raw_lines: Vec<String> = vec!["foo ".to_string(), " bar".to_string()]; raw_lines.iter().map(|l| l.trim()).collect() //~^ ERROR `raw_lines` does not live long enough } diff --git a/src/test/compile-fail/integral-indexing.rs b/src/test/compile-fail/integral-indexing.rs index 897aca66cbf..c8f33c3caf8 100644 --- a/src/test/compile-fail/integral-indexing.rs +++ b/src/test/compile-fail/integral-indexing.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let v: Vec<isize> = vec!(0, 1, 2, 3, 4, 5); + let v: Vec<isize> = vec![0, 1, 2, 3, 4, 5]; let s: String = "abcdef".to_string(); v[3_usize]; v[3]; diff --git a/src/test/compile-fail/issue-11873.rs b/src/test/compile-fail/issue-11873.rs index 38956944f63..4618851529a 100644 --- a/src/test/compile-fail/issue-11873.rs +++ b/src/test/compile-fail/issue-11873.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let mut v = vec!(1); + let mut v = vec![1]; let mut f = || v.push(2); let _w = v; //~ ERROR: cannot move out of `v` diff --git a/src/test/compile-fail/issue-13446.rs b/src/test/compile-fail/issue-13446.rs index 53d14862889..6ad3ec67b29 100644 --- a/src/test/compile-fail/issue-13446.rs +++ b/src/test/compile-fail/issue-13446.rs @@ -13,6 +13,6 @@ // error-pattern: mismatched types -static VEC: [u32; 256] = vec!(); +static VEC: [u32; 256] = vec![]; fn main() {} diff --git a/src/test/compile-fail/issue-3044.rs b/src/test/compile-fail/issue-3044.rs index b934cbe4b5d..c7b276da573 100644 --- a/src/test/compile-fail/issue-3044.rs +++ b/src/test/compile-fail/issue-3044.rs @@ -10,7 +10,7 @@ fn main() { - let needlesArr: Vec<char> = vec!('a', 'f'); + let needlesArr: Vec<char> = vec!['a', 'f']; needlesArr.iter().fold(|x, y| { }); //~^^ ERROR this function takes 2 parameters but 1 parameter was supplied diff --git a/src/test/compile-fail/issue-5067.rs b/src/test/compile-fail/issue-5067.rs index b7b5553dc74..1c543a5fdac 100644 --- a/src/test/compile-fail/issue-5067.rs +++ b/src/test/compile-fail/issue-5067.rs @@ -48,7 +48,7 @@ macro_rules! make_vec { } fn main() { - let _ = make_vec!(a 1, a 2, a 3); + let _ = make_vec![a 1, a 2, a 3]; } diff --git a/src/test/compile-fail/lint-unused-mut-variables.rs b/src/test/compile-fail/lint-unused-mut-variables.rs index 8165dd0fa29..21cfadb9c79 100644 --- a/src/test/compile-fail/lint-unused-mut-variables.rs +++ b/src/test/compile-fail/lint-unused-mut-variables.rs @@ -21,7 +21,7 @@ fn main() { let mut a = 3; //~ ERROR: variable does not need to be mutable let mut a = 2; //~ ERROR: variable does not need to be mutable let mut b = 3; //~ ERROR: variable does not need to be mutable - let mut a = vec!(3); //~ ERROR: variable does not need to be mutable + let mut a = vec![3]; //~ ERROR: variable does not need to be mutable let (mut a, b) = (1, 2); //~ ERROR: variable does not need to be mutable let mut a; //~ ERROR: variable does not need to be mutable a = 3; @@ -88,5 +88,5 @@ fn callback<F>(f: F) where F: FnOnce() {} #[allow(unused_mut)] fn foo(mut a: isize) { let mut a = 3; - let mut b = vec!(2); + let mut b = vec![2]; } diff --git a/src/test/compile-fail/match-vec-unreachable.rs b/src/test/compile-fail/match-vec-unreachable.rs index 57e3a58b566..4d9b3aea112 100644 --- a/src/test/compile-fail/match-vec-unreachable.rs +++ b/src/test/compile-fail/match-vec-unreachable.rs @@ -29,7 +29,7 @@ fn main() { _ => { } } - let x: Vec<char> = vec!('a', 'b', 'c'); + let x: Vec<char> = vec!['a', 'b', 'c']; let x: &[char] = &x; match *x { ['a', 'b', 'c', ref _tail..] => {} diff --git a/src/test/compile-fail/moves-based-on-type-access-to-field.rs b/src/test/compile-fail/moves-based-on-type-access-to-field.rs index b8572fbd215..63fb4ff02a4 100644 --- a/src/test/compile-fail/moves-based-on-type-access-to-field.rs +++ b/src/test/compile-fail/moves-based-on-type-access-to-field.rs @@ -16,7 +16,7 @@ fn consume(_s: String) {} fn touch<A>(_a: &A) {} fn f20() { - let x = vec!("hi".to_string()); + let x = vec!["hi".to_string()]; consume(x.into_iter().next().unwrap()); touch(&x[0]); //~ ERROR use of moved value: `x` } diff --git a/src/test/compile-fail/moves-based-on-type-exprs.rs b/src/test/compile-fail/moves-based-on-type-exprs.rs index 9ad44567a41..194f278259b 100644 --- a/src/test/compile-fail/moves-based-on-type-exprs.rs +++ b/src/test/compile-fail/moves-based-on-type-exprs.rs @@ -29,7 +29,7 @@ fn f20() { } fn f21() { - let x = vec!(1, 2, 3); + let x = vec![1, 2, 3]; let _y = (x[0], 3); touch(&x); } @@ -77,24 +77,24 @@ fn f70() { fn f80() { let x = "hi".to_string(); - let _y = vec!(x); + let _y = vec![x]; touch(&x); //~ ERROR use of moved value: `x` } fn f100() { - let x = vec!("hi".to_string()); + let x = vec!["hi".to_string()]; let _y = x.into_iter().next().unwrap(); touch(&x); //~ ERROR use of moved value: `x` } fn f110() { - let x = vec!("hi".to_string()); + let x = vec!["hi".to_string()]; let _y = [x.into_iter().next().unwrap(); 1]; touch(&x); //~ ERROR use of moved value: `x` } fn f120() { - let mut x = vec!("hi".to_string(), "ho".to_string()); + let mut x = vec!["hi".to_string(), "ho".to_string()]; x.swap(0, 1); touch(&x[0]); touch(&x[1]); diff --git a/src/test/compile-fail/no-capture-arc.rs b/src/test/compile-fail/no-capture-arc.rs index 7b7b3c414dd..5e1d22bf63b 100644 --- a/src/test/compile-fail/no-capture-arc.rs +++ b/src/test/compile-fail/no-capture-arc.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use std::thread; fn main() { - let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let arc_v = Arc::new(v); thread::spawn(move|| { diff --git a/src/test/compile-fail/no-reuse-move-arc.rs b/src/test/compile-fail/no-reuse-move-arc.rs index 1720b40c83b..76c8a444320 100644 --- a/src/test/compile-fail/no-reuse-move-arc.rs +++ b/src/test/compile-fail/no-reuse-move-arc.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use std::thread; fn main() { - let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let arc_v = Arc::new(v); thread::spawn(move|| { diff --git a/src/test/compile-fail/non-copyable-void.rs b/src/test/compile-fail/non-copyable-void.rs index fd245f38a0c..6067b71280c 100644 --- a/src/test/compile-fail/non-copyable-void.rs +++ b/src/test/compile-fail/non-copyable-void.rs @@ -11,7 +11,7 @@ extern crate libc; fn main() { - let x : *const Vec<isize> = &vec!(1,2,3); + let x : *const Vec<isize> = &vec![1,2,3]; let y : *const libc::c_void = x as *const libc::c_void; unsafe { let _z = (*y).clone(); diff --git a/src/test/compile-fail/non-exhaustive-match.rs b/src/test/compile-fail/non-exhaustive-match.rs index 017baacc9d3..74e728d713b 100644 --- a/src/test/compile-fail/non-exhaustive-match.rs +++ b/src/test/compile-fail/non-exhaustive-match.rs @@ -37,20 +37,20 @@ fn main() { (_, t::a) => {} (t::b, t::b) => {} } - let vec = vec!(Some(42), None, Some(21)); + let vec = vec![Some(42), None, Some(21)]; let vec: &[Option<isize>] = &vec; match *vec { //~ ERROR non-exhaustive patterns: `[]` not covered [Some(..), None, ref tail..] => {} [Some(..), Some(..), ref tail..] => {} [None] => {} } - let vec = vec!(1); + let vec = vec![1]; let vec: &[isize] = &vec; match *vec { [_, ref tail..] => (), [] => () } - let vec = vec!(0.5f32); + let vec = vec![0.5f32]; let vec: &[f32] = &vec; match *vec { //~ ERROR non-exhaustive patterns: `[_, _, _, _]` not covered [0.1, 0.2, 0.3] => (), @@ -58,7 +58,7 @@ fn main() { [0.1] => (), [] => () } - let vec = vec!(Some(42), None, Some(21)); + let vec = vec![Some(42), None, Some(21)]; let vec: &[Option<isize>] = &vec; match *vec { [Some(..), None, ref tail..] => {} diff --git a/src/test/compile-fail/on-unimplemented/on-trait.rs b/src/test/compile-fail/on-unimplemented/on-trait.rs index ef7695af3e1..3a789f3faeb 100644 --- a/src/test/compile-fail/on-unimplemented/on-trait.rs +++ b/src/test/compile-fail/on-unimplemented/on-trait.rs @@ -30,7 +30,7 @@ fn collect<A, I: Iterator<Item=A>, B: MyFromIterator<A>>(it: I) -> B { } pub fn main() { - let x = vec!(1u8, 2, 3, 4); + let x = vec![1u8, 2, 3, 4]; let y: Option<Vec<u8>> = collect(x.iter()); // this should give approximately the same error for x.iter().collect() //~^ ERROR //~^^ NOTE a collection of type `std::option::Option<std::vec::Vec<u8>>` cannot be built from an iterator over elements of type `&u8` diff --git a/src/test/compile-fail/unboxed-closures-failed-recursive-fn-2.rs b/src/test/compile-fail/unboxed-closures-failed-recursive-fn-2.rs index f40c8fc7474..12b48b2a6c8 100644 --- a/src/test/compile-fail/unboxed-closures-failed-recursive-fn-2.rs +++ b/src/test/compile-fail/unboxed-closures-failed-recursive-fn-2.rs @@ -16,7 +16,7 @@ fn a() { let mut closure0 = None; - let vec = vec!(1, 2, 3); + let vec = vec![1, 2, 3]; loop { { diff --git a/src/test/compile-fail/unboxed-closures-move-upvar-from-non-once-ref-closure.rs b/src/test/compile-fail/unboxed-closures-move-upvar-from-non-once-ref-closure.rs index e66610c1496..cd9f1636c3f 100644 --- a/src/test/compile-fail/unboxed-closures-move-upvar-from-non-once-ref-closure.rs +++ b/src/test/compile-fail/unboxed-closures-move-upvar-from-non-once-ref-closure.rs @@ -16,7 +16,7 @@ fn call<F>(f: F) where F : Fn() { } fn main() { - let y = vec!(format!("World")); + let y = vec![format!("World")]; call(|| { y.into_iter(); //~^ ERROR cannot move out of captured outer variable in an `Fn` closure diff --git a/src/test/compile-fail/vec-macro-with-comma-only.rs b/src/test/compile-fail/vec-macro-with-comma-only.rs index 346cf1ec555..96f58666fdf 100644 --- a/src/test/compile-fail/vec-macro-with-comma-only.rs +++ b/src/test/compile-fail/vec-macro-with-comma-only.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn main() { - vec!(,); //~ ERROR expected expression, found `,` + vec![,]; //~ ERROR expected expression, found `,` } diff --git a/src/test/compile-fail/vec-mut-iter-borrow.rs b/src/test/compile-fail/vec-mut-iter-borrow.rs index 023ef72c453..571634e3992 100644 --- a/src/test/compile-fail/vec-mut-iter-borrow.rs +++ b/src/test/compile-fail/vec-mut-iter-borrow.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let mut xs: Vec<isize> = vec!(); + let mut xs: Vec<isize> = vec![]; for x in &mut xs { xs.push(1) //~ ERROR cannot borrow `xs` diff --git a/src/test/compile-fail/vec-res-add.rs b/src/test/compile-fail/vec-res-add.rs index cf64486c9c7..27f6fc51164 100644 --- a/src/test/compile-fail/vec-res-add.rs +++ b/src/test/compile-fail/vec-res-add.rs @@ -21,8 +21,8 @@ impl Drop for r { fn main() { // This can't make sense as it would copy the classes - let i = vec!(r(0)); - let j = vec!(r(1)); + let i = vec![r(0)]; + let j = vec![r(1)]; let k = i + j; //~^ ERROR binary operation `+` cannot be applied to type println!("{:?}", j); diff --git a/src/test/compile-fail/writing-to-immutable-vec.rs b/src/test/compile-fail/writing-to-immutable-vec.rs index 09c9439b464..f289b85992e 100644 --- a/src/test/compile-fail/writing-to-immutable-vec.rs +++ b/src/test/compile-fail/writing-to-immutable-vec.rs @@ -10,6 +10,6 @@ fn main() { - let v: Vec<isize> = vec!(1, 2, 3); + let v: Vec<isize> = vec![1, 2, 3]; v[1] = 4; //~ ERROR cannot borrow immutable local variable `v` as mutable } diff --git a/src/test/debuginfo/issue14411.rs b/src/test/debuginfo/issue14411.rs index 3b2d372117d..d334e33f887 100644 --- a/src/test/debuginfo/issue14411.rs +++ b/src/test/debuginfo/issue14411.rs @@ -20,6 +20,6 @@ fn test(a: &Vec<u8>) { } pub fn main() { - let data = vec!(); + let data = vec![]; test(&data); } diff --git a/src/test/incremental/change_private_fn/struct_point.rs b/src/test/incremental/change_private_fn/struct_point.rs new file mode 100644 index 00000000000..678bc10f1e5 --- /dev/null +++ b/src/test/incremental/change_private_fn/struct_point.rs @@ -0,0 +1,111 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Test where we change the body of a private method in an impl. +// We then test what sort of functions must be rebuilt as a result. + +// revisions:rpass1 rpass2 +// compile-flags: -Z query-dep-graph + +#![feature(rustc_attrs)] +#![feature(stmt_expr_attributes)] +#![allow(dead_code)] + +#![rustc_partition_translated(module="struct_point-point", cfg="rpass2")] + +#![rustc_partition_reused(module="struct_point-fn_calls_methods_in_same_impl", cfg="rpass2")] +#![rustc_partition_reused(module="struct_point-fn_calls_methods_in_another_impl", cfg="rpass2")] +#![rustc_partition_reused(module="struct_point-fn_make_struct", cfg="rpass2")] +#![rustc_partition_reused(module="struct_point-fn_read_field", cfg="rpass2")] +#![rustc_partition_reused(module="struct_point-fn_write_field", cfg="rpass2")] + +mod point { + pub struct Point { + pub x: f32, + pub y: f32, + } + + fn distance_squared(this: &Point) -> f32 { + #[cfg(rpass1)] + return this.x + this.y; + + #[cfg(rpass2)] + return this.x * this.x + this.y * this.y; + } + + impl Point { + pub fn distance_from_origin(&self) -> f32 { + distance_squared(self).sqrt() + } + } + + impl Point { + pub fn translate(&mut self, x: f32, y: f32) { + self.x += x; + self.y += y; + } + } + +} + +/// A fn item that calls (public) methods on `Point` from the same impl which changed +mod fn_calls_methods_in_same_impl { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn check() { + let x = Point { x: 2.0, y: 2.0 }; + x.distance_from_origin(); + } +} + +/// A fn item that calls (public) methods on `Point` from another impl +mod fn_calls_methods_in_another_impl { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn check() { + let mut x = Point { x: 2.0, y: 2.0 }; + x.translate(3.0, 3.0); + } +} + +/// A fn item that makes an instance of `Point` but does not invoke methods +mod fn_make_struct { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn make_origin() -> Point { + Point { x: 2.0, y: 2.0 } + } +} + +/// A fn item that reads fields from `Point` but does not invoke methods +mod fn_read_field { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn get_x(p: Point) -> f32 { + p.x + } +} + +/// A fn item that writes to a field of `Point` but does not invoke methods +mod fn_write_field { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn inc_x(p: &mut Point) { + p.x += 1.0; + } +} + +fn main() { +} diff --git a/src/test/incremental/change_private_fn_cc/auxiliary/point.rs b/src/test/incremental/change_private_fn_cc/auxiliary/point.rs new file mode 100644 index 00000000000..dcc1ced635f --- /dev/null +++ b/src/test/incremental/change_private_fn_cc/auxiliary/point.rs @@ -0,0 +1,35 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub struct Point { + pub x: f32, + pub y: f32, +} + +fn distance_squared(this: &Point) -> f32 { + #[cfg(rpass1)] + return this.x + this.y; + + #[cfg(rpass2)] + return this.x * this.x + this.y * this.y; +} + +impl Point { + pub fn distance_from_origin(&self) -> f32 { + distance_squared(self).sqrt() + } +} + +impl Point { + pub fn translate(&mut self, x: f32, y: f32) { + self.x += x; + self.y += y; + } +} diff --git a/src/test/incremental/change_private_fn_cc/struct_point.rs b/src/test/incremental/change_private_fn_cc/struct_point.rs new file mode 100644 index 00000000000..d6d2b5436ff --- /dev/null +++ b/src/test/incremental/change_private_fn_cc/struct_point.rs @@ -0,0 +1,86 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Test where we change the body of a private method in an impl. +// We then test what sort of functions must be rebuilt as a result. + +// revisions:rpass1 rpass2 +// compile-flags: -Z query-dep-graph +// aux-build:point.rs + +#![feature(rustc_attrs)] +#![feature(stmt_expr_attributes)] +#![allow(dead_code)] + +#![rustc_partition_reused(module="struct_point-fn_calls_methods_in_same_impl", cfg="rpass2")] +#![rustc_partition_reused(module="struct_point-fn_calls_methods_in_another_impl", cfg="rpass2")] +#![rustc_partition_reused(module="struct_point-fn_read_field", cfg="rpass2")] +#![rustc_partition_reused(module="struct_point-fn_write_field", cfg="rpass2")] + +// FIXME(#37335) -- should be reused, but an errant Krate edge causes +// it to get translated (at least I *think* this is that same problem) +#![rustc_partition_translated(module="struct_point-fn_make_struct", cfg="rpass2")] + +extern crate point; + +/// A fn item that calls (public) methods on `Point` from the same impl which changed +mod fn_calls_methods_in_same_impl { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn check() { + let x = Point { x: 2.0, y: 2.0 }; + x.distance_from_origin(); + } +} + +/// A fn item that calls (public) methods on `Point` from another impl +mod fn_calls_methods_in_another_impl { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn check() { + let mut x = Point { x: 2.0, y: 2.0 }; + x.translate(3.0, 3.0); + } +} + +/// A fn item that makes an instance of `Point` but does not invoke methods +mod fn_make_struct { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn make_origin() -> Point { + Point { x: 2.0, y: 2.0 } + } +} + +/// A fn item that reads fields from `Point` but does not invoke methods +mod fn_read_field { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn get_x(p: Point) -> f32 { + p.x + } +} + +/// A fn item that writes to a field of `Point` but does not invoke methods +mod fn_write_field { + use point::Point; + + #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] + pub fn inc_x(p: &mut Point) { + p.x += 1.0; + } +} + +fn main() { +} diff --git a/src/test/incremental/change_private_impl_method_cc/auxiliary/point.rs b/src/test/incremental/change_private_impl_method_cc/auxiliary/point.rs new file mode 100644 index 00000000000..8df1cf54da2 --- /dev/null +++ b/src/test/incremental/change_private_impl_method_cc/auxiliary/point.rs @@ -0,0 +1,35 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub struct Point { + pub x: f32, + pub y: f32, +} + +impl Point { + fn distance_squared(&self) -> f32 { + #[cfg(rpass1)] + return self.x + self.y; + + #[cfg(rpass2)] + return self.x * self.x + self.y * self.y; + } + + pub fn distance_from_origin(&self) -> f32 { + self.distance_squared().sqrt() + } +} + +impl Point { + pub fn translate(&mut self, x: f32, y: f32) { + self.x += x; + self.y += y; + } +} diff --git a/src/test/incremental/change_private_impl_method_cc/struct_point.rs b/src/test/incremental/change_private_impl_method_cc/struct_point.rs new file mode 100644 index 00000000000..d8e5fbadad8 --- /dev/null +++ b/src/test/incremental/change_private_impl_method_cc/struct_point.rs @@ -0,0 +1,89 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Test where we change the body of a private method in an impl. +// We then test what sort of functions must be rebuilt as a result. + +// revisions:rpass1 rpass2 +// compile-flags: -Z query-dep-graph +// aux-build:point.rs + +#![feature(rustc_attrs)] +#![feature(stmt_expr_attributes)] +#![allow(dead_code)] + +// FIXME(#37333) -- the following modules *should* be reused but are not +#![rustc_partition_translated(module="struct_point-fn_calls_methods_in_same_impl", cfg="rpass2")] +#![rustc_partition_translated(module="struct_point-fn_calls_methods_in_another_impl", cfg="rpass2")] +#![rustc_partition_translated(module="struct_point-fn_make_struct", cfg="rpass2")] +#![rustc_partition_translated(module="struct_point-fn_read_field", cfg="rpass2")] +#![rustc_partition_translated(module="struct_point-fn_write_field", cfg="rpass2")] + +extern crate point; + +/// A fn item that calls (public) methods on `Point` from the same impl which changed +mod fn_calls_methods_in_same_impl { + use point::Point; + + // FIXME(#37333) -- we should not need to typeck this again + #[rustc_dirty(label="TypeckItemBody", cfg="rpass2")] + pub fn check() { + let x = Point { x: 2.0, y: 2.0 }; + x.distance_from_origin(); + } +} + +/// A fn item that calls (public) methods on `Point` from another impl +mod fn_calls_methods_in_another_impl { + use point::Point; + + // FIXME(#37333) -- we should not need to typeck this again + #[rustc_dirty(label="TypeckItemBody", cfg="rpass2")] + pub fn check() { + let mut x = Point { x: 2.0, y: 2.0 }; + x.translate(3.0, 3.0); + } +} + +/// A fn item that makes an instance of `Point` but does not invoke methods +mod fn_make_struct { + use point::Point; + + // FIXME(#37333) -- we should not need to typeck this again + #[rustc_dirty(label="TypeckItemBody", cfg="rpass2")] + pub fn make_origin() -> Point { + Point { x: 2.0, y: 2.0 } + } +} + +/// A fn item that reads fields from `Point` but does not invoke methods +mod fn_read_field { + use point::Point; + + // FIXME(#37333) -- we should not need to typeck this again + #[rustc_dirty(label="TypeckItemBody", cfg="rpass2")] + pub fn get_x(p: Point) -> f32 { + p.x + } +} + +/// A fn item that writes to a field of `Point` but does not invoke methods +mod fn_write_field { + use point::Point; + + // FIXME(#37333) -- we should not need to typeck this again + #[rustc_dirty(label="TypeckItemBody", cfg="rpass2")] + pub fn inc_x(p: &mut Point) { + p.x += 1.0; + } +} + +fn main() { +} diff --git a/src/test/incremental/hashes/panic_exprs.rs b/src/test/incremental/hashes/panic_exprs.rs new file mode 100644 index 00000000000..f5f4c0042b4 --- /dev/null +++ b/src/test/incremental/hashes/panic_exprs.rs @@ -0,0 +1,173 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This test case tests the incremental compilation hash (ICH) implementation +// for exprs that can panic at runtime (e.g. because of bounds checking). For +// these expressions an error message containing their source location is +// generated, so their hash must always depend on their location in the source +// code, not just when debuginfo is enabled. + +// The general pattern followed here is: Change one thing between rev1 and rev2 +// and make sure that the hash has changed, then change nothing between rev2 and +// rev3 and make sure that the hash has not changed. + +// must-compile-successfully +// revisions: cfail1 cfail2 cfail3 +// compile-flags: -Z query-dep-graph -C debug-assertions + +#![allow(warnings)] +#![feature(rustc_attrs)] +#![crate_type="rlib"] + + +// Indexing expression --------------------------------------------------------- +#[cfg(cfail1)] +pub fn indexing(slice: &[u8]) -> u8 { + slice[100] +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn indexing(slice: &[u8]) -> u8 { + slice[100] +} + + +// Arithmetic overflow plus ---------------------------------------------------- +#[cfg(cfail1)] +pub fn arithmetic_overflow_plus(val: i32) -> i32 { + val + 1 +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn arithmetic_overflow_plus(val: i32) -> i32 { + val + 1 +} + + +// Arithmetic overflow minus ---------------------------------------------------- +#[cfg(cfail1)] +pub fn arithmetic_overflow_minus(val: i32) -> i32 { + val - 1 +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn arithmetic_overflow_minus(val: i32) -> i32 { + val - 1 +} + + +// Arithmetic overflow mult ---------------------------------------------------- +#[cfg(cfail1)] +pub fn arithmetic_overflow_mult(val: i32) -> i32 { + val * 2 +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn arithmetic_overflow_mult(val: i32) -> i32 { + val * 2 +} + + +// Arithmetic overflow negation ------------------------------------------------ +#[cfg(cfail1)] +pub fn arithmetic_overflow_negation(val: i32) -> i32 { + -val +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn arithmetic_overflow_negation(val: i32) -> i32 { + -val +} + + +// Division by zero ------------------------------------------------------------ +#[cfg(cfail1)] +pub fn division_by_zero(val: i32) -> i32 { + 2 / val +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn division_by_zero(val: i32) -> i32 { + 2 / val +} + +// Division by zero ------------------------------------------------------------ +#[cfg(cfail1)] +pub fn mod_by_zero(val: i32) -> i32 { + 2 % val +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn mod_by_zero(val: i32) -> i32 { + 2 % val +} + + + +// THE FOLLOWING ITEMS SHOULD NOT BE INFLUENCED BY THEIR SOURCE LOCATION + +// bitwise --------------------------------------------------------------------- +#[cfg(cfail1)] +pub fn bitwise(val: i32) -> i32 { + !val & 0x101010101 | 0x45689 ^ 0x2372382 << 1 >> 1 +} + +#[cfg(not(cfail1))] +#[rustc_clean(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_clean(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn bitwise(val: i32) -> i32 { + !val & 0x101010101 | 0x45689 ^ 0x2372382 << 1 >> 1 +} + + +// logical --------------------------------------------------------------------- +#[cfg(cfail1)] +pub fn logical(val1: bool, val2: bool, val3: bool) -> bool { + val1 && val2 || val3 +} + +#[cfg(not(cfail1))] +#[rustc_clean(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_clean(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn logical(val1: bool, val2: bool, val3: bool) -> bool { + val1 && val2 || val3 +} diff --git a/src/test/incremental/hashes/panic_exprs_no_overflow_checks.rs b/src/test/incremental/hashes/panic_exprs_no_overflow_checks.rs new file mode 100644 index 00000000000..b84b7f5f378 --- /dev/null +++ b/src/test/incremental/hashes/panic_exprs_no_overflow_checks.rs @@ -0,0 +1,251 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This test case tests the incremental compilation hash (ICH) implementation +// for exprs that can panic at runtime (e.g. because of bounds checking). For +// these expressions an error message containing their source location is +// generated, so their hash must always depend on their location in the source +// code, not just when debuginfo is enabled. + +// As opposed to the panic_exprs.rs test case, this test case checks that things +// behave as expected when overflow checks are off: +// +// - Addition, subtraction, and multiplication do not change the ICH, unless +// the function containing them is marked with rustc_inherit_overflow_checks. +// - Division by zero and bounds checks always influence the ICH + +// The general pattern followed here is: Change one thing between rev1 and rev2 +// and make sure that the hash has changed, then change nothing between rev2 and +// rev3 and make sure that the hash has not changed. + +// must-compile-successfully +// revisions: cfail1 cfail2 cfail3 +// compile-flags: -Z query-dep-graph -Z force-overflow-checks=off + +#![allow(warnings)] +#![feature(rustc_attrs)] +#![crate_type="rlib"] + + +// Indexing expression --------------------------------------------------------- +#[cfg(cfail1)] +pub fn indexing(slice: &[u8]) -> u8 { + slice[100] +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn indexing(slice: &[u8]) -> u8 { + slice[100] +} + + +// Arithmetic overflow plus ---------------------------------------------------- +#[cfg(cfail1)] +#[rustc_inherit_overflow_checks] +pub fn arithmetic_overflow_plus_inherit(val: i32) -> i32 { + val + 1 +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +#[rustc_inherit_overflow_checks] +pub fn arithmetic_overflow_plus_inherit(val: i32) -> i32 { + val + 1 +} + + +// Arithmetic overflow minus ---------------------------------------------------- +#[cfg(cfail1)] +#[rustc_inherit_overflow_checks] +pub fn arithmetic_overflow_minus_inherit(val: i32) -> i32 { + val - 1 +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +#[rustc_inherit_overflow_checks] +pub fn arithmetic_overflow_minus_inherit(val: i32) -> i32 { + val - 1 +} + + +// Arithmetic overflow mult ---------------------------------------------------- +#[cfg(cfail1)] +#[rustc_inherit_overflow_checks] +pub fn arithmetic_overflow_mult_inherit(val: i32) -> i32 { + val * 2 +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +#[rustc_inherit_overflow_checks] +pub fn arithmetic_overflow_mult_inherit(val: i32) -> i32 { + val * 2 +} + + +// Arithmetic overflow negation ------------------------------------------------ +#[cfg(cfail1)] +#[rustc_inherit_overflow_checks] +pub fn arithmetic_overflow_negation_inherit(val: i32) -> i32 { + -val +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +#[rustc_inherit_overflow_checks] +pub fn arithmetic_overflow_negation_inherit(val: i32) -> i32 { + -val +} + + +// Division by zero ------------------------------------------------------------ +#[cfg(cfail1)] +pub fn division_by_zero(val: i32) -> i32 { + 2 / val +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn division_by_zero(val: i32) -> i32 { + 2 / val +} + +// Division by zero ------------------------------------------------------------ +#[cfg(cfail1)] +pub fn mod_by_zero(val: i32) -> i32 { + 2 % val +} + +#[cfg(not(cfail1))] +#[rustc_dirty(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_dirty(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn mod_by_zero(val: i32) -> i32 { + 2 % val +} + + + +// THE FOLLOWING ITEMS SHOULD NOT BE INFLUENCED BY THEIR SOURCE LOCATION + +// bitwise --------------------------------------------------------------------- +#[cfg(cfail1)] +pub fn bitwise(val: i32) -> i32 { + !val & 0x101010101 | 0x45689 ^ 0x2372382 << 1 >> 1 +} + +#[cfg(not(cfail1))] +#[rustc_clean(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_clean(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn bitwise(val: i32) -> i32 { + !val & 0x101010101 | 0x45689 ^ 0x2372382 << 1 >> 1 +} + + +// logical --------------------------------------------------------------------- +#[cfg(cfail1)] +pub fn logical(val1: bool, val2: bool, val3: bool) -> bool { + val1 && val2 || val3 +} + +#[cfg(not(cfail1))] +#[rustc_clean(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_clean(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn logical(val1: bool, val2: bool, val3: bool) -> bool { + val1 && val2 || val3 +} + +// Arithmetic overflow plus ---------------------------------------------------- +#[cfg(cfail1)] +pub fn arithmetic_overflow_plus(val: i32) -> i32 { + val + 1 +} + +#[cfg(not(cfail1))] +#[rustc_clean(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_clean(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn arithmetic_overflow_plus(val: i32) -> i32 { + val + 1 +} + + +// Arithmetic overflow minus ---------------------------------------------------- +#[cfg(cfail1)] +pub fn arithmetic_overflow_minus(val: i32) -> i32 { + val - 1 +} + +#[cfg(not(cfail1))] +#[rustc_clean(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_clean(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn arithmetic_overflow_minus(val: i32) -> i32 { + val - 1 +} + + +// Arithmetic overflow mult ---------------------------------------------------- +#[cfg(cfail1)] +pub fn arithmetic_overflow_mult(val: i32) -> i32 { + val * 2 +} + +#[cfg(not(cfail1))] +#[rustc_clean(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_clean(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn arithmetic_overflow_mult(val: i32) -> i32 { + val * 2 +} + + +// Arithmetic overflow negation ------------------------------------------------ +#[cfg(cfail1)] +pub fn arithmetic_overflow_negation(val: i32) -> i32 { + -val +} + +#[cfg(not(cfail1))] +#[rustc_clean(label="Hir", cfg="cfail2")] +#[rustc_clean(label="Hir", cfg="cfail3")] +#[rustc_metadata_clean(cfg="cfail2")] +#[rustc_metadata_clean(cfg="cfail3")] +pub fn arithmetic_overflow_negation(val: i32) -> i32 { + -val +} diff --git a/src/test/parse-fail/issue-10412.rs b/src/test/parse-fail/issue-10412.rs index fc2598d1e9d..d723d94c02c 100644 --- a/src/test/parse-fail/issue-10412.rs +++ b/src/test/parse-fail/issue-10412.rs @@ -19,7 +19,7 @@ trait Serializable<'self, T> { //~ ERROR lifetimes cannot use keyword names impl<'self> Serializable<str> for &'self str { //~ ERROR lifetimes cannot use keyword names //~^ ERROR lifetimes cannot use keyword names fn serialize(val : &'self str) -> Vec<u8> { //~ ERROR lifetimes cannot use keyword names - vec!(1) + vec![1] } fn deserialize(repr: &[u8]) -> &'self str { //~ ERROR lifetimes cannot use keyword names "hi" diff --git a/src/test/pretty/block-disambig.rs b/src/test/pretty/block-disambig.rs index 5f88f903678..c645a66b70e 100644 --- a/src/test/pretty/block-disambig.rs +++ b/src/test/pretty/block-disambig.rs @@ -61,9 +61,9 @@ fn test9() { } fn test10() -> isize { - let regs = vec!(0); + let regs = vec![0]; match true { true => { } _ => { } } regs[0] } -fn test11() -> Vec<isize> { if true { } vec!(1, 2) } +fn test11() -> Vec<isize> { if true { } vec![1, 2] } diff --git a/src/test/run-pass-fulldeps/auxiliary/custom_derive_partial_eq.rs b/src/test/run-pass-fulldeps/auxiliary/custom_derive_partial_eq.rs index 956f789dab8..e750d1fb1e3 100644 --- a/src/test/run-pass-fulldeps/auxiliary/custom_derive_partial_eq.rs +++ b/src/test/run-pass-fulldeps/auxiliary/custom_derive_partial_eq.rs @@ -53,12 +53,12 @@ fn expand_deriving_partial_eq(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, it } let inline = cx.meta_word(span, InternedString::new("inline")); - let attrs = vec!(cx.attribute(span, inline)); + let attrs = vec![cx.attribute(span, inline)]; let methods = vec![MethodDef { name: "eq", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), - args: vec!(borrowed_self()), + args: vec![borrowed_self()], ret_ty: Literal(deriving::generic::ty::Path::new_local("bool")), attributes: attrs, is_unsafe: false, diff --git a/src/test/run-pass/assignability-trait.rs b/src/test/run-pass/assignability-trait.rs index c364240f4ad..bc95d96a8cc 100644 --- a/src/test/run-pass/assignability-trait.rs +++ b/src/test/run-pass/assignability-trait.rs @@ -38,7 +38,7 @@ fn length<A, T: iterable<A>>(x: T) -> usize { } pub fn main() { - let x: Vec<isize> = vec!(0,1,2,3); + let x: Vec<isize> = vec![0,1,2,3]; // Call a method x.iterate(|y| { assert_eq!(x[*y as usize], *y); true }); // Call a parameterized function diff --git a/src/test/run-pass/associated-types-doubleendediterator-object.rs b/src/test/run-pass/associated-types-doubleendediterator-object.rs index 1661812520b..dd194447740 100644 --- a/src/test/run-pass/associated-types-doubleendediterator-object.rs +++ b/src/test/run-pass/associated-types-doubleendediterator-object.rs @@ -25,7 +25,7 @@ fn pairwise_sub(mut t: Box<DoubleEndedIterator<Item=isize>>) -> isize { } fn main() { - let v = vec!(1, 2, 3, 4, 5, 6); + let v = vec![1, 2, 3, 4, 5, 6]; // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let r = pairwise_sub(Box::new(v.into_iter())); assert_eq!(r, 9); diff --git a/src/test/run-pass/associated-types-iterator-binding.rs b/src/test/run-pass/associated-types-iterator-binding.rs index be854f820d4..abd4917cae8 100644 --- a/src/test/run-pass/associated-types-iterator-binding.rs +++ b/src/test/run-pass/associated-types-iterator-binding.rs @@ -22,7 +22,7 @@ fn pairwise_sub<T:DoubleEndedIterator<Item=isize>>(mut t: T) -> isize { } fn main() { - let v = vec!(1, 2, 3, 4, 5, 6); + let v = vec![1, 2, 3, 4, 5, 6]; let r = pairwise_sub(v.into_iter()); assert_eq!(r, 9); } diff --git a/src/test/run-pass/auto-loop.rs b/src/test/run-pass/auto-loop.rs index babc0db4c31..b0afae79c36 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); + let xs = vec![1, 2, 3, 4, 5]; for x in &xs { sum += *x; } diff --git a/src/test/run-pass/auto-ref-sliceable.rs b/src/test/run-pass/auto-ref-sliceable.rs index 5b12edb4275..f6cb314d06e 100644 --- a/src/test/run-pass/auto-ref-sliceable.rs +++ b/src/test/run-pass/auto-ref-sliceable.rs @@ -21,7 +21,7 @@ impl<T> Pushable<T> for Vec<T> { } pub fn main() { - let mut v = vec!(1); + let mut v = vec![1]; v.push_val(2); v.push_val(3); assert_eq!(v, [1, 2, 3]); diff --git a/src/test/run-pass/autobind.rs b/src/test/run-pass/autobind.rs index 1f3d17ad55c..ed0b9eca0e0 100644 --- a/src/test/run-pass/autobind.rs +++ b/src/test/run-pass/autobind.rs @@ -12,7 +12,7 @@ fn f<T>(x: Vec<T>) -> T { return x.into_iter().next().unwrap(); } -fn g<F>(act: F) -> isize where F: FnOnce(Vec<isize>) -> isize { return act(vec!(1, 2, 3)); } +fn g<F>(act: F) -> isize where F: FnOnce(Vec<isize>) -> isize { return act(vec![1, 2, 3]); } pub fn main() { assert_eq!(g(f), 1); diff --git a/src/test/run-pass/block-arg.rs b/src/test/run-pass/block-arg.rs index 2f530331a2b..7fca4bccab3 100644 --- a/src/test/run-pass/block-arg.rs +++ b/src/test/run-pass/block-arg.rs @@ -10,7 +10,7 @@ // Check usage and precedence of block arguments in expressions: pub fn main() { - let v = vec!(-1.0f64, 0.0, 1.0, 2.0, 3.0); + let v = vec![-1.0f64, 0.0, 1.0, 2.0, 3.0]; // Statement form does not require parentheses: for i in &v { diff --git a/src/test/run-pass/borrow-by-val-method-receiver.rs b/src/test/run-pass/borrow-by-val-method-receiver.rs index 052b6053931..44f4a54610a 100644 --- a/src/test/run-pass/borrow-by-val-method-receiver.rs +++ b/src/test/run-pass/borrow-by-val-method-receiver.rs @@ -17,6 +17,6 @@ impl<'a> Foo for &'a [isize] { } pub fn main() { - let items = vec!( 3, 5, 1, 2, 4 ); + let items = vec![ 3, 5, 1, 2, 4 ]; items.foo(); } diff --git a/src/test/run-pass/borrowck/borrowck-binding-mutbl.rs b/src/test/run-pass/borrowck/borrowck-binding-mutbl.rs index 187063968f7..b6c2a3a61ea 100644 --- a/src/test/run-pass/borrowck/borrowck-binding-mutbl.rs +++ b/src/test/run-pass/borrowck/borrowck-binding-mutbl.rs @@ -14,7 +14,7 @@ fn impure(_v: &[isize]) { } pub fn main() { - let mut x = F {f: vec!(3)}; + let mut x = F {f: vec![3]}; match x { F {f: ref mut v} => { diff --git a/src/test/run-pass/borrowck/borrowck-mut-vec-as-imm-slice.rs b/src/test/run-pass/borrowck/borrowck-mut-vec-as-imm-slice.rs index d55517c65d6..4699f376313 100644 --- a/src/test/run-pass/borrowck/borrowck-mut-vec-as-imm-slice.rs +++ b/src/test/run-pass/borrowck/borrowck-mut-vec-as-imm-slice.rs @@ -21,5 +21,5 @@ fn has_mut_vec(v: Vec<isize> ) -> isize { } pub fn main() { - assert_eq!(has_mut_vec(vec!(1, 2, 3)), 6); + assert_eq!(has_mut_vec(vec![1, 2, 3]), 6); } diff --git a/src/test/run-pass/break.rs b/src/test/run-pass/break.rs index ea136e2dc48..9a32fbc1031 100644 --- a/src/test/run-pass/break.rs +++ b/src/test/run-pass/break.rs @@ -26,7 +26,7 @@ pub fn main() { i += 1; if i % 2 == 0 { continue; } assert!((i % 2 != 0)); if i >= 10 { break; } } - let ys = vec!(1, 2, 3, 4, 5, 6); + let ys = vec![1, 2, 3, 4, 5, 6]; for x in &ys { if *x % 2 == 0 { continue; } assert!((*x % 2 != 0)); diff --git a/src/test/run-pass/byte-literals.rs b/src/test/run-pass/byte-literals.rs index 9f7b98a57fc..ad779d26f9e 100644 --- a/src/test/run-pass/byte-literals.rs +++ b/src/test/run-pass/byte-literals.rs @@ -57,7 +57,7 @@ pub fn main() { _ => panic!(), } - let buf = vec!(97u8, 98, 99, 100); + let buf = vec![97u8, 98, 99, 100]; assert_eq!(match &buf[0..3] { b"def" => 1, b"abc" => 2, diff --git a/src/test/run-pass/cci_no_inline_exe.rs b/src/test/run-pass/cci_no_inline_exe.rs index cc76ed530c4..b105411c284 100644 --- a/src/test/run-pass/cci_no_inline_exe.rs +++ b/src/test/run-pass/cci_no_inline_exe.rs @@ -21,7 +21,7 @@ pub fn main() { // actually working. //let bt0 = sys::frame_address(); //println!("%?", bt0); - iter(vec!(1, 2, 3), |i| { + iter(vec![1, 2, 3], |i| { println!("{}", i); //let bt1 = sys::frame_address(); diff --git a/src/test/run-pass/class-poly-methods-cross-crate.rs b/src/test/run-pass/class-poly-methods-cross-crate.rs index 4d247bde190..7d266181c9e 100644 --- a/src/test/run-pass/class-poly-methods-cross-crate.rs +++ b/src/test/run-pass/class-poly-methods-cross-crate.rs @@ -14,12 +14,12 @@ extern crate cci_class_6; use cci_class_6::kitties::cat; pub fn main() { - let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!('p')); - let mut kitty = cat(1000_usize, 2, vec!("tabby".to_string())); + let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!['p']); + let mut kitty = cat(1000_usize, 2, vec!["tabby".to_string()]); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); - nyan.speak(vec!(1_usize,2_usize,3_usize)); + nyan.speak(vec![1_usize,2_usize,3_usize]); assert_eq!(nyan.meow_count(), 55_usize); - kitty.speak(vec!("meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string())); + kitty.speak(vec!["meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()]); assert_eq!(kitty.meow_count(), 1004_usize); } diff --git a/src/test/run-pass/class-poly-methods.rs b/src/test/run-pass/class-poly-methods.rs index 2528ff5128f..5da858e3c40 100644 --- a/src/test/run-pass/class-poly-methods.rs +++ b/src/test/run-pass/class-poly-methods.rs @@ -33,12 +33,12 @@ fn cat<U>(in_x : usize, in_y : isize, in_info: Vec<U> ) -> cat<U> { } pub fn main() { - let mut nyan : cat<isize> = cat::<isize>(52, 99, vec!(9)); - let mut kitty = cat(1000, 2, vec!("tabby".to_string())); + let mut nyan : cat<isize> = cat::<isize>(52, 99, vec![9]); + let mut kitty = cat(1000, 2, vec!["tabby".to_string()]); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); - nyan.speak(vec!(1,2,3)); + nyan.speak(vec![1,2,3]); assert_eq!(nyan.meow_count(), 55); - kitty.speak(vec!("meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string())); + kitty.speak(vec!["meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()]); assert_eq!(kitty.meow_count(), 1004); } diff --git a/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs b/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs index 25d3eb3bbe2..c401b529c30 100644 --- a/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs +++ b/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs @@ -41,7 +41,7 @@ fn do_it(x: &[usize]) -> Foo { panic!() } -fn get_bar(x: usize) -> Vec<usize> { vec!(x * 2) } +fn get_bar(x: usize) -> Vec<usize> { vec![x * 2] } pub fn fails() { let x = 2; diff --git a/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs b/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs index 4e116ae1466..e86f20694e1 100644 --- a/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs +++ b/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs @@ -19,7 +19,7 @@ fn bip(v: &[usize]) -> Vec<usize> { } pub fn main() { - let mut the_vec = vec!(1, 2, 3, 100); + let mut the_vec = vec![1, 2, 3, 100]; assert_eq!(the_vec.clone(), bar(&mut the_vec)); assert_eq!(the_vec.clone(), bip(&the_vec)); } diff --git a/src/test/run-pass/coerce-reborrow-mut-vec-arg.rs b/src/test/run-pass/coerce-reborrow-mut-vec-arg.rs index ce0bc33905f..ca4ee4a97d5 100644 --- a/src/test/run-pass/coerce-reborrow-mut-vec-arg.rs +++ b/src/test/run-pass/coerce-reborrow-mut-vec-arg.rs @@ -21,7 +21,7 @@ fn bar(v: &mut [usize]) { } pub fn main() { - let mut the_vec = vec!(1, 2, 3, 100); + let mut the_vec = vec![1, 2, 3, 100]; bar(&mut the_vec); assert_eq!(the_vec, [100, 3, 2, 1]); } diff --git a/src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs b/src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs index 066b33e007b..f35735adbcf 100644 --- a/src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs +++ b/src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs @@ -17,7 +17,7 @@ fn bar(v: &mut [usize]) { } pub fn main() { - let mut the_vec = vec!(1, 2, 3, 100); + let mut the_vec = vec![1, 2, 3, 100]; bar(&mut the_vec); assert_eq!(the_vec, [100, 3, 2, 1]); } diff --git a/src/test/run-pass/deriving-in-macro.rs b/src/test/run-pass/deriving-in-macro.rs index b23075e6d0a..adc3e3efd70 100644 --- a/src/test/run-pass/deriving-in-macro.rs +++ b/src/test/run-pass/deriving-in-macro.rs @@ -19,6 +19,6 @@ macro_rules! define_vec { ) } -define_vec!(); +define_vec![]; pub fn main() {} diff --git a/src/test/run-pass/drop-with-type-ascription-2.rs b/src/test/run-pass/drop-with-type-ascription-2.rs index cb3712dea32..53005ea5291 100644 --- a/src/test/run-pass/drop-with-type-ascription-2.rs +++ b/src/test/run-pass/drop-with-type-ascription-2.rs @@ -12,7 +12,7 @@ #![feature(collections)] fn main() { - let args = vec!("foobie", "asdf::asdf"); + let args = vec!["foobie", "asdf::asdf"]; let arr: Vec<&str> = args[1].split("::").collect(); assert_eq!(arr[0], "asdf"); assert_eq!(arr[0], "asdf"); diff --git a/src/test/run-pass/expr-fn.rs b/src/test/run-pass/expr-fn.rs index aeca388d317..cc9a2e60dec 100644 --- a/src/test/run-pass/expr-fn.rs +++ b/src/test/run-pass/expr-fn.rs @@ -16,7 +16,7 @@ fn test_int() { } fn test_vec() { - fn f() -> Vec<isize> { vec!(10, 11) } + fn f() -> Vec<isize> { vec![10, 11] } let vect = f(); assert_eq!(vect[1], 11); } diff --git a/src/test/run-pass/expr-match-panic.rs b/src/test/run-pass/expr-match-panic.rs index 89dc7b09c7b..1a6466048d9 100644 --- a/src/test/run-pass/expr-match-panic.rs +++ b/src/test/run-pass/expr-match-panic.rs @@ -16,7 +16,7 @@ fn test_simple() { } fn test_box() { - let r = match true { true => { vec!(10) } false => { panic!() } }; + let r = match true { true => { vec![10] } false => { panic!() } }; assert_eq!(r[0], 10); } diff --git a/src/test/run-pass/for-destruct.rs b/src/test/run-pass/for-destruct.rs index 963d34a2d2f..ba78ff4d539 100644 --- a/src/test/run-pass/for-destruct.rs +++ b/src/test/run-pass/for-destruct.rs @@ -12,7 +12,7 @@ struct Pair { x: isize, y: isize } pub fn main() { - for elt in &(vec!(Pair {x: 10, y: 20}, Pair {x: 30, y: 0})) { + 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/foreach-nested.rs b/src/test/run-pass/foreach-nested.rs index 60068185f5a..2c4d0cc7648 100644 --- a/src/test/run-pass/foreach-nested.rs +++ b/src/test/run-pass/foreach-nested.rs @@ -13,7 +13,7 @@ fn two<F>(mut it: F) where F: FnMut(isize) { it(0); it(1); } pub fn main() { - let mut a: Vec<isize> = vec!(-1, -1, -1, -1); + let mut a: Vec<isize> = vec![-1, -1, -1, -1]; let mut p: isize = 0; two(|i| { two(|j| { a[p as usize] = 10 * i + j; p += 1; }) diff --git a/src/test/run-pass/generic-ivec-leak.rs b/src/test/run-pass/generic-ivec-leak.rs index eb0546063f7..d439c623801 100644 --- a/src/test/run-pass/generic-ivec-leak.rs +++ b/src/test/run-pass/generic-ivec-leak.rs @@ -10,4 +10,4 @@ enum wrapper<T> { wrapped(T), } -pub fn main() { let _w = wrapper::wrapped(vec!(1, 2, 3, 4, 5)); } +pub fn main() { let _w = wrapper::wrapped(vec![1, 2, 3, 4, 5]); } diff --git a/src/test/run-pass/generic-static-methods.rs b/src/test/run-pass/generic-static-methods.rs index 7a496ebf8ce..ad501ec7e9b 100644 --- a/src/test/run-pass/generic-static-methods.rs +++ b/src/test/run-pass/generic-static-methods.rs @@ -25,5 +25,5 @@ impl<T> vec_utils<T> for Vec<T> { } pub fn main() { - assert_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), [2,3,4]); + assert_eq!(vec_utils::map_(&vec![1,2,3], |&x| x+1), [2,3,4]); } diff --git a/src/test/run-pass/getopts_ref.rs b/src/test/run-pass/getopts_ref.rs index c9595d09e21..90726c21fac 100644 --- a/src/test/run-pass/getopts_ref.rs +++ b/src/test/run-pass/getopts_ref.rs @@ -17,7 +17,7 @@ use getopts::{optopt, getopts}; pub fn main() { let args = Vec::new(); - let opts = vec!(optopt("b", "", "something", "SMTHNG")); + let opts = vec![optopt("b", "", "something", "SMTHNG")]; match getopts(&args, &opts) { Ok(ref m) => diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index 8efc4cb1b17..2306fa9afa2 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -99,5 +99,5 @@ mod map_reduce { pub fn main() { map_reduce::map_reduce( - vec!("../src/test/run-pass/hashmap-memory.rs".to_string())); + vec!["../src/test/run-pass/hashmap-memory.rs".to_string()]); } diff --git a/src/test/run-pass/html-literals.rs b/src/test/run-pass/html-literals.rs index a9cfe7a3802..1e1fde4d1e2 100644 --- a/src/test/run-pass/html-literals.rs +++ b/src/test/run-pass/html-literals.rs @@ -40,7 +40,7 @@ macro_rules! parse_node { parse_node!( [$(: $tags ($(:$tag_nodes),*))*]; [$(:$head_nodes,)* :tag(stringify!($head).to_string(), - vec!($($nodes),*))]; + vec![$($nodes),*])]; $($rest)* ) ); diff --git a/src/test/run-pass/ifmt.rs b/src/test/run-pass/ifmt.rs index c9af2b190b2..2a7a593d268 100644 --- a/src/test/run-pass/ifmt.rs +++ b/src/test/run-pass/ifmt.rs @@ -237,7 +237,7 @@ fn test_write() { // can do with them just yet (to test the output) fn test_print() { print!("hi"); - print!("{:?}", vec!(0u8)); + print!("{:?}", vec![0u8]); println!("hello"); println!("this is a {}", "test"); println!("{foo}", foo="bar"); diff --git a/src/test/run-pass/issue-13204.rs b/src/test/run-pass/issue-13204.rs index 36f606e5d73..13e8fe0e964 100644 --- a/src/test/run-pass/issue-13204.rs +++ b/src/test/run-pass/issue-13204.rs @@ -28,6 +28,6 @@ impl Foo for Baz { fn main() { let x = Baz; - let y = vec!((), (), ()); + let y = vec![(), (), ()]; assert_eq!(x.bar(y.iter()), 3); } diff --git a/src/test/run-pass/issue-14936.rs b/src/test/run-pass/issue-14936.rs index 428d4e4dbb1..8a628b73c00 100644 --- a/src/test/run-pass/issue-14936.rs +++ b/src/test/run-pass/issue-14936.rs @@ -24,7 +24,7 @@ macro_rules! demo { let mut x: isize = 0; let y: isize = 1; - let mut history: History = vec!(); + let mut history: History = vec![]; unsafe { asm!("mov ($1), $0" : $output_constraint (*wrap(&mut x, "out", &mut history)) diff --git a/src/test/run-pass/issue-15080.rs b/src/test/run-pass/issue-15080.rs index cee0caeb465..14e00378846 100644 --- a/src/test/run-pass/issue-15080.rs +++ b/src/test/run-pass/issue-15080.rs @@ -14,7 +14,7 @@ fn main() { let mut x: &[_] = &[1, 2, 3, 4]; - let mut result = vec!(); + let mut result = vec![]; loop { x = match *x { [1, n, 3, ref rest..] => { diff --git a/src/test/run-pass/issue-15189.rs b/src/test/run-pass/issue-15189.rs index 35faa5789a9..54b96d66307 100644 --- a/src/test/run-pass/issue-15189.rs +++ b/src/test/run-pass/issue-15189.rs @@ -13,7 +13,7 @@ macro_rules! third { } fn main() { - let x = vec!(10_usize,11_usize,12_usize,13_usize); + let x = vec![10_usize,11_usize,12_usize,13_usize]; let t = third!(x); assert_eq!(t,12_usize); } diff --git a/src/test/run-pass/issue-15734.rs b/src/test/run-pass/issue-15734.rs index 66b0aeeb988..daf14b4c2ff 100644 --- a/src/test/run-pass/issue-15734.rs +++ b/src/test/run-pass/issue-15734.rs @@ -54,7 +54,7 @@ impl<T, M: Index<(usize, usize), Output=T>> Index<usize> for Row<M> { } fn main() { - let m = Mat::new(vec!(1, 2, 3, 4, 5, 6), 3); + let m = Mat::new(vec![1, 2, 3, 4, 5, 6], 3); let r = m.row(1); assert_eq!(r.index(2), &6); diff --git a/src/test/run-pass/issue-2631-b.rs b/src/test/run-pass/issue-2631-b.rs index 365b594c99e..913b07613e0 100644 --- a/src/test/run-pass/issue-2631-b.rs +++ b/src/test/run-pass/issue-2631-b.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; use std::rc::Rc; pub fn main() { - let v = vec!(Rc::new("hi".to_string())); + let v = vec![Rc::new("hi".to_string())]; let mut m: req::header_map = HashMap::new(); m.insert("METHOD".to_string(), Rc::new(RefCell::new(v))); request::<isize>(&m); diff --git a/src/test/run-pass/issue-2723-b.rs b/src/test/run-pass/issue-2723-b.rs index bab7b0d24db..a6ba957a1b1 100644 --- a/src/test/run-pass/issue-2723-b.rs +++ b/src/test/run-pass/issue-2723-b.rs @@ -15,6 +15,6 @@ use issue_2723_a::f; pub fn main() { unsafe { - f(vec!(2)); + f(vec![2]); } } diff --git a/src/test/run-pass/issue-28936.rs b/src/test/run-pass/issue-28936.rs index 2a932cd7756..992fbdce268 100644 --- a/src/test/run-pass/issue-28936.rs +++ b/src/test/run-pass/issue-28936.rs @@ -23,7 +23,7 @@ pub fn parse_stream<T: Iterator<Item=i32>, U, F>( where F: Fn(&mut StreamParser<T>) -> U { panic!(); } pub fn thing(session: &mut Session) { - let mut stream = vec!(1, 2, 3).into_iter(); + let mut stream = vec![1, 2, 3].into_iter(); let _b = parse_stream(session, stream.by_ref(), diff --git a/src/test/run-pass/issue-2989.rs b/src/test/run-pass/issue-2989.rs index 8b6eb12f102..a4342f33402 100644 --- a/src/test/run-pass/issue-2989.rs +++ b/src/test/run-pass/issue-2989.rs @@ -32,8 +32,8 @@ fn to_bools(bitv: Storage) -> Vec<bool> { struct Storage { storage: Vec<u64> } pub fn main() { - let bools = vec!(false, false, true, false, false, true, true, false); - let bools2 = to_bools(Storage{storage: vec!(0b01100100)}); + let bools = vec![false, false, true, false, false, true, true, false]; + let bools2 = to_bools(Storage{storage: vec![0b01100100]}); for i in 0..8 { println!("{} => {} vs {}", i, bools[i], bools2[i]); diff --git a/src/test/run-pass/issue-3389.rs b/src/test/run-pass/issue-3389.rs index 26558bdd30c..70e3484a0c5 100644 --- a/src/test/run-pass/issue-3389.rs +++ b/src/test/run-pass/issue-3389.rs @@ -25,8 +25,8 @@ pub fn main() { content: Vec::new(), children: Vec::new() }; - let v = vec!("123".to_string(), "abc".to_string()); - node.content = vec!("123".to_string(), "abc".to_string()); + let v = vec!["123".to_string(), "abc".to_string()]; + node.content = vec!["123".to_string(), "abc".to_string()]; print_str_vector(v); print_str_vector(node.content.clone()); diff --git a/src/test/run-pass/issue-37291/auxiliary/lib.rs b/src/test/run-pass/issue-37291/auxiliary/lib.rs new file mode 100644 index 00000000000..67cdea807be --- /dev/null +++ b/src/test/run-pass/issue-37291/auxiliary/lib.rs @@ -0,0 +1,52 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-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"] + +use std::ops::Mul; + +pub trait A {} +pub trait B { + type AT: A; +} +pub trait C { + type BT: B; +} + +pub struct AV; +impl A for AV {} + +pub struct BV; +impl B for BV { + type AT = AV; +} + +pub struct CV; +impl C for CV { + type BT = BV; +} + +pub struct WrapperB<T>(pub T); +pub struct WrapperC<T>(pub T); + +impl<C1> Mul<WrapperB<<C1::BT as B>::AT>> for WrapperC<C1> + where C1: C +{ + type Output = u8; + fn mul(self, _: WrapperB<<C1::BT as B>::AT>) -> Self::Output { + loop {} + } +} +impl<C1> Mul<WrapperC<C1>> for WrapperC<C1> { + type Output = u8; + fn mul(self, _: WrapperC<C1>) -> Self::Output { + loop {} + } +} diff --git a/src/test/run-pass/issue-37291/main.rs b/src/test/run-pass/issue-37291/main.rs new file mode 100644 index 00000000000..2461f7485f2 --- /dev/null +++ b/src/test/run-pass/issue-37291/main.rs @@ -0,0 +1,29 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// aux-build:lib.rs + +// Regression test for #37291. The problem was that the starting +// environment for a specialization check was not including the +// where-clauses from the impl when attempting to normalize the impl's +// trait-ref, so things like `<C as Foo>::Item` could not resolve, +// since the `C: Foo` trait bound was not included in the environment. + +extern crate lib; + +use lib::{CV, WrapperB, WrapperC}; + +fn main() { + let a = WrapperC(CV); + let b = WrapperC(CV); + if false { + let _ = a * b; + } +} diff --git a/src/test/run-pass/issue-6153.rs b/src/test/run-pass/issue-6153.rs index 16e7060f4b9..1b16418ac42 100644 --- a/src/test/run-pass/issue-6153.rs +++ b/src/test/run-pass/issue-6153.rs @@ -11,7 +11,7 @@ fn swap<F>(f: F) -> Vec<isize> where F: FnOnce(Vec<isize>) -> Vec<isize> { - let x = vec!(1, 2, 3); + let x = vec![1, 2, 3]; f(x) } diff --git a/src/test/run-pass/ivec-pass-by-value.rs b/src/test/run-pass/ivec-pass-by-value.rs index 5b40105a979..e3b42e60645 100644 --- a/src/test/run-pass/ivec-pass-by-value.rs +++ b/src/test/run-pass/ivec-pass-by-value.rs @@ -9,4 +9,4 @@ // except according to those terms. fn f(_a: Vec<isize> ) { } -pub fn main() { f(vec!(1, 2, 3, 4, 5)); } +pub fn main() { f(vec![1, 2, 3, 4, 5]); } diff --git a/src/test/run-pass/ivec-tag.rs b/src/test/run-pass/ivec-tag.rs index b8238774bc1..a511db8e939 100644 --- a/src/test/run-pass/ivec-tag.rs +++ b/src/test/run-pass/ivec-tag.rs @@ -17,8 +17,8 @@ use std::sync::mpsc::{channel, Sender}; fn producer(tx: &Sender<Vec<u8>>) { tx.send( - vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, - 13)).unwrap(); + vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13]).unwrap(); } pub fn main() { diff --git a/src/test/run-pass/lambda-infer-unresolved.rs b/src/test/run-pass/lambda-infer-unresolved.rs index fca700f6e4a..5109c6fc777 100644 --- a/src/test/run-pass/lambda-infer-unresolved.rs +++ b/src/test/run-pass/lambda-infer-unresolved.rs @@ -15,7 +15,7 @@ struct Refs { refs: Vec<isize> , n: isize } pub fn main() { - let mut e = Refs{refs: vec!(), n: 0}; + let mut e = Refs{refs: vec![], n: 0}; let _f = || println!("{}", e.n); let x: &[isize] = &e.refs; assert_eq!(x.len(), 0); diff --git a/src/test/run-pass/linear-for-loop.rs b/src/test/run-pass/linear-for-loop.rs index 3da2fc8ceac..fc6d435b034 100644 --- a/src/test/run-pass/linear-for-loop.rs +++ b/src/test/run-pass/linear-for-loop.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let x = vec!(1, 2, 3); + let x = vec![1, 2, 3]; let mut y = 0; for i in &x { println!("{}", *i); y += *i; } println!("{}", y); diff --git a/src/test/run-pass/log-poly.rs b/src/test/run-pass/log-poly.rs index d8a69177caf..b54b4692a41 100644 --- a/src/test/run-pass/log-poly.rs +++ b/src/test/run-pass/log-poly.rs @@ -17,5 +17,5 @@ pub fn main() { println!("{:?}", 1); println!("{:?}", 2.0f64); println!("{:?}", Numbers::Three); - println!("{:?}", vec!(4)); + println!("{:?}", vec![4]); } diff --git a/src/test/run-pass/loop-scope.rs b/src/test/run-pass/loop-scope.rs index 0c1e7916cdb..6916bfb8c61 100644 --- a/src/test/run-pass/loop-scope.rs +++ b/src/test/run-pass/loop-scope.rs @@ -10,7 +10,7 @@ pub fn main() { - let x = vec!(10, 20, 30); + let x = vec![10, 20, 30]; let mut sum = 0; for x in &x { sum += *x; } assert_eq!(sum, 60); diff --git a/src/test/run-pass/match-vec-rvalue.rs b/src/test/run-pass/match-vec-rvalue.rs index a10f9b1d7d6..3d221927b96 100644 --- a/src/test/run-pass/match-vec-rvalue.rs +++ b/src/test/run-pass/match-vec-rvalue.rs @@ -13,7 +13,7 @@ pub fn main() { - match vec!(1, 2, 3) { + match vec![1, 2, 3] { x => { assert_eq!(x.len(), 3); assert_eq!(x[0], 1); diff --git a/src/test/run-pass/monad.rs b/src/test/run-pass/monad.rs index b28e5ec64de..211827f9222 100644 --- a/src/test/run-pass/monad.rs +++ b/src/test/run-pass/monad.rs @@ -45,9 +45,9 @@ fn transform(x: Option<isize>) -> Option<String> { pub fn main() { assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); - assert_eq!((vec!("hi".to_string())) - .bind(|x| vec!(x.clone(), format!("{}!", x)) ) - .bind(|x| vec!(x.clone(), format!("{}?", x)) ), + assert_eq!((vec!["hi".to_string()]) + .bind(|x| vec![x.clone(), format!("{}!", x)] ) + .bind(|x| vec![x.clone(), format!("{}?", x)] ), ["hi".to_string(), "hi?".to_string(), "hi!".to_string(), diff --git a/src/test/run-pass/move-arg-2-unique.rs b/src/test/run-pass/move-arg-2-unique.rs index bed339e1586..0ff5a66adc2 100644 --- a/src/test/run-pass/move-arg-2-unique.rs +++ b/src/test/run-pass/move-arg-2-unique.rs @@ -15,10 +15,10 @@ fn test(foo: Box<Vec<isize>> ) { assert_eq!((*foo)[0], 10); } pub fn main() { - let x = box vec!(10); + let x = box vec![10]; // Test forgetting a local by move-in test(x); // Test forgetting a temporary by move-in. - test(box vec!(10)); + test(box vec![10]); } diff --git a/src/test/run-pass/move-arg-2.rs b/src/test/run-pass/move-arg-2.rs index a6a26ab3578..8de487bc363 100644 --- a/src/test/run-pass/move-arg-2.rs +++ b/src/test/run-pass/move-arg-2.rs @@ -15,10 +15,10 @@ fn test(foo: Box<Vec<isize>>) { assert_eq!((*foo)[0], 10); } pub fn main() { - let x = box vec!(10); + let x = box vec![10]; // Test forgetting a local by move-in test(x); // Test forgetting a temporary by move-in. - test(box vec!(10)); + test(box vec![10]); } diff --git a/src/test/run-pass/newtype-polymorphic.rs b/src/test/run-pass/newtype-polymorphic.rs index 91599608cee..e7da8d7bf93 100644 --- a/src/test/run-pass/newtype-polymorphic.rs +++ b/src/test/run-pass/newtype-polymorphic.rs @@ -24,7 +24,7 @@ fn myvec_elt<X>(mv: myvec<X>) -> X { } pub fn main() { - let mv = myvec(vec!(1, 2, 3)); + let mv = myvec(vec![1, 2, 3]); let mv_clone = mv.clone(); let mv_clone = myvec_deref(mv_clone); assert_eq!(mv_clone[1], 2); diff --git a/src/test/run-pass/nullable-pointer-iotareduction.rs b/src/test/run-pass/nullable-pointer-iotareduction.rs index dffdcfe0af5..7e8d082a286 100644 --- a/src/test/run-pass/nullable-pointer-iotareduction.rs +++ b/src/test/run-pass/nullable-pointer-iotareduction.rs @@ -76,7 +76,7 @@ pub fn main() { check_type!(&17, &isize); check_type!(box 18, Box<isize>); check_type!("foo".to_string(), String); - check_type!(vec!(20, 22), Vec<isize>); + check_type!(vec![20, 22], Vec<isize>); check_type!(main, fn(), |pthing| { assert_eq!(main as fn(), *pthing as fn()) }); diff --git a/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs b/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs index 176f67fd3a1..768f126e4ed 100644 --- a/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs +++ b/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs @@ -32,11 +32,11 @@ impl FooTrait for BarStruct { } pub fn main() { - let foos: Vec<Box<FooTrait>> = vec!( + let foos: Vec<Box<FooTrait>> = vec![ box BarStruct{ x: 0 } as Box<FooTrait>, box BarStruct{ x: 1 } as Box<FooTrait>, box BarStruct{ x: 2 } as Box<FooTrait> - ); + ]; for i in 0..foos.len() { assert_eq!(i, foos[i].foo()); diff --git a/src/test/run-pass/overloaded-deref.rs b/src/test/run-pass/overloaded-deref.rs index 8541c1c0a89..e2ca880719a 100644 --- a/src/test/run-pass/overloaded-deref.rs +++ b/src/test/run-pass/overloaded-deref.rs @@ -45,7 +45,7 @@ pub fn main() { (*(*p).borrow_mut()).y += 3; assert_eq!(*(*p).borrow(), Point {x: 3, y: 5}); - let v = Rc::new(RefCell::new(vec!(1, 2, 3))); + let v = Rc::new(RefCell::new(vec![1, 2, 3])); (*(*v).borrow_mut())[0] = 3; (*(*v).borrow_mut())[1] += 3; assert_eq!(((*(*v).borrow())[0], diff --git a/src/test/run-pass/rcvr-borrowed-to-slice.rs b/src/test/run-pass/rcvr-borrowed-to-slice.rs index 1ec16747181..efa73ad92ce 100644 --- a/src/test/run-pass/rcvr-borrowed-to-slice.rs +++ b/src/test/run-pass/rcvr-borrowed-to-slice.rs @@ -23,17 +23,17 @@ impl<'a> sum for &'a [isize] { fn call_sum(x: &[isize]) -> isize { x.sum_() } pub fn main() { - let x = vec!(1, 2, 3); + let x = vec![1, 2, 3]; let y = call_sum(&x); println!("y=={}", y); assert_eq!(y, 6); - let x = vec!(1, 2, 3); + let x = vec![1, 2, 3]; let y = x.sum_(); println!("y=={}", y); assert_eq!(y, 6); - let x = vec!(1, 2, 3); + let x = vec![1, 2, 3]; let y = x.sum_(); println!("y=={}", y); assert_eq!(y, 6); diff --git a/src/test/run-pass/regions-borrow-evec-uniq.rs b/src/test/run-pass/regions-borrow-evec-uniq.rs index ec1f4eda28c..e61a8d14775 100644 --- a/src/test/run-pass/regions-borrow-evec-uniq.rs +++ b/src/test/run-pass/regions-borrow-evec-uniq.rs @@ -15,11 +15,11 @@ fn foo(x: &[isize]) -> isize { } pub fn main() { - let p = vec!(1,2,3,4,5); + let p = vec![1,2,3,4,5]; let r = foo(&p); assert_eq!(r, 1); - let p = vec!(5,4,3,2,1); + let p = vec![5,4,3,2,1]; let r = foo(&p); assert_eq!(r, 5); } diff --git a/src/test/run-pass/regions-dependent-addr-of.rs b/src/test/run-pass/regions-dependent-addr-of.rs index a6a179c432c..e9a3e16438f 100644 --- a/src/test/run-pass/regions-dependent-addr-of.rs +++ b/src/test/run-pass/regions-dependent-addr-of.rs @@ -90,7 +90,7 @@ fn get_v5_ref(a: &A, _i: usize) -> &isize { pub fn main() { let a = A {value: B {v1: 22, v2: [23, 24, 25], - v3: vec!(26, 27, 28), + v3: vec![26, 27, 28], v4: C { f: 29 }, v5: box C { f: 30 }, v6: Some(C { f: 31 })}}; diff --git a/src/test/run-pass/regions-dependent-autoslice.rs b/src/test/run-pass/regions-dependent-autoslice.rs index 7183937fe80..cd140f7aa59 100644 --- a/src/test/run-pass/regions-dependent-autoslice.rs +++ b/src/test/run-pass/regions-dependent-autoslice.rs @@ -18,6 +18,6 @@ fn both<'r>(v: &'r [usize]) -> &'r [usize] { } pub fn main() { - let v = vec!(1,2,3); + let v = vec![1,2,3]; both(&v); } diff --git a/src/test/run-pass/regions-infer-borrow-scope-view.rs b/src/test/run-pass/regions-infer-borrow-scope-view.rs index f9ba8e82ef7..262e936826e 100644 --- a/src/test/run-pass/regions-infer-borrow-scope-view.rs +++ b/src/test/run-pass/regions-infer-borrow-scope-view.rs @@ -13,7 +13,7 @@ fn view<T>(x: &[T]) -> &[T] {x} pub fn main() { - let v = vec!(1, 2, 3); + let v = vec![1, 2, 3]; let x = view(&v); let y = view(x); assert!((v[0] == x[0]) && (v[0] == y[0])); diff --git a/src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs b/src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs index 465f43e36b9..8eee54b3fec 100644 --- a/src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs +++ b/src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs @@ -63,7 +63,7 @@ impl<'a,'tcx> Foo<'a,'tcx> { } fn main() { - let v = vec!(); + let v = vec![]; let cx = Ctxt { x: &v }; let mut foo = Foo { cx: &cx }; assert_eq!(foo.bother(), 22); // just so the code is not dead, basically diff --git a/src/test/run-pass/seq-compare.rs b/src/test/run-pass/seq-compare.rs index f1a21d90ab2..43612f52977 100644 --- a/src/test/run-pass/seq-compare.rs +++ b/src/test/run-pass/seq-compare.rs @@ -14,13 +14,13 @@ pub fn main() { assert!(("hello".to_string() < "hellr".to_string())); assert!(("hello ".to_string() > "hello".to_string())); assert!(("hello".to_string() != "there".to_string())); - assert!((vec!(1, 2, 3, 4) > vec!(1, 2, 3))); - assert!((vec!(1, 2, 3) < vec!(1, 2, 3, 4))); - assert!((vec!(1, 2, 4, 4) > vec!(1, 2, 3, 4))); - assert!((vec!(1, 2, 3, 4) < vec!(1, 2, 4, 4))); - assert!((vec!(1, 2, 3) <= vec!(1, 2, 3))); - assert!((vec!(1, 2, 3) <= vec!(1, 2, 3, 3))); - assert!((vec!(1, 2, 3, 4) > vec!(1, 2, 3))); - assert_eq!(vec!(1, 2, 3), vec!(1, 2, 3)); - assert!((vec!(1, 2, 3) != vec!(1, 1, 3))); + assert!((vec![1, 2, 3, 4] > vec![1, 2, 3])); + assert!((vec![1, 2, 3] < vec![1, 2, 3, 4])); + assert!((vec![1, 2, 4, 4] > vec![1, 2, 3, 4])); + assert!((vec![1, 2, 3, 4] < vec![1, 2, 4, 4])); + assert!((vec![1, 2, 3] <= vec![1, 2, 3])); + assert!((vec![1, 2, 3] <= vec![1, 2, 3, 3])); + assert!((vec![1, 2, 3, 4] > vec![1, 2, 3])); + assert_eq!(vec![1, 2, 3], vec![1, 2, 3]); + assert!((vec![1, 2, 3] != vec![1, 1, 3])); } diff --git a/src/test/run-pass/size-and-align.rs b/src/test/run-pass/size-and-align.rs index 007ce52d7c4..13d55e0172e 100644 --- a/src/test/run-pass/size-and-align.rs +++ b/src/test/run-pass/size-and-align.rs @@ -22,6 +22,6 @@ fn uhoh<T>(v: Vec<clam<T>> ) { } pub fn main() { - let v: Vec<clam<isize>> = vec!(clam::b::<isize>, clam::b::<isize>, clam::a::<isize>(42, 17)); + let v: Vec<clam<isize>> = vec![clam::b::<isize>, clam::b::<isize>, clam::a::<isize>(42, 17)]; uhoh::<isize>(v); } diff --git a/src/test/run-pass/static-impl.rs b/src/test/run-pass/static-impl.rs index 84bb1b871b9..89fd83ced4c 100644 --- a/src/test/run-pass/static-impl.rs +++ b/src/test/run-pass/static-impl.rs @@ -62,10 +62,10 @@ pub fn main() { assert_eq!(10_usize.plus(), 30); assert_eq!(("hi".to_string()).plus(), 200); - assert_eq!((vec!(1)).length_().str(), "1".to_string()); - let vect = vec!(3, 4).map_(|a| *a + 4); + assert_eq!((vec![1]).length_().str(), "1".to_string()); + let vect = vec![3, 4].map_(|a| *a + 4); assert_eq!(vect[0], 7); - let vect = (vec!(3, 4)).map_::<usize, _>(|a| *a as usize + 4_usize); + let vect = (vec![3, 4]).map_::<usize, _>(|a| *a as usize + 4_usize); assert_eq!(vect[0], 7_usize); let mut x = 0_usize; 10_usize.multi(|_n| x += 2_usize ); diff --git a/src/test/run-pass/swap-2.rs b/src/test/run-pass/swap-2.rs index 3dbd7f1a601..4601b7d7cf5 100644 --- a/src/test/run-pass/swap-2.rs +++ b/src/test/run-pass/swap-2.rs @@ -12,7 +12,7 @@ use std::mem::swap; pub fn main() { - let mut a: Vec<isize> = vec!(0, 1, 2, 3, 4, 5, 6); + let mut a: Vec<isize> = vec![0, 1, 2, 3, 4, 5, 6]; a.swap(2, 4); assert_eq!(a[2], 4); assert_eq!(a[4], 2); diff --git a/src/test/run-pass/task-comm-16.rs b/src/test/run-pass/task-comm-16.rs index c6d8f3c0d9b..0caf21ead39 100644 --- a/src/test/run-pass/task-comm-16.rs +++ b/src/test/run-pass/task-comm-16.rs @@ -27,7 +27,7 @@ fn test_rec() { fn test_vec() { let (tx, rx) = channel(); - let v0: Vec<isize> = vec!(0, 1, 2); + let v0: Vec<isize> = vec![0, 1, 2]; tx.send(v0).unwrap(); let v1 = rx.recv().unwrap(); assert_eq!(v1[0], 0); diff --git a/src/test/run-pass/trait-bounds-in-arc.rs b/src/test/run-pass/trait-bounds-in-arc.rs index f7fd86c9570..9877dffe9df 100644 --- a/src/test/run-pass/trait-bounds-in-arc.rs +++ b/src/test/run-pass/trait-bounds-in-arc.rs @@ -75,10 +75,10 @@ pub fn main() { swim_speed: 998, name: "alec_guinness".to_string(), }; - let arc = Arc::new(vec!(box catte as Box<Pet+Sync+Send>, + let arc = Arc::new(vec![box catte as Box<Pet+Sync+Send>, box dogge1 as Box<Pet+Sync+Send>, box fishe as Box<Pet+Sync+Send>, - box dogge2 as Box<Pet+Sync+Send>)); + box dogge2 as Box<Pet+Sync+Send>]); let (tx1, rx1) = channel(); let arc1 = arc.clone(); let t1 = thread::spawn(move|| { check_legs(arc1); tx1.send(()); }); diff --git a/src/test/run-pass/trait-generic.rs b/src/test/run-pass/trait-generic.rs index 49982366291..eadda5dfe29 100644 --- a/src/test/run-pass/trait-generic.rs +++ b/src/test/run-pass/trait-generic.rs @@ -45,9 +45,9 @@ fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> { } pub fn main() { - assert_eq!(foo(vec!(1)), ["hi".to_string()]); - assert_eq!(bar::<isize, Vec<isize> >(vec!(4, 5)), ["4".to_string(), "5".to_string()]); - assert_eq!(bar::<String, Vec<String> >(vec!("x".to_string(), "y".to_string())), + assert_eq!(foo(vec![1]), ["hi".to_string()]); + assert_eq!(bar::<isize, Vec<isize> >(vec![4, 5]), ["4".to_string(), "5".to_string()]); + assert_eq!(bar::<String, Vec<String> >(vec!["x".to_string(), "y".to_string()]), ["x".to_string(), "y".to_string()]); - assert_eq!(bar::<(), Vec<()>>(vec!(())), ["()".to_string()]); + assert_eq!(bar::<(), Vec<()>>(vec![()]), ["()".to_string()]); } diff --git a/src/test/run-pass/trait-to-str.rs b/src/test/run-pass/trait-to-str.rs index f5af05d872b..9671e31d7e4 100644 --- a/src/test/run-pass/trait-to-str.rs +++ b/src/test/run-pass/trait-to-str.rs @@ -30,15 +30,15 @@ impl<T:to_str> to_str for Vec<T> { pub fn main() { assert_eq!(1.to_string_(), "1".to_string()); - assert_eq!((vec!(2, 3, 4)).to_string_(), "[2, 3, 4]".to_string()); + assert_eq!((vec![2, 3, 4]).to_string_(), "[2, 3, 4]".to_string()); fn indirect<T:to_str>(x: T) -> String { format!("{}!", x.to_string_()) } - assert_eq!(indirect(vec!(10, 20)), "[10, 20]!".to_string()); + assert_eq!(indirect(vec![10, 20]), "[10, 20]!".to_string()); fn indirect2<T:to_str>(x: T) -> String { indirect(x) } - assert_eq!(indirect2(vec!(1)), "[1]!".to_string()); + assert_eq!(indirect2(vec![1]), "[1]!".to_string()); } 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 0b85916d224..300a0ee63f8 100644 --- a/src/test/run-pass/unboxed-closures-counter-not-moved.rs +++ b/src/test/run-pass/unboxed-closures-counter-not-moved.rs @@ -15,7 +15,7 @@ fn call<F>(f: F) where F : FnOnce() { } fn main() { - let y = vec!(format!("Hello"), format!("World")); + let y = vec![format!("Hello"), format!("World")]; let mut counter = 22_u32; call(|| { 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 99663646254..b9a16535c42 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 @@ -16,8 +16,8 @@ fn call<F>(f: F) where F : FnOnce() { } fn main() { - let mut x = vec!(format!("Hello")); - let y = vec!(format!("World")); + let mut x = vec![format!("Hello")]; + let y = vec![format!("World")]; call(|| { // Here: `x` must be captured with a mutable reference in // order for us to append on it, and `y` must be captured by diff --git a/src/test/run-pass/unique-autoderef-index.rs b/src/test/run-pass/unique-autoderef-index.rs index c68ff1f0612..1ef61008b3c 100644 --- a/src/test/run-pass/unique-autoderef-index.rs +++ b/src/test/run-pass/unique-autoderef-index.rs @@ -13,6 +13,6 @@ #![feature(box_syntax)] pub fn main() { - let i: Box<_> = box vec!(100); + let i: Box<_> = box vec![100]; assert_eq!((*i)[0], 100); } diff --git a/src/test/run-pass/unique-create.rs b/src/test/run-pass/unique-create.rs index 8469ae70200..6d638bbf562 100644 --- a/src/test/run-pass/unique-create.rs +++ b/src/test/run-pass/unique-create.rs @@ -18,5 +18,5 @@ pub fn main() { } fn vec() { - vec!(0); + vec![0]; } diff --git a/src/test/run-pass/unique-drop-complex.rs b/src/test/run-pass/unique-drop-complex.rs index 056acd16208..1910d51bd0b 100644 --- a/src/test/run-pass/unique-drop-complex.rs +++ b/src/test/run-pass/unique-drop-complex.rs @@ -14,5 +14,5 @@ #![feature(box_syntax)] pub fn main() { - let _x: Box<_> = box vec!(0,0,0,0,0); + let _x: Box<_> = box vec![0,0,0,0,0]; } diff --git a/src/test/run-pass/unique-in-vec-copy.rs b/src/test/run-pass/unique-in-vec-copy.rs index ab0e3ee809d..ece206caa02 100644 --- a/src/test/run-pass/unique-in-vec-copy.rs +++ b/src/test/run-pass/unique-in-vec-copy.rs @@ -13,7 +13,7 @@ #![feature(box_syntax)] pub fn main() { - let mut a: Vec<Box<_>> = vec!(box 10); + let mut a: Vec<Box<_>> = vec![box 10]; let b = a.clone(); assert_eq!(*a[0], 10); diff --git a/src/test/run-pass/unique-in-vec.rs b/src/test/run-pass/unique-in-vec.rs index 026bc0435d9..bd965d41eea 100644 --- a/src/test/run-pass/unique-in-vec.rs +++ b/src/test/run-pass/unique-in-vec.rs @@ -13,6 +13,6 @@ #![feature(box_syntax)] pub fn main() { - let vect : Vec<Box<_>> = vec!(box 100); + let vect : Vec<Box<_>> = vec![box 100]; assert_eq!(vect[0], box 100); } diff --git a/src/test/run-pass/utf8_chars.rs b/src/test/run-pass/utf8_chars.rs index 0f751501293..0a984429fab 100644 --- a/src/test/run-pass/utf8_chars.rs +++ b/src/test/run-pass/utf8_chars.rs @@ -15,7 +15,7 @@ use std::str; pub fn main() { // Chars of 1, 2, 3, and 4 bytes - let chs: Vec<char> = vec!('e', 'é', '€', '\u{10000}'); + let chs: Vec<char> = vec!['e', 'é', '€', '\u{10000}']; let s: String = chs.iter().cloned().collect(); let schs: Vec<char> = s.chars().collect(); diff --git a/src/test/run-pass/vec-concat.rs b/src/test/run-pass/vec-concat.rs index 5fe9dd60591..8ba8df57e54 100644 --- a/src/test/run-pass/vec-concat.rs +++ b/src/test/run-pass/vec-concat.rs @@ -11,8 +11,8 @@ use std::vec; pub fn main() { - let a: Vec<isize> = vec!(1, 2, 3, 4, 5); - let b: Vec<isize> = vec!(6, 7, 8, 9, 0); + let a: Vec<isize> = vec![1, 2, 3, 4, 5]; + let b: Vec<isize> = vec![6, 7, 8, 9, 0]; let mut v: Vec<isize> = a; v.extend_from_slice(&b); println!("{}", v[9]); diff --git a/src/test/run-pass/vec-growth.rs b/src/test/run-pass/vec-growth.rs index e51d898e1d4..5bf6a457df9 100644 --- a/src/test/run-pass/vec-growth.rs +++ b/src/test/run-pass/vec-growth.rs @@ -11,7 +11,7 @@ pub fn main() { - let mut v = vec!(1); + let mut v = vec![1]; v.push(2); v.push(3); v.push(4); diff --git a/src/test/run-pass/vec-late-init.rs b/src/test/run-pass/vec-late-init.rs index 7a8c0739efe..420f6a429f1 100644 --- a/src/test/run-pass/vec-late-init.rs +++ b/src/test/run-pass/vec-late-init.rs @@ -11,6 +11,6 @@ pub fn main() { let mut later: Vec<isize> ; - if true { later = vec!(1); } else { later = vec!(2); } + if true { later = vec![1]; } else { later = vec![2]; } println!("{}", later[0]); } diff --git a/src/test/run-pass/vec-macro-with-trailing-comma.rs b/src/test/run-pass/vec-macro-with-trailing-comma.rs index 35af249ef5f..135ecb47498 100644 --- a/src/test/run-pass/vec-macro-with-trailing-comma.rs +++ b/src/test/run-pass/vec-macro-with-trailing-comma.rs @@ -11,6 +11,6 @@ pub fn main() { - assert_eq!(vec!(1), vec!(1,)); - assert_eq!(vec!(1, 2, 3), vec!(1, 2, 3,)); + assert_eq!(vec![1], vec![1,]); + assert_eq!(vec![1, 2, 3], vec![1, 2, 3,]); } diff --git a/src/test/run-pass/vec-push.rs b/src/test/run-pass/vec-push.rs index 33f01c5bd41..14a52cc4b5c 100644 --- a/src/test/run-pass/vec-push.rs +++ b/src/test/run-pass/vec-push.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub fn main() { let mut v = vec!(1, 2, 3); v.push(1); } +pub fn main() { let mut v = vec![1, 2, 3]; v.push(1); } diff --git a/src/test/run-pass/vec-to_str.rs b/src/test/run-pass/vec-to_str.rs index f000ada770a..1fed6a0be48 100644 --- a/src/test/run-pass/vec-to_str.rs +++ b/src/test/run-pass/vec-to_str.rs @@ -10,9 +10,9 @@ pub fn main() { - assert_eq!(format!("{:?}", vec!(0, 1)), "[0, 1]".to_string()); + assert_eq!(format!("{:?}", vec![0, 1]), "[0, 1]".to_string()); - let foo = vec!(3, 4); + let foo = vec![3, 4]; let bar: &[isize] = &[4, 5]; assert_eq!(format!("{:?}", foo), "[3, 4]"); diff --git a/src/test/run-pass/vec.rs b/src/test/run-pass/vec.rs index c61b3d56dbf..9cacb9db20e 100644 --- a/src/test/run-pass/vec.rs +++ b/src/test/run-pass/vec.rs @@ -11,7 +11,7 @@ pub fn main() { - let v: Vec<isize> = vec!(10, 20); + let v: Vec<isize> = vec![10, 20]; assert_eq!(v[0], 10); assert_eq!(v[1], 20); let mut x: usize = 0; diff --git a/src/test/run-pass/while-with-break.rs b/src/test/run-pass/while-with-break.rs index ed149ad5109..4c599e9c428 100644 --- a/src/test/run-pass/while-with-break.rs +++ b/src/test/run-pass/while-with-break.rs @@ -16,7 +16,7 @@ pub fn main() { i = i + 1; if i == 95 { let _v: Vec<isize> = - vec!(1, 2, 3, 4, 5); // we check that it is freed by break + vec![1, 2, 3, 4, 5]; // we check that it is freed by break println!("breaking"); break; diff --git a/src/test/compile-fail/borrowck/borrowck-ref-into-rvalue.rs b/src/test/ui/span/borrowck-ref-into-rvalue.rs index 726d4bcdf1d..726d4bcdf1d 100644 --- a/src/test/compile-fail/borrowck/borrowck-ref-into-rvalue.rs +++ b/src/test/ui/span/borrowck-ref-into-rvalue.rs diff --git a/src/test/ui/span/borrowck-ref-into-rvalue.stderr b/src/test/ui/span/borrowck-ref-into-rvalue.stderr new file mode 100644 index 00000000000..adbf39b3f75 --- /dev/null +++ b/src/test/ui/span/borrowck-ref-into-rvalue.stderr @@ -0,0 +1,16 @@ +error: borrowed value does not live long enough + --> $DIR/borrowck-ref-into-rvalue.rs:18:5 + | +14 | Some(ref m) => { //~ ERROR borrowed value does not live long enough + | ----- borrow occurs here +... +18 | } + | ^ borrowed value dropped here while still borrowed +19 | println!("{}", *msg); +20 | } + | - borrowed value needs to live until here + | + = note: consider using a `let` binding to increase its lifetime + +error: aborting due to previous error + diff --git a/src/test/compile-fail/destructor-restrictions.rs b/src/test/ui/span/destructor-restrictions.rs index 22f615cafd7..22f615cafd7 100644 --- a/src/test/compile-fail/destructor-restrictions.rs +++ b/src/test/ui/span/destructor-restrictions.rs diff --git a/src/test/ui/span/destructor-restrictions.stderr b/src/test/ui/span/destructor-restrictions.stderr new file mode 100644 index 00000000000..3253212c5b8 --- /dev/null +++ b/src/test/ui/span/destructor-restrictions.stderr @@ -0,0 +1,12 @@ +error: `*a` does not live long enough + --> $DIR/destructor-restrictions.rs:19:5 + | +18 | *a.borrow() + 1 //~ ERROR `*a` does not live long enough + | - borrow occurs here +19 | }; + | ^- borrowed value needs to live until here + | | + | `*a` dropped here while still borrowed + +error: aborting due to previous error + diff --git a/src/test/ui/span/issue-11925.stderr b/src/test/ui/span/issue-11925.stderr index 3fedb2884bc..6ad9c27b8b9 100644 --- a/src/test/ui/span/issue-11925.stderr +++ b/src/test/ui/span/issue-11925.stderr @@ -4,8 +4,8 @@ error: `x` does not live long enough 18 | let f = to_fn_once(move|| &x); | ^ | | - | does not live long enough - | borrowed value only lives until here + | borrow occurs here + | `x` dropped here while still borrowed ... 23 | } | - borrowed value needs to live until here diff --git a/src/test/ui/span/issue-23338-locals-die-before-temps-of-body.stderr b/src/test/ui/span/issue-23338-locals-die-before-temps-of-body.stderr index f10ba0bf221..85a0002f241 100644 --- a/src/test/ui/span/issue-23338-locals-die-before-temps-of-body.stderr +++ b/src/test/ui/span/issue-23338-locals-die-before-temps-of-body.stderr @@ -9,14 +9,14 @@ error: `y` does not live long enough = note: values in a scope are dropped in the opposite order they are created error: `y` does not live long enough - --> $DIR/issue-23338-locals-die-before-temps-of-body.rs:27:9 + --> $DIR/issue-23338-locals-die-before-temps-of-body.rs:28:5 | 27 | y.borrow().clone() //~ ERROR `y` does not live long enough - | ^ does not live long enough + | - borrow occurs here 28 | }; - | -- borrowed value needs to live until here + | ^- borrowed value needs to live until here | | - | borrowed value only lives until here + | `y` dropped here while still borrowed error: aborting due to 2 previous errors diff --git a/src/test/ui/span/issue-24690.rs b/src/test/ui/span/issue-24690.rs new file mode 100644 index 00000000000..def0d9aced3 --- /dev/null +++ b/src/test/ui/span/issue-24690.rs @@ -0,0 +1,22 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A test to ensure that helpful `note` messages aren't emitted more often +//! than necessary. + +// Although there are three errors, we should only get two "lint level defined +// here" notes pointing at the `warnings` span, one for each error type. +#![deny(warnings)] + +fn main() { + let theTwo = 2; + let theOtherTwo = 2; + println!("{}", theTwo); +} diff --git a/src/test/ui/span/issue-24690.stderr b/src/test/ui/span/issue-24690.stderr new file mode 100644 index 00000000000..0d2a2ef7516 --- /dev/null +++ b/src/test/ui/span/issue-24690.stderr @@ -0,0 +1,32 @@ +error: unused variable: `theOtherTwo` + --> $DIR/issue-24690.rs:20:9 + | +20 | let theOtherTwo = 2; + | ^^^^^^^^^^^ + | +note: lint level defined here + --> $DIR/issue-24690.rs:16:9 + | +16 | #![deny(warnings)] + | ^^^^^^^^ + +error: variable `theTwo` should have a snake case name such as `the_two` + --> $DIR/issue-24690.rs:19:9 + | +19 | let theTwo = 2; + | ^^^^^^ + | +note: lint level defined here + --> $DIR/issue-24690.rs:16:9 + | +16 | #![deny(warnings)] + | ^^^^^^^^ + +error: variable `theOtherTwo` should have a snake case name such as `the_other_two` + --> $DIR/issue-24690.rs:20:9 + | +20 | let theOtherTwo = 2; + | ^^^^^^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs b/src/test/ui/span/mut-ptr-cant-outlive-ref.rs index 8e968d90a2f..8e968d90a2f 100644 --- a/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs +++ b/src/test/ui/span/mut-ptr-cant-outlive-ref.rs diff --git a/src/test/ui/span/mut-ptr-cant-outlive-ref.stderr b/src/test/ui/span/mut-ptr-cant-outlive-ref.stderr new file mode 100644 index 00000000000..0417eb075af --- /dev/null +++ b/src/test/ui/span/mut-ptr-cant-outlive-ref.stderr @@ -0,0 +1,12 @@ +error: `b` does not live long enough + --> $DIR/mut-ptr-cant-outlive-ref.rs:19:5 + | +18 | p = &*b; //~ ERROR `b` does not live long enough + | - borrow occurs here +19 | } + | ^ `b` dropped here while still borrowed +20 | } + | - borrowed value needs to live until here + +error: aborting due to previous error + diff --git a/src/test/compile-fail/range-2.rs b/src/test/ui/span/range-2.rs index 94967693ecf..94967693ecf 100644 --- a/src/test/compile-fail/range-2.rs +++ b/src/test/ui/span/range-2.rs diff --git a/src/test/ui/span/range-2.stderr b/src/test/ui/span/range-2.stderr new file mode 100644 index 00000000000..9f11de77be7 --- /dev/null +++ b/src/test/ui/span/range-2.stderr @@ -0,0 +1,24 @@ +error: `a` does not live long enough + --> $DIR/range-2.rs:20:5 + | +17 | &a..&b + | - borrow occurs here +... +20 | }; + | ^ `a` dropped here while still borrowed +21 | } + | - borrowed value needs to live until here + +error: `b` does not live long enough + --> $DIR/range-2.rs:20:5 + | +17 | &a..&b + | - borrow occurs here +... +20 | }; + | ^ `b` dropped here while still borrowed +21 | } + | - borrowed value needs to live until here + +error: aborting due to 2 previous errors + diff --git a/src/test/compile-fail/regionck-unboxed-closure-lifetimes.rs b/src/test/ui/span/regionck-unboxed-closure-lifetimes.rs index 8ec6036762f..8ec6036762f 100644 --- a/src/test/compile-fail/regionck-unboxed-closure-lifetimes.rs +++ b/src/test/ui/span/regionck-unboxed-closure-lifetimes.rs diff --git a/src/test/ui/span/regionck-unboxed-closure-lifetimes.stderr b/src/test/ui/span/regionck-unboxed-closure-lifetimes.stderr new file mode 100644 index 00000000000..9c369e03e33 --- /dev/null +++ b/src/test/ui/span/regionck-unboxed-closure-lifetimes.stderr @@ -0,0 +1,13 @@ +error: `c` does not live long enough + --> $DIR/regionck-unboxed-closure-lifetimes.rs:19:5 + | +17 | let c_ref = &c; //~ ERROR `c` does not live long enough + | - borrow occurs here +18 | f = move |a: isize, b: isize| { a + b + *c_ref }; +19 | } + | ^ `c` dropped here while still borrowed +20 | } + | - borrowed value needs to live until here + +error: aborting due to previous error + diff --git a/src/test/compile-fail/regions-close-over-type-parameter-2.rs b/src/test/ui/span/regions-close-over-type-parameter-2.rs index 053af49e068..053af49e068 100644 --- a/src/test/compile-fail/regions-close-over-type-parameter-2.rs +++ b/src/test/ui/span/regions-close-over-type-parameter-2.rs diff --git a/src/test/ui/span/regions-close-over-type-parameter-2.stderr b/src/test/ui/span/regions-close-over-type-parameter-2.stderr new file mode 100644 index 00000000000..ea652da7da4 --- /dev/null +++ b/src/test/ui/span/regions-close-over-type-parameter-2.stderr @@ -0,0 +1,13 @@ +error: `tmp0` does not live long enough + --> $DIR/regions-close-over-type-parameter-2.rs:35:5 + | +33 | let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough + | ---- borrow occurs here +34 | repeater3(tmp1) +35 | }; + | ^- borrowed value needs to live until here + | | + | `tmp0` dropped here while still borrowed + +error: aborting due to previous error + diff --git a/src/test/compile-fail/regions-escape-loop-via-variable.rs b/src/test/ui/span/regions-escape-loop-via-variable.rs index f588655d1af..f588655d1af 100644 --- a/src/test/compile-fail/regions-escape-loop-via-variable.rs +++ b/src/test/ui/span/regions-escape-loop-via-variable.rs diff --git a/src/test/ui/span/regions-escape-loop-via-variable.stderr b/src/test/ui/span/regions-escape-loop-via-variable.stderr new file mode 100644 index 00000000000..09f2154905f --- /dev/null +++ b/src/test/ui/span/regions-escape-loop-via-variable.stderr @@ -0,0 +1,12 @@ +error: `x` does not live long enough + --> $DIR/regions-escape-loop-via-variable.rs:22:5 + | +21 | p = &x; //~ ERROR `x` does not live long enough + | - borrow occurs here +22 | } + | ^ `x` dropped here while still borrowed +23 | } + | - borrowed value needs to live until here + +error: aborting due to previous error + diff --git a/src/test/compile-fail/regions-escape-loop-via-vec.rs b/src/test/ui/span/regions-escape-loop-via-vec.rs index f5ea7a2108e..8982b5cd98d 100644 --- a/src/test/compile-fail/regions-escape-loop-via-vec.rs +++ b/src/test/ui/span/regions-escape-loop-via-vec.rs @@ -11,7 +11,7 @@ // The type of `y` ends up getting inferred to the type of the block. fn broken() { let mut x = 3; - let mut _y = vec!(&mut x); + let mut _y = vec![&mut x]; //~^ NOTE borrow of `x` occurs here //~| NOTE borrow of `x` occurs here //~| NOTE borrow of `x` occurs here diff --git a/src/test/ui/span/regions-escape-loop-via-vec.stderr b/src/test/ui/span/regions-escape-loop-via-vec.stderr new file mode 100644 index 00000000000..58f7849e443 --- /dev/null +++ b/src/test/ui/span/regions-escape-loop-via-vec.stderr @@ -0,0 +1,41 @@ +error: `z` does not live long enough + --> $DIR/regions-escape-loop-via-vec.rs:26:5 + | +22 | _y.push(&mut z); //~ ERROR `z` does not live long enough + | - borrow occurs here +... +26 | } + | ^ `z` dropped here while still borrowed +27 | //~^ NOTE borrowed value only lives until here +28 | } + | - borrowed value needs to live until here + +error[E0503]: cannot use `x` because it was mutably borrowed + --> $DIR/regions-escape-loop-via-vec.rs:18:11 + | +14 | let mut _y = vec![&mut x]; + | - borrow of `x` occurs here +... +18 | while x < 10 { //~ ERROR cannot use `x` because it was mutably borrowed + | ^ use of borrowed `x` + +error[E0503]: cannot use `x` because it was mutably borrowed + --> $DIR/regions-escape-loop-via-vec.rs:20:13 + | +14 | let mut _y = vec![&mut x]; + | - borrow of `x` occurs here +... +20 | let mut z = x; //~ ERROR cannot use `x` because it was mutably borrowed + | ^^^^^ use of borrowed `x` + +error[E0506]: cannot assign to `x` because it is borrowed + --> $DIR/regions-escape-loop-via-vec.rs:24:9 + | +14 | let mut _y = vec![&mut x]; + | - borrow of `x` occurs here +... +24 | x += 1; //~ ERROR cannot assign + | ^^^^^^ assignment to borrowed `x` occurs here + +error: aborting due to 4 previous errors + diff --git a/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs b/src/test/ui/span/regions-infer-borrow-scope-within-loop.rs index a05658e9e58..a05658e9e58 100644 --- a/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs +++ b/src/test/ui/span/regions-infer-borrow-scope-within-loop.rs diff --git a/src/test/ui/span/regions-infer-borrow-scope-within-loop.stderr b/src/test/ui/span/regions-infer-borrow-scope-within-loop.stderr new file mode 100644 index 00000000000..0e7b64ec2b3 --- /dev/null +++ b/src/test/ui/span/regions-infer-borrow-scope-within-loop.stderr @@ -0,0 +1,14 @@ +error: `*x` does not live long enough + --> $DIR/regions-infer-borrow-scope-within-loop.rs:28:5 + | +24 | y = borrow(&*x); //~ ERROR `*x` does not live long enough + | -- borrow occurs here +... +28 | } + | ^ `*x` dropped here while still borrowed +29 | assert!(*y != 0); +30 | } + | - borrowed value needs to live until here + +error: aborting due to previous error + diff --git a/src/test/compile-fail/send-is-not-static-ensures-scoping.rs b/src/test/ui/span/send-is-not-static-ensures-scoping.rs index 1b7718d2283..1b7718d2283 100644 --- a/src/test/compile-fail/send-is-not-static-ensures-scoping.rs +++ b/src/test/ui/span/send-is-not-static-ensures-scoping.rs diff --git a/src/test/ui/span/send-is-not-static-ensures-scoping.stderr b/src/test/ui/span/send-is-not-static-ensures-scoping.stderr new file mode 100644 index 00000000000..5897921476d --- /dev/null +++ b/src/test/ui/span/send-is-not-static-ensures-scoping.stderr @@ -0,0 +1,28 @@ +error: `x` does not live long enough + --> $DIR/send-is-not-static-ensures-scoping.rs:32:5 + | +26 | let y = &x; //~ ERROR `x` does not live long enough + | - borrow occurs here +... +32 | }; + | ^ `x` dropped here while still borrowed +... +35 | } + | - borrowed value needs to live until here + +error: `y` does not live long enough + --> $DIR/send-is-not-static-ensures-scoping.rs:29:22 + | +28 | scoped(|| { + | -- capture occurs here +29 | let _z = y; + | ^ does not live long enough +... +32 | }; + | - borrowed value only lives until here +... +35 | } + | - borrowed value needs to live until here + +error: aborting due to 2 previous errors + diff --git a/src/test/compile-fail/send-is-not-static-std-sync-2.rs b/src/test/ui/span/send-is-not-static-std-sync-2.rs index d9d3706586b..d9d3706586b 100644 --- a/src/test/compile-fail/send-is-not-static-std-sync-2.rs +++ b/src/test/ui/span/send-is-not-static-std-sync-2.rs diff --git a/src/test/ui/span/send-is-not-static-std-sync-2.stderr b/src/test/ui/span/send-is-not-static-std-sync-2.stderr new file mode 100644 index 00000000000..08f85f17bf8 --- /dev/null +++ b/src/test/ui/span/send-is-not-static-std-sync-2.stderr @@ -0,0 +1,36 @@ +error: `x` does not live long enough + --> $DIR/send-is-not-static-std-sync-2.rs:22:5 + | +21 | Mutex::new(&x) //~ ERROR does not live long enough + | - borrow occurs here +22 | }; + | ^ `x` dropped here while still borrowed +... +25 | } + | - borrowed value needs to live until here + +error: `x` does not live long enough + --> $DIR/send-is-not-static-std-sync-2.rs:31:5 + | +30 | RwLock::new(&x) //~ ERROR does not live long enough + | - borrow occurs here +31 | }; + | ^ `x` dropped here while still borrowed +32 | let _dangling = *lock.read().unwrap(); +33 | } + | - borrowed value needs to live until here + +error: `x` does not live long enough + --> $DIR/send-is-not-static-std-sync-2.rs:41:5 + | +39 | let _ = tx.send(&x); //~ ERROR does not live long enough + | - borrow occurs here +40 | (tx, rx) +41 | }; + | ^ `x` dropped here while still borrowed +... +44 | } + | - borrowed value needs to live until here + +error: aborting due to 3 previous errors + diff --git a/src/test/compile-fail/send-is-not-static-std-sync.rs b/src/test/ui/span/send-is-not-static-std-sync.rs index 8ec2fe8a1ec..8ec2fe8a1ec 100644 --- a/src/test/compile-fail/send-is-not-static-std-sync.rs +++ b/src/test/ui/span/send-is-not-static-std-sync.rs diff --git a/src/test/ui/span/send-is-not-static-std-sync.stderr b/src/test/ui/span/send-is-not-static-std-sync.stderr new file mode 100644 index 00000000000..a86cf1e5884 --- /dev/null +++ b/src/test/ui/span/send-is-not-static-std-sync.stderr @@ -0,0 +1,56 @@ +error: `z` does not live long enough + --> $DIR/send-is-not-static-std-sync.rs:27:5 + | +26 | *lock.lock().unwrap() = &z; //~ ERROR does not live long enough + | - borrow occurs here +27 | } + | ^ `z` dropped here while still borrowed +28 | } + | - borrowed value needs to live until here + +error[E0505]: cannot move out of `y` because it is borrowed + --> $DIR/send-is-not-static-std-sync.rs:23:10 + | +22 | *lock.lock().unwrap() = &*y; + | -- borrow of `*y` occurs here +23 | drop(y); //~ ERROR cannot move out + | ^ move out of `y` occurs here + +error: `z` does not live long enough + --> $DIR/send-is-not-static-std-sync.rs:39:5 + | +38 | *lock.write().unwrap() = &z; //~ ERROR does not live long enough + | - borrow occurs here +39 | } + | ^ `z` dropped here while still borrowed +40 | } + | - borrowed value needs to live until here + +error[E0505]: cannot move out of `y` because it is borrowed + --> $DIR/send-is-not-static-std-sync.rs:35:10 + | +34 | *lock.write().unwrap() = &*y; + | -- borrow of `*y` occurs here +35 | drop(y); //~ ERROR cannot move out + | ^ move out of `y` occurs here + +error: `z` does not live long enough + --> $DIR/send-is-not-static-std-sync.rs:53:5 + | +52 | tx.send(&z).unwrap(); //~ ERROR does not live long enough + | - borrow occurs here +53 | } + | ^ `z` dropped here while still borrowed +54 | } + | - borrowed value needs to live until here + +error[E0505]: cannot move out of `y` because it is borrowed + --> $DIR/send-is-not-static-std-sync.rs:49:10 + | +48 | tx.send(&*y); + | -- borrow of `*y` occurs here +49 | drop(y); //~ ERROR cannot move out + | ^ move out of `y` occurs here + +error: aborting due to 6 previous errors + diff --git a/src/test/compile-fail/wf-method-late-bound-regions.rs b/src/test/ui/span/wf-method-late-bound-regions.rs index b9d292fd156..b9d292fd156 100644 --- a/src/test/compile-fail/wf-method-late-bound-regions.rs +++ b/src/test/ui/span/wf-method-late-bound-regions.rs diff --git a/src/test/ui/span/wf-method-late-bound-regions.stderr b/src/test/ui/span/wf-method-late-bound-regions.stderr new file mode 100644 index 00000000000..aeac3102fbf --- /dev/null +++ b/src/test/ui/span/wf-method-late-bound-regions.stderr @@ -0,0 +1,13 @@ +error: `pointer` does not live long enough + --> $DIR/wf-method-late-bound-regions.rs:31:5 + | +30 | f2.xmute(&pointer) //~ ERROR `pointer` does not live long enough + | ------- borrow occurs here +31 | }; + | ^ `pointer` dropped here while still borrowed +32 | println!("{}", dangling); +33 | } + | - borrowed value needs to live until here + +error: aborting due to previous error + diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index e6efd45cad1..2dc7cdbf935 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -73,7 +73,7 @@ fn main() { pub fn parse_config(args: Vec<String> ) -> Config { let groups : Vec<getopts::OptGroup> = - vec!(reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"), + vec![reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"), reqopt("", "run-lib-path", "path to target shared libraries", "PATH"), reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"), reqopt("", "rustdoc-path", "path to rustdoc to use for compiling", "PATH"), @@ -111,7 +111,7 @@ pub fn parse_config(args: Vec<String> ) -> Config { reqopt("", "llvm-components", "list of LLVM components built in", "LIST"), reqopt("", "llvm-cxxflags", "C++ flags for LLVM", "FLAGS"), optopt("", "nodejs", "the name of nodejs", "PATH"), - optflag("h", "help", "show this message")); + optflag("h", "help", "show this message")]; let (argv0, args_) = args.split_first().unwrap(); if args.len() == 1 || args[1] == "-h" || args[1] == "--help" { diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index e10420bf291..03c05f919b7 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -253,7 +253,7 @@ impl<'test> TestCx<'test> { let mut src = String::new(); File::open(&self.testpaths.file).unwrap().read_to_string(&mut src).unwrap(); - let mut srcs = vec!(src); + let mut srcs = vec![src]; let mut round = 0; while round < rounds { @@ -335,13 +335,13 @@ impl<'test> TestCx<'test> { -> ProcArgs { let aux_dir = self.aux_output_dir_name(); // FIXME (#9639): This needs to handle non-utf8 paths - let mut args = vec!("-".to_owned(), + let mut args = vec!["-".to_owned(), "-Zunstable-options".to_owned(), "--unpretty".to_owned(), pretty_type, format!("--target={}", self.config.target), "-L".to_owned(), - aux_dir.to_str().unwrap().to_owned()); + aux_dir.to_str().unwrap().to_owned()]; args.extend(self.split_maybe_args(&self.config.target_rustcflags)); args.extend(self.props.compile_flags.iter().cloned()); return ProcArgs { @@ -388,7 +388,7 @@ actual:\n\ self.create_dir_racy(&out_dir); // FIXME (#9639): This needs to handle non-utf8 paths - let mut args = vec!("-".to_owned(), + let mut args = vec!["-".to_owned(), "-Zno-trans".to_owned(), "--out-dir".to_owned(), out_dir.to_str().unwrap().to_owned(), @@ -396,7 +396,7 @@ actual:\n\ "-L".to_owned(), self.config.build_base.to_str().unwrap().to_owned(), "-L".to_owned(), - aux_dir.to_str().unwrap().to_owned()); + aux_dir.to_str().unwrap().to_owned()]; if let Some(revision) = self.revision { args.extend(vec![ format!("--cfg"), @@ -487,7 +487,7 @@ actual:\n\ exe_file.to_str().unwrap().to_owned(), self.config.adb_test_dir.clone() ], - vec!(("".to_owned(), "".to_owned())), + vec![("".to_owned(), "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{:?}`", self.config.adb_path)); @@ -499,7 +499,7 @@ actual:\n\ "tcp:5039".to_owned(), "tcp:5039".to_owned() ], - vec!(("".to_owned(), "".to_owned())), + vec![("".to_owned(), "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{:?}`", self.config.adb_path)); @@ -520,8 +520,8 @@ actual:\n\ "shell".to_owned(), adb_arg.clone() ], - vec!(("".to_owned(), - "".to_owned())), + vec![("".to_owned(), + "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{:?}`", self.config.adb_path)); loop { @@ -535,10 +535,10 @@ actual:\n\ let debugger_script = self.make_out_name("debugger.script"); // FIXME (#9639): This needs to handle non-utf8 paths let debugger_opts = - vec!("-quiet".to_owned(), + vec!["-quiet".to_owned(), "-batch".to_owned(), "-nx".to_owned(), - format!("-command={}", debugger_script.to_str().unwrap())); + format!("-command={}", debugger_script.to_str().unwrap())]; let mut gdb_path = tool_path; gdb_path.push_str(&format!("/bin/{}-gdb", self.config.target)); @@ -550,7 +550,7 @@ actual:\n\ &gdb_path, None, &debugger_opts, - vec!(("".to_owned(), "".to_owned())), + vec![("".to_owned(), "".to_owned())], None) .expect(&format!("failed to exec `{:?}`", gdb_path)); let cmdline = { @@ -642,10 +642,10 @@ actual:\n\ // FIXME (#9639): This needs to handle non-utf8 paths let debugger_opts = - vec!("-quiet".to_owned(), + vec!["-quiet".to_owned(), "-batch".to_owned(), "-nx".to_owned(), - format!("-command={}", debugger_script.to_str().unwrap())); + format!("-command={}", debugger_script.to_str().unwrap())]; let proc_args = ProcArgs { prog: debugger().to_owned(), @@ -830,9 +830,9 @@ actual:\n\ let command_directive = format!("{}-command", debugger_prefix); let check_directive = format!("{}-check", debugger_prefix); - let mut breakpoint_lines = vec!(); - let mut commands = vec!(); - let mut check_lines = vec!(); + let mut breakpoint_lines = vec![]; + let mut commands = vec![]; + let mut check_lines = vec![]; let mut counter = 1; let reader = BufReader::new(File::open(&self.testpaths.file).unwrap()); for line in reader.lines() { @@ -1120,8 +1120,8 @@ actual:\n\ fn compile_test(&self) -> ProcRes { let aux_dir = self.aux_output_dir_name(); // FIXME (#9639): This needs to handle non-utf8 paths - let link_args = vec!("-L".to_owned(), - aux_dir.to_str().unwrap().to_owned()); + let link_args = vec!["-L".to_owned(), + aux_dir.to_str().unwrap().to_owned()]; let args = self.make_compile_args(link_args, &self.testpaths.file, TargetLocation::ThisFile(self.make_exe_name())); @@ -1231,9 +1231,9 @@ actual:\n\ if (self.config.target.contains("musl") && !aux_props.force_host) || self.config.target.contains("emscripten") { - vec!("--crate-type=lib".to_owned()) + vec!["--crate-type=lib".to_owned()] } else { - vec!("--crate-type=dylib".to_owned()) + vec!["--crate-type=dylib".to_owned()] } }; crate_type.extend(extra_link_args.clone()); @@ -1315,10 +1315,10 @@ actual:\n\ }; // FIXME (#9639): This needs to handle non-utf8 paths - let mut args = vec!(input_file.to_str().unwrap().to_owned(), + let mut args = vec![input_file.to_str().unwrap().to_owned(), "-L".to_owned(), self.config.build_base.to_str().unwrap().to_owned(), - format!("--target={}", target)); + format!("--target={}", target)]; if let Some(revision) = self.revision { args.extend(vec![ @@ -1613,7 +1613,7 @@ actual:\n\ args.prog.clone(), self.config.adb_test_dir.clone() ], - vec!(("".to_owned(), "".to_owned())), + vec![("".to_owned(), "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{}`", self.config.adb_path)); @@ -1645,7 +1645,7 @@ actual:\n\ &self.config.adb_path, None, &runargs, - vec!(("".to_owned(), "".to_owned())), Some("".to_owned())) + vec![("".to_owned(), "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{}`", self.config.adb_path)); // get exitcode of result @@ -1659,7 +1659,7 @@ actual:\n\ &self.config.adb_path, None, &runargs, - vec!(("".to_owned(), "".to_owned())), + vec![("".to_owned(), "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{}`", self.config.adb_path)); @@ -1683,7 +1683,7 @@ actual:\n\ &self.config.adb_path, None, &runargs, - vec!(("".to_owned(), "".to_owned())), + vec![("".to_owned(), "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{}`", self.config.adb_path)); @@ -1698,7 +1698,7 @@ actual:\n\ &self.config.adb_path, None, &runargs, - vec!(("".to_owned(), "".to_owned())), + vec![("".to_owned(), "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{}`", self.config.adb_path)); @@ -1730,8 +1730,8 @@ actual:\n\ .to_owned(), self.config.adb_test_dir.to_owned(), ], - vec!(("".to_owned(), - "".to_owned())), + vec![("".to_owned(), + "".to_owned())], Some("".to_owned())) .expect(&format!("failed to exec `{}`", self.config.adb_path)); @@ -1749,9 +1749,9 @@ actual:\n\ fn compile_test_and_save_ir(&self) -> ProcRes { let aux_dir = self.aux_output_dir_name(); // FIXME (#9639): This needs to handle non-utf8 paths - let mut link_args = vec!("-L".to_owned(), - aux_dir.to_str().unwrap().to_owned()); - let llvm_args = vec!("--emit=llvm-ir".to_owned(),); + let mut link_args = vec!["-L".to_owned(), + aux_dir.to_str().unwrap().to_owned()]; + let llvm_args = vec!["--emit=llvm-ir".to_owned(),]; link_args.extend(llvm_args); let args = self.make_compile_args(link_args, &self.testpaths.file, @@ -1768,8 +1768,8 @@ actual:\n\ let proc_args = ProcArgs { // FIXME (#9639): This needs to handle non-utf8 paths prog: prog.to_str().unwrap().to_owned(), - args: vec!(format!("-input-file={}", irfile.to_str().unwrap()), - self.testpaths.file.to_str().unwrap().to_owned()) + args: vec![format!("-input-file={}", irfile.to_str().unwrap()), + self.testpaths.file.to_str().unwrap().to_owned()] }; self.compose_and_run(proc_args, Vec::new(), "", None, None) } diff --git a/src/tools/rustbook/book.rs b/src/tools/rustbook/book.rs index 36a37dba1fa..c5f72127a9c 100644 --- a/src/tools/rustbook/book.rs +++ b/src/tools/rustbook/book.rs @@ -94,16 +94,16 @@ pub fn parse_summary(input: &mut Read, src: &Path) -> Result<Book, Vec<String>> } } - let mut top_items = vec!(); - let mut stack = vec!(); - let mut errors = vec!(); + let mut top_items = vec![]; + let mut stack = vec![]; + let mut errors = vec![]; // always include the introduction top_items.push(BookItem { title: "Introduction".to_string(), path: PathBuf::from("README.md"), path_to_root: PathBuf::from(""), - children: vec!(), + children: vec![], }); for line_result in BufReader::new(input).lines() { @@ -142,7 +142,7 @@ pub fn parse_summary(input: &mut Read, src: &Path) -> Result<Book, Vec<String>> title: title, path: path_from_root, path_to_root: path_to_root, - children: vec!(), + children: vec![], }; let level = indent.chars().map(|c| -> usize { match c { diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 1d04e8fc8eb..a5e4e5a4c26 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -57,22 +57,18 @@ const EXCEPTION_PATHS: &'static [&'static str] = &[ "src/libpanic_abort", "src/libpanic_unwind", "src/libunwind", - "src/libstd/sys/unix", // This is where platform-specific code for std should live - "src/libstd/sys/windows", // Ditto + "src/libstd/sys/", // Platform-specific code for std lives here. + // This has the trailing slash so that sys_common is not excepted. "src/libstd/os", // Platform-specific public interfaces "src/rtstartup", // Not sure what to do about this. magic stuff for mingw // temporary exceptions - "src/libstd/lib.rs", // This could probably be done within the sys directory "src/libstd/rtdeps.rs", // Until rustbuild replaces make "src/libstd/path.rs", - "src/libstd/io/stdio.rs", - "src/libstd/num/f32.rs", - "src/libstd/num/f64.rs", - "src/libstd/thread/local.rs", - "src/libstd/sys/common/mod.rs", - "src/libstd/sys/common/net.rs", - "src/libstd/sys/common/util.rs", + "src/libstd/f32.rs", + "src/libstd/f64.rs", + "src/libstd/sys_common/mod.rs", + "src/libstd/sys_common/net.rs", "src/libterm", // Not sure how to make this crate portable, but test needs it "src/libtest", // Probably should defer to unstable std::sys APIs |
