From 1d344cfd9f37e7864f6d50d4fa0a919326d4229d Mon Sep 17 00:00:00 2001 From: Florian Zeitz Date: Tue, 30 Aug 2016 05:44:21 +0200 Subject: [PATCH 01/62] typeck: Fix error reporting of wrong entry function signatures Expected and actual type were switched, this was introduced by refactoring in 8eb12d91aaf95432ca73bda429af04e0710c984d. --- src/librustc_typeck/lib.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 2a989105c9cb..6318574b1428 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -192,12 +192,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 @@ -246,8 +246,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, @@ -302,8 +302,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, From 971e0be77c53a4d97f7b50f59854770b651c7881 Mon Sep 17 00:00:00 2001 From: David Henningsson Date: Fri, 30 Sep 2016 06:13:14 +0200 Subject: [PATCH 02/62] str: Fix documentation typo from_utf8 returns a Result, not an Option. Signed-off-by: David Henningsson --- src/libcore/str/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index d63d2d64fe10..196750254af3 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 /// From d41c91c1fa6633754e7c88ab45224aedd5b5ed92 Mon Sep 17 00:00:00 2001 From: Marcin Fatyga Date: Sun, 9 Oct 2016 10:46:11 +0200 Subject: [PATCH 03/62] Add or and or_else for ordering. --- src/libcore/cmp.rs | 70 ++++++++++++++++++++++++++++++++++++++++++ src/libcoretest/cmp.rs | 26 ++++++++++++++++ src/libcoretest/lib.rs | 1 + 3 files changed, 97 insertions(+) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index f990a27e52b3..58b3db0ad395 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -245,6 +245,76 @@ impl Ordering { Greater => Less, } } + + /// Chain two orderings. + /// + /// Returns `self` when it's not `Equal`. Otherwise returns `other`. + /// # Examples + /// + /// ``` + /// use std::cmp::Ordering; + /// + /// let result = Ordering::Equal.or(Ordering::Less); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Less.or(Ordering::Equal); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Less.or(Ordering::Greater); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Equal.or(Ordering::Equal); + /// assert_eq!(result, Ordering::Equal); + /// + /// let x = (1, 2, 7); + /// let y = (1, 5, 3); + /// let result = x.0.cmp(y.0).or(x.1.cmp(y.1)).or(x.2.cmp(y.2)); + /// + /// assert_eq!(result, Ordering::Less); + /// ``` + #[unstable(feature = "ordering_chaining", issue = "37053")] + pub fn or(self, other: Ordering) -> Ordering { + match self { + Equal => other, + _ => self, + } + } + + /// Chain the ordering with given function. + /// + /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns + /// the result. + /// + /// # Examples + /// + /// ``` + /// use std::cmp::Ordering; + /// + /// let result = Ordering::Equal.or_else(|| Ordering::Less); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Less.or_else(|| Ordering::Equal); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Less.or_else(|| Ordering::Greater); + /// assert_eq!(result, Ordering::Less); + /// + /// let result = Ordering::Equal.or_else(|| Ordering::Equal); + /// assert_eq!(result, Ordering::Equal); + /// + /// let x = (1, 2, 7); + /// let y = (1, 5, 3); + /// let result = x.0.cmp(&y.0).or_else(|| x.1.cmp(&y.1)).or_else(|| x.2.cmp(&y.2)); + /// + /// assert_eq!(result, Ordering::Less); + /// ``` + #[unstable(feature = "ordering_chaining", issue = "37053")] + pub fn or_else 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/libcoretest/cmp.rs b/src/libcoretest/cmp.rs index 051356cad164..94f66e4d1518 100644 --- a/src/libcoretest/cmp.rs +++ b/src/libcoretest/cmp.rs @@ -41,6 +41,32 @@ fn test_ordering_order() { assert_eq!(Greater.cmp(&Less), Greater); } +#[test] +fn test_ordering_or() { + assert_eq!(Equal.or(Less), Less); + assert_eq!(Equal.or(Equal), Equal); + assert_eq!(Equal.or(Greater), Greater); + assert_eq!(Less.or(Less), Less); + assert_eq!(Less.or(Equal), Less); + assert_eq!(Less.or(Greater), Less); + assert_eq!(Greater.or(Less), Greater); + assert_eq!(Greater.or(Equal), Greater); + assert_eq!(Greater.or(Greater), Greater); +} + +#[test] +fn test_ordering_or_else() { + assert_eq!(Equal.or_else(|| Less), Less); + assert_eq!(Equal.or_else(|| Equal), Equal); + assert_eq!(Equal.or_else(|| Greater), Greater); + assert_eq!(Less.or_else(|| Less), Less); + assert_eq!(Less.or_else(|| Equal), Less); + assert_eq!(Less.or_else(|| Greater), Less); + assert_eq!(Greater.or_else(|| Less), Greater); + assert_eq!(Greater.or_else(|| Equal), Greater); + assert_eq!(Greater.or_else(|| Greater), Greater); +} + #[test] fn test_user_defined_eq() { // Our type. diff --git a/src/libcoretest/lib.rs b/src/libcoretest/lib.rs index 590bf478aa72..aad0d2fedaa1 100644 --- a/src/libcoretest/lib.rs +++ b/src/libcoretest/lib.rs @@ -34,6 +34,7 @@ #![feature(unique)] #![feature(iter_max_by)] #![feature(iter_min_by)] +#![feature(ordering_chaining)] extern crate core; extern crate test; From def0b4ebc8da5cce04bc24881de8c0e6bb13bbe0 Mon Sep 17 00:00:00 2001 From: Marcin Fatyga Date: Sun, 9 Oct 2016 14:10:56 +0200 Subject: [PATCH 04/62] Fix trailing whitespace. --- src/libcore/cmp.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 58b3db0ad395..942a236fe9e9 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -246,8 +246,8 @@ impl Ordering { } } - /// Chain two orderings. - /// + /// Chain two orderings. + /// /// Returns `self` when it's not `Equal`. Otherwise returns `other`. /// # Examples /// @@ -281,10 +281,10 @@ impl Ordering { } /// Chain the ordering with given function. - /// + /// /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns /// the result. - /// + /// /// # Examples /// /// ``` From 16a979c106caddf665f74122d807086129e93bed Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 2 Oct 2016 16:29:20 -0700 Subject: [PATCH 05/62] Remove TypeOrigin::RangeExpression This variant became unused in #30884. --- src/librustc/infer/mod.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/librustc/infer/mod.rs b/src/librustc/infer/mod.rs index 39fc50666a8c..f061e0a6d15d 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", @@ -1742,7 +1737,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, From ca76d43dcb931dc8c0c1fd2a1ea5e68203d341b1 Mon Sep 17 00:00:00 2001 From: Marcin Fatyga Date: Mon, 10 Oct 2016 18:54:37 +0200 Subject: [PATCH 06/62] Fix comments --- src/libcore/cmp.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 942a236fe9e9..07f02b9c6852 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -246,7 +246,7 @@ impl Ordering { } } - /// Chain two orderings. + /// Chains two orderings. /// /// Returns `self` when it's not `Equal`. Otherwise returns `other`. /// # Examples @@ -280,7 +280,7 @@ impl Ordering { } } - /// Chain the ordering with given function. + /// Chains the ordering with the given function. /// /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns /// the result. From 1bfa1d51fd220ee5281176f565581cd9dfeaa380 Mon Sep 17 00:00:00 2001 From: "Zack M. Davis" Date: Sat, 15 Oct 2016 10:28:12 -0700 Subject: [PATCH 07/62] introing one-time diagnostics: only emit "lint level defined here" once We introduce a new `one_time_diagnostics` field on `rustc::session::Session` to hold a hashset of diagnostic messages we've set once but don't want to see again (as uniquified by span and message text), "lint level defined here" being the motivating example dealt with here. This is in the matter of #24690. --- src/librustc/lint/context.rs | 3 +-- src/librustc/session/mod.rs | 27 ++++++++++++++++++- src/test/compile-fail/lint-group-style.rs | 2 -- .../lint-unconditional-recursion.rs | 14 +--------- 4 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 81d3d440b566..eebf4d32ab26 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -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, span, "lint level defined here"); } err diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index d002aba595bc..7917964c8f1b 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, pub lints: RefCell>>, + /// Set of (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>, pub plugin_llvm_passes: RefCell>, pub mir_passes: RefCell, pub plugin_attributes: RefCell>, @@ -288,6 +292,26 @@ 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 span and message for this `Session`. + // + // FIXME: if the need arises for one-time diagnostics other than + // `span_note`, we almost certainly want to generalize this "check 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>, + span: Span, message: &str) { + let span_message = (span, message.to_owned()); + let already_noted: bool = self.one_time_diagnostics.borrow() + .contains(&span_message); + if !already_noted { + diag_builder.span_note(span, &message); + self.one_time_diagnostics.borrow_mut().insert(span_message); + } + } + pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap { self.parse_sess.codemap() } @@ -561,6 +585,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/test/compile-fail/lint-group-style.rs b/src/test/compile-fail/lint-group-style.rs index 393e46ab5394..a88e0c63ac37 100644 --- a/src/test/compile-fail/lint-group-style.rs +++ b/src/test/compile-fail/lint-group-style.rs @@ -20,7 +20,6 @@ mod test { #[forbid(bad_style)] //~^ NOTE lint level defined here - //~^^ NOTE lint level defined here mod bad { fn CamelCase() {} //~ ERROR function `CamelCase` should have a snake case name @@ -30,7 +29,6 @@ mod test { mod warn { #![warn(bad_style)] //~^ NOTE lint level defined here - //~| NOTE lint level defined here fn CamelCase() {} //~ WARN function `CamelCase` should have a snake case name diff --git a/src/test/compile-fail/lint-unconditional-recursion.rs b/src/test/compile-fail/lint-unconditional-recursion.rs index 94e189aa47f6..bee5a2c45be6 100644 --- a/src/test/compile-fail/lint-unconditional-recursion.rs +++ b/src/test/compile-fail/lint-unconditional-recursion.rs @@ -10,19 +10,7 @@ #![deny(unconditional_recursion)] //~^ NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here -//~| NOTE lint level defined here + #![allow(dead_code)] fn foo() { //~ ERROR function cannot return without recurring foo(); //~ NOTE recursive call site From 43a022660acf414f3463eb63392f344796b8e7dc Mon Sep 17 00:00:00 2001 From: Marcin Fatyga Date: Sun, 16 Oct 2016 20:24:20 +0200 Subject: [PATCH 08/62] Fix doctests --- src/libcore/cmp.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 07f02b9c6852..d4566b5a694d 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -266,8 +266,8 @@ impl Ordering { /// let result = Ordering::Equal.or(Ordering::Equal); /// assert_eq!(result, Ordering::Equal); /// - /// let x = (1, 2, 7); - /// let y = (1, 5, 3); + /// let x: (i64, i64, i64) = (1, 2, 7); + /// let y: (i64, i64, i64) = (1, 5, 3); /// let result = x.0.cmp(y.0).or(x.1.cmp(y.1)).or(x.2.cmp(y.2)); /// /// assert_eq!(result, Ordering::Less); @@ -302,8 +302,8 @@ impl Ordering { /// let result = Ordering::Equal.or_else(|| Ordering::Equal); /// assert_eq!(result, Ordering::Equal); /// - /// let x = (1, 2, 7); - /// let y = (1, 5, 3); + /// let x: (i64, i64, i64) = (1, 2, 7); + /// let y: (i64, i64, i64) = (1, 5, 3); /// let result = x.0.cmp(&y.0).or_else(|| x.1.cmp(&y.1)).or_else(|| x.2.cmp(&y.2)); /// /// assert_eq!(result, Ordering::Less); From f8322035eb54cdc701b1a856bda952d4bc3837be Mon Sep 17 00:00:00 2001 From: Andrew Paseltiner Date: Fri, 14 Oct 2016 15:31:15 -0400 Subject: [PATCH 09/62] Implement `RefUnwindSafe` for atomic types Closes #37136 --- src/libstd/lib.rs | 2 ++ src/libstd/panic.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index c2f6a6f660c4..e697c15baab7 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -218,6 +218,7 @@ #![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)] @@ -239,6 +240,7 @@ #![feature(heap_api)] #![feature(inclusive_range)] #![feature(int_error_internals)] +#![feature(integer_atomics)] #![feature(into_cow)] #![feature(lang_items)] #![feature(libc)] diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs index 3788568a2fd2..a7e8c4fab373 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 RefUnwindSafe for Mutex {} #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")] impl RefUnwindSafe for RwLock {} +#[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 RefUnwindSafe for atomic::AtomicPtr {} + #[stable(feature = "catch_unwind", since = "1.9.0")] impl Deref for AssertUnwindSafe { type Target = T; From c78a2121105736e951bbbae1cfe48b7874144cf6 Mon Sep 17 00:00:00 2001 From: Marcin Fatyga Date: Mon, 17 Oct 2016 08:37:54 +0200 Subject: [PATCH 10/62] Add ordering_chaining feature to libcore/lib.rs --- src/libcore/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 1ae4cf8e5ef5..26eae84dee81 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -92,6 +92,7 @@ #![feature(question_mark)] #![feature(never_type)] #![feature(prelude_import)] +#![feature(ordering_chaining)] #[prelude_import] #[allow(unused)] From 13a1f21371efa5be7a7d8b26bde19fb7da5bd967 Mon Sep 17 00:00:00 2001 From: Ulrik Sverdrup Date: Tue, 20 Sep 2016 09:40:25 +0200 Subject: [PATCH 11/62] hashmap: Store hashes as usize internally We can't use more than usize's bits of a hash to select a bucket anyway, so we only need to store that part in the table. This should be an improvement for the size of the data structure on 32-bit platforms. Smaller data means better cache utilization and hopefully better performance. --- src/libstd/collections/hash/table.rs | 69 ++++++++++++++++++---------- 1 file changed, 44 insertions(+), 25 deletions(-) diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index b357bc3552a5..ec0e457dc6aa 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 { capacity: usize, size: usize, - hashes: Unique, + hashes: Unique, // 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 Send for RawTable {} unsafe impl Sync for RawTable {} struct RawBucket { - 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)>, @@ -136,15 +147,27 @@ pub struct GapThenFull { /// 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::() * 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 +179,21 @@ pub fn make_hash(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::(), size_of::()) +fn can_alias_safehash_as_hash() { + assert_eq!(size_of::(), size_of::()) } impl RawBucket { @@ -605,14 +624,14 @@ impl RawTable { 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::()); + let hashes_size = capacity.wrapping_mul(size_of::()); let pairs_size = capacity.wrapping_mul(size_of::<(K, V)>()); // Allocating hashmaps is a little tricky. We need to allocate two @@ -624,13 +643,13 @@ impl RawTable { // 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::(), + align_of::(), 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::().checked_add(size_of::<(K, V)>()).unwrap(); + let size_of_bucket = size_of::().checked_add(size_of::<(K, V)>()).unwrap(); assert!(size >= capacity.checked_mul(size_of_bucket) .expect("capacity overflow"), @@ -641,7 +660,7 @@ impl RawTable { ::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 +671,7 @@ impl RawTable { } fn first_bucket_raw(&self) -> RawBucket { - let hashes_size = self.capacity * size_of::(); + let hashes_size = self.capacity * size_of::(); let pairs_size = self.capacity * size_of::<(K, V)>(); let buffer = *self.hashes as *mut u8; @@ -756,7 +775,7 @@ impl RawTable { /// this interface is safe, it's not used outside this module. struct RawBuckets<'a, K, V> { raw: RawBucket, - 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 +821,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, - 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 +1055,10 @@ impl Drop for RawTable { } } - let hashes_size = self.capacity * size_of::(); + let hashes_size = self.capacity * size_of::(); let pairs_size = self.capacity * size_of::<(K, V)>(); let (align, _, size, oflo) = calculate_allocation(hashes_size, - align_of::(), + align_of::(), pairs_size, align_of::<(K, V)>()); From 1c2151b7f9b460cda4a028f7ad031d9dae3f5913 Mon Sep 17 00:00:00 2001 From: Devon Hollowood Date: Wed, 19 Oct 2016 22:08:49 -0700 Subject: [PATCH 12/62] Add `unwrap_or_default` method to `Result` --- src/libcore/result.rs | 33 +++++++++++++++++++++++++++++++++ src/libcoretest/result.rs | 6 ++++++ 2 files changed, 39 insertions(+) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 96845259299b..8964b29b3a62 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -792,6 +792,39 @@ impl Result { } } +impl Result { + /// 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. + /// + /// ``` + /// 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); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + 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] diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index 6e9f653dcd8a..bc2cd8bbfc65 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); +} From 8faa503a6b1a02cd66d2517187b0b501a02a4905 Mon Sep 17 00:00:00 2001 From: Oliver Middleton Date: Fri, 21 Oct 2016 00:49:47 +0100 Subject: [PATCH 13/62] Fix a few links in the docs --- src/libcore/convert.rs | 6 +++--- src/libcore/macros.rs | 7 ++++--- src/libcore/marker.rs | 4 ++-- src/libcore/ops.rs | 6 +++--- src/libstd/error.rs | 4 +++- src/libstd/io/cursor.rs | 4 ++-- src/libstd/path.rs | 1 + 7 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index 5f16a4f2435f..830bbc079ad1 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -145,7 +145,7 @@ pub trait AsMut { /// /// # Generic Impls /// -/// - `[From][From] for U` implies `Into for T` +/// - [`From`][From]` for U` implies `Into for T` /// - [`into()`] is reflexive, which means that `Into for T` is implemented /// /// [`TryInto`]: trait.TryInto.html @@ -178,14 +178,14 @@ pub trait Into: Sized { /// ``` /// # Generic impls /// -/// - `From for U` implies `[Into] for T` +/// - `From for U` implies [`Into`]` for T` /// - [`from()`] is reflexive, which means that `From for T` is implemented /// /// [`TryFrom`]: trait.TryFrom.html /// [`Option`]: ../../std/option/enum.Option.html /// [`Result`]: ../../std/result/enum.Result.html /// [`String`]: ../../std/string/struct.String.html -/// [Into]: trait.Into.html +/// [`Into`]: trait.Into.html /// [`from()`]: trait.From.html#tymethod.from #[stable(feature = "rust1", since = "1.0.0")] pub trait From: Sized { diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index 6e08abd34614..d5b65d27a5a8 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 /// /// ``` diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs index 03d8af1563d6..bdb0dd8e7d1a 100644 --- a/src/libcore/marker.rs +++ b/src/libcore/marker.rs @@ -241,8 +241,8 @@ pub trait Unsize { /// 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 72e951a7c347..0349f113762e 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 /// diff --git a/src/libstd/error.rs b/src/libstd/error.rs index a1909b0f9578..454fa47cfbc9 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/io/cursor.rs b/src/libstd/io/cursor.rs index ca9452ffe3ec..1fed061292b8 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`]`>` 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 diff --git a/src/libstd/path.rs b/src/libstd/path.rs index d6a5dfe55180..34d1ed9e00a3 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. From fb1ef4f42c0aefa3f92b3f81ad4f24bdcb0b1753 Mon Sep 17 00:00:00 2001 From: Devon Hollowood Date: Thu, 20 Oct 2016 23:50:33 -0700 Subject: [PATCH 14/62] Make `Result`'s `unwrap_or_default` unstable --- src/libcore/result.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 8964b29b3a62..f4973b3a254b 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -802,8 +802,8 @@ impl Result { /// # 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 + /// into 0 (the default value for integers). [`parse`] converts + /// a string to any other type that implements [`FromStr`], returning an /// `Err` on error. /// /// ``` @@ -814,9 +814,12 @@ impl Result { /// /// assert_eq!(1909, good_year); /// assert_eq!(0, bad_year); + /// + /// [`parse`]: ../../std/primitive.str.html#method.parse + /// [`FromStr`]: ../../std/str/trait.FromStr.html /// ``` #[inline] - #[stable(feature = "rust1", since = "1.0.0")] + #[unstable(feature = "result_unwrap_or_default", issue = "0")] pub fn unwrap_or_default(self) -> T { match self { Ok(x) => x, From 095850594f9140ae9d25eb3801aa4442295b0a91 Mon Sep 17 00:00:00 2001 From: Devon Hollowood Date: Fri, 21 Oct 2016 00:48:39 -0700 Subject: [PATCH 15/62] Fix `test_unwrap_or_default` --- src/libcoretest/result.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index bc2cd8bbfc65..f80cb8d52073 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(result_unwrap_or_default)] + fn op1() -> Result { Ok(666) } fn op2() -> Result { Err("sadface") } From 320055396bc8c05f305cc4a861863c14db4d2a8f Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 21 Oct 2016 17:30:12 -0400 Subject: [PATCH 16/62] add test case for changes to a private fn --- .../change_private_fn/struct_point.rs | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/test/incremental/change_private_fn/struct_point.rs 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 000000000000..678bc10f1e56 --- /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 or the MIT license +// , 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() { +} From 5d31a818df97e8a71545e5ba6de0627abb7837ee Mon Sep 17 00:00:00 2001 From: Devon Hollowood Date: Fri, 21 Oct 2016 14:29:42 -0700 Subject: [PATCH 17/62] Fix use of `result_unwrap_or_default` feature --- src/libcore/result.rs | 2 ++ src/libcoretest/lib.rs | 1 + src/libcoretest/result.rs | 2 -- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index f4973b3a254b..e7768106aa6a 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -807,6 +807,8 @@ impl Result { /// `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(); diff --git a/src/libcoretest/lib.rs b/src/libcoretest/lib.rs index 590bf478aa72..cdbc21473180 100644 --- a/src/libcoretest/lib.rs +++ b/src/libcoretest/lib.rs @@ -34,6 +34,7 @@ #![feature(unique)] #![feature(iter_max_by)] #![feature(iter_min_by)] +#![feature(result_unwrap_or_default)] extern crate core; extern crate test; diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index f80cb8d52073..bc2cd8bbfc65 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(result_unwrap_or_default)] - fn op1() -> Result { Ok(666) } fn op2() -> Result { Err("sadface") } From 86b3f6cbbe2d7e1344573118df76178a7bee5da8 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 21 Oct 2016 18:02:25 -0400 Subject: [PATCH 18/62] add a test case for changing a private impl method across crates Currently doesn't work that well at all in terms of getting reuse afterwards, see #37333. =) --- .../auxiliary/point.rs | 35 ++++++++ .../struct_point.rs | 89 +++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 src/test/incremental/change_private_impl_method_cc/auxiliary/point.rs create mode 100644 src/test/incremental/change_private_impl_method_cc/struct_point.rs 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 000000000000..8df1cf54da2b --- /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 or the MIT license +// , 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 000000000000..d8e5fbadad8b --- /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 or the MIT license +// , 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() { +} From 3dbf4d1e240ee1e1c56efdaf0c6d4556944e1b93 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 21 Oct 2016 18:15:32 -0400 Subject: [PATCH 19/62] test case for changing a private fn in root of another crate --- .../change_private_fn_cc/auxiliary/point.rs | 35 ++++++++ .../change_private_fn_cc/struct_point.rs | 86 +++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 src/test/incremental/change_private_fn_cc/auxiliary/point.rs create mode 100644 src/test/incremental/change_private_fn_cc/struct_point.rs 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 000000000000..dcc1ced635fb --- /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 or the MIT license +// , 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 000000000000..d6d2b5436ff3 --- /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 or the MIT license +// , 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() { +} From 634715a736236ba797036d76aed872ff03277fd7 Mon Sep 17 00:00:00 2001 From: Marcin Fatyga Date: Sat, 22 Oct 2016 12:44:24 +0200 Subject: [PATCH 20/62] Actually fix doctests. --- src/libcore/cmp.rs | 6 +++++- src/libcore/lib.rs | 1 - 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index d4566b5a694d..7d4b0139d9b8 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -252,6 +252,8 @@ impl Ordering { /// # Examples /// /// ``` + /// #![feature(ordering_chaining)] + /// /// use std::cmp::Ordering; /// /// let result = Ordering::Equal.or(Ordering::Less); @@ -268,7 +270,7 @@ impl Ordering { /// /// let x: (i64, i64, i64) = (1, 2, 7); /// let y: (i64, i64, i64) = (1, 5, 3); - /// let result = x.0.cmp(y.0).or(x.1.cmp(y.1)).or(x.2.cmp(y.2)); + /// let result = x.0.cmp(&y.0).or(x.1.cmp(&y.1)).or(x.2.cmp(&y.2)); /// /// assert_eq!(result, Ordering::Less); /// ``` @@ -288,6 +290,8 @@ impl Ordering { /// # Examples /// /// ``` + /// #![feature(ordering_chaining)] + /// /// use std::cmp::Ordering; /// /// let result = Ordering::Equal.or_else(|| Ordering::Less); diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 26eae84dee81..1ae4cf8e5ef5 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -92,7 +92,6 @@ #![feature(question_mark)] #![feature(never_type)] #![feature(prelude_import)] -#![feature(ordering_chaining)] #[prelude_import] #[allow(unused)] From 5a2fb8806ba841c74dee49a732937a71d16caff5 Mon Sep 17 00:00:00 2001 From: Amanieu d'Antras Date: Sat, 22 Oct 2016 14:09:45 +0100 Subject: [PATCH 21/62] Prevent exhaustive matching of Ordering to allow for future extension --- src/libcore/sync/atomic.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs index 657f7e7992fe..c10f7e39fc39 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(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(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(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(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(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(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(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(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(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(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"), } } } From 95805ee6275b4fe12cdb8845e699e7a6aa6b26eb Mon Sep 17 00:00:00 2001 From: "Zack M. Davis" Date: Wed, 26 Oct 2016 20:16:58 -0700 Subject: [PATCH 22/62] save a borrow by using return value of HashSet::insert Thanks to Niko Matsakis's review for the suggestion. --- src/librustc/session/mod.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 7917964c8f1b..f4029fde471b 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -297,18 +297,16 @@ impl Session { /// deduplicates on span and message for this `Session`. // // FIXME: if the need arises for one-time diagnostics other than - // `span_note`, we almost certainly want to generalize this "check the - // one-time diagnostics map, then set message if it's not already there" - // code to accomodate all of them + // `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>, span: Span, message: &str) { let span_message = (span, message.to_owned()); - let already_noted: bool = self.one_time_diagnostics.borrow() - .contains(&span_message); - if !already_noted { + let fresh = self.one_time_diagnostics.borrow_mut().insert(span_message); + if fresh { diag_builder.span_note(span, &message); - self.one_time_diagnostics.borrow_mut().insert(span_message); } } From 8d1da8452cc725443c43c44e0f4ec64a73944cdf Mon Sep 17 00:00:00 2001 From: "Zack M. Davis" Date: Wed, 26 Oct 2016 21:03:18 -0700 Subject: [PATCH 23/62] one-time diagnostics are only one-time for humans, not JSON-eating tools Jonathan D. Turner pointed out that we don't want to dedup in JSON mode. Since the compile-test runner uses JSON output, we regrettably need to revert the edits to existing tests; one imagines that testing for one-time diagnosticity for humans will have to be added as a UI test. This remains in the matter of #24690. --- src/librustc/session/mod.rs | 20 ++++++++++++++----- src/test/compile-fail/lint-group-style.rs | 2 ++ .../lint-unconditional-recursion.rs | 14 ++++++++++++- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index f4029fde471b..154fe9af79a9 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -294,7 +294,8 @@ impl Session { } /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but - /// deduplicates on span and message for this `Session`. + /// deduplicates on 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 @@ -303,10 +304,19 @@ impl Session { pub fn diag_span_note_once<'a, 'b>(&'a self, diag_builder: &'b mut DiagnosticBuilder<'a>, span: Span, message: &str) { - let span_message = (span, message.to_owned()); - let fresh = self.one_time_diagnostics.borrow_mut().insert(span_message); - if fresh { - diag_builder.span_note(span, &message); + 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 span_message = (span, message.to_owned()); + let fresh = self.one_time_diagnostics.borrow_mut().insert(span_message); + if fresh { + diag_builder.span_note(span, &message); + } + } } } diff --git a/src/test/compile-fail/lint-group-style.rs b/src/test/compile-fail/lint-group-style.rs index a88e0c63ac37..393e46ab5394 100644 --- a/src/test/compile-fail/lint-group-style.rs +++ b/src/test/compile-fail/lint-group-style.rs @@ -20,6 +20,7 @@ mod test { #[forbid(bad_style)] //~^ NOTE lint level defined here + //~^^ NOTE lint level defined here mod bad { fn CamelCase() {} //~ ERROR function `CamelCase` should have a snake case name @@ -29,6 +30,7 @@ mod test { mod warn { #![warn(bad_style)] //~^ NOTE lint level defined here + //~| NOTE lint level defined here fn CamelCase() {} //~ WARN function `CamelCase` should have a snake case name diff --git a/src/test/compile-fail/lint-unconditional-recursion.rs b/src/test/compile-fail/lint-unconditional-recursion.rs index bee5a2c45be6..94e189aa47f6 100644 --- a/src/test/compile-fail/lint-unconditional-recursion.rs +++ b/src/test/compile-fail/lint-unconditional-recursion.rs @@ -10,7 +10,19 @@ #![deny(unconditional_recursion)] //~^ NOTE lint level defined here - +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here +//~| NOTE lint level defined here #![allow(dead_code)] fn foo() { //~ ERROR function cannot return without recurring foo(); //~ NOTE recursive call site From ef6a07221d66bff1ef8edac4f9ffc39013abf256 Mon Sep 17 00:00:00 2001 From: "Zack M. Davis" Date: Wed, 26 Oct 2016 23:07:38 -0700 Subject: [PATCH 24/62] deduplicate one-time diagnostics on lint ID as well as span and message Some lint-level attributes (like `bad-style`, or, more dramatically, `warnings`) can affect more than one lint; it seems fairer to point out the attribute once for each distinct lint affected. Also, a UI test is added. This remains in the matter of #24690. --- src/librustc/lint/context.rs | 2 +- src/librustc/session/mod.rs | 17 +++++++-------- src/test/ui/span/issue-24690.rs | 22 ++++++++++++++++++++ src/test/ui/span/issue-24690.stderr | 32 +++++++++++++++++++++++++++++ 4 files changed, 64 insertions(+), 9 deletions(-) create mode 100644 src/test/ui/span/issue-24690.rs create mode 100644 src/test/ui/span/issue-24690.stderr diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index eebf4d32ab26..cf4115e37cd9 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -452,7 +452,7 @@ pub fn raw_struct_lint<'a>(sess: &'a Session, } if let Some(span) = def { - sess.diag_span_note_once(&mut err, span, "lint level defined here"); + sess.diag_span_note_once(&mut err, lint, span, "lint level defined here"); } err diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 154fe9af79a9..ce3f2be54b2d 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -75,10 +75,10 @@ pub struct Session { pub working_dir: PathBuf, pub lint_store: RefCell, pub lints: RefCell>>, - /// Set of (span, message) tuples tracking lint (sub)diagnostics that have - /// been set once, but should not be set again, in order to avoid + /// 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>, + pub one_time_diagnostics: RefCell>, pub plugin_llvm_passes: RefCell>, pub mir_passes: RefCell, pub plugin_attributes: RefCell>, @@ -294,8 +294,8 @@ impl Session { } /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but - /// deduplicates on span and message for this `Session` if we're not - /// outputting in JSON mode. + /// 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 @@ -303,7 +303,7 @@ impl Session { // 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>, - span: Span, message: &str) { + 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 @@ -311,8 +311,9 @@ impl Session { diag_builder.span_note(span, &message); }, _ => { - let span_message = (span, message.to_owned()); - let fresh = self.one_time_diagnostics.borrow_mut().insert(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); } diff --git a/src/test/ui/span/issue-24690.rs b/src/test/ui/span/issue-24690.rs new file mode 100644 index 000000000000..def0d9aced3c --- /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 or the MIT license +// , 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 000000000000..0d2a2ef75166 --- /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 + From 4e2822c5c28bb342e5862ba7cc0b90b865c68be1 Mon Sep 17 00:00:00 2001 From: Marcin Fatyga Date: Thu, 27 Oct 2016 23:31:10 +0200 Subject: [PATCH 25/62] Rename ordering chaining functions. --- src/libcore/cmp.rs | 24 ++++++++++++------------ src/libcoretest/cmp.rs | 40 ++++++++++++++++++++-------------------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 7d4b0139d9b8..31920fcb0f8c 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -256,26 +256,26 @@ impl Ordering { /// /// use std::cmp::Ordering; /// - /// let result = Ordering::Equal.or(Ordering::Less); + /// let result = Ordering::Equal.then(Ordering::Less); /// assert_eq!(result, Ordering::Less); /// - /// let result = Ordering::Less.or(Ordering::Equal); + /// let result = Ordering::Less.then(Ordering::Equal); /// assert_eq!(result, Ordering::Less); /// - /// let result = Ordering::Less.or(Ordering::Greater); + /// let result = Ordering::Less.then(Ordering::Greater); /// assert_eq!(result, Ordering::Less); /// - /// let result = Ordering::Equal.or(Ordering::Equal); + /// 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).or(x.1.cmp(&y.1)).or(x.2.cmp(&y.2)); + /// 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 or(self, other: Ordering) -> Ordering { + pub fn then(self, other: Ordering) -> Ordering { match self { Equal => other, _ => self, @@ -294,26 +294,26 @@ impl Ordering { /// /// use std::cmp::Ordering; /// - /// let result = Ordering::Equal.or_else(|| Ordering::Less); + /// let result = Ordering::Equal.then_with(|| Ordering::Less); /// assert_eq!(result, Ordering::Less); /// - /// let result = Ordering::Less.or_else(|| Ordering::Equal); + /// let result = Ordering::Less.then_with(|| Ordering::Equal); /// assert_eq!(result, Ordering::Less); /// - /// let result = Ordering::Less.or_else(|| Ordering::Greater); + /// let result = Ordering::Less.then_with(|| Ordering::Greater); /// assert_eq!(result, Ordering::Less); /// - /// let result = Ordering::Equal.or_else(|| Ordering::Equal); + /// 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).or_else(|| x.1.cmp(&y.1)).or_else(|| x.2.cmp(&y.2)); + /// 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 or_else Ordering>(self, f: F) -> Ordering { + pub fn then_with Ordering>(self, f: F) -> Ordering { match self { Equal => f(), _ => self, diff --git a/src/libcoretest/cmp.rs b/src/libcoretest/cmp.rs index 94f66e4d1518..e3c65ad8b33c 100644 --- a/src/libcoretest/cmp.rs +++ b/src/libcoretest/cmp.rs @@ -42,29 +42,29 @@ fn test_ordering_order() { } #[test] -fn test_ordering_or() { - assert_eq!(Equal.or(Less), Less); - assert_eq!(Equal.or(Equal), Equal); - assert_eq!(Equal.or(Greater), Greater); - assert_eq!(Less.or(Less), Less); - assert_eq!(Less.or(Equal), Less); - assert_eq!(Less.or(Greater), Less); - assert_eq!(Greater.or(Less), Greater); - assert_eq!(Greater.or(Equal), Greater); - assert_eq!(Greater.or(Greater), Greater); +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_or_else() { - assert_eq!(Equal.or_else(|| Less), Less); - assert_eq!(Equal.or_else(|| Equal), Equal); - assert_eq!(Equal.or_else(|| Greater), Greater); - assert_eq!(Less.or_else(|| Less), Less); - assert_eq!(Less.or_else(|| Equal), Less); - assert_eq!(Less.or_else(|| Greater), Less); - assert_eq!(Greater.or_else(|| Less), Greater); - assert_eq!(Greater.or_else(|| Equal), Greater); - assert_eq!(Greater.or_else(|| Greater), Greater); +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] From 6768edde788430c5277aad6b5165df8eaaedf3a2 Mon Sep 17 00:00:00 2001 From: Cobrand Date: Fri, 28 Oct 2016 01:42:47 +0200 Subject: [PATCH 26/62] improve docs for Index and IndexMut --- src/libcore/ops.rs | 85 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 67 insertions(+), 18 deletions(-) diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 72e951a7c347..0a86bec728e2 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -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 { } /// 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, +/// } /// -/// impl Index for Foo { -/// type Output = Foo; +/// #[derive(Debug, PartialEq)] +/// enum Weight { +/// Kilogram(f32), +/// Pound(f32), +/// } /// -/// fn index(&self, _index: usize) -> &Foo { -/// self +/// struct Balance { +/// pub left: Weight, +/// pub right:Weight, +/// } +/// +/// impl Index 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 for Foo { -/// fn index_mut(&mut self, index: usize) -> &mut Foo { -/// println!("Mutable indexing with {}!", index); -/// self +/// impl IndexMut 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"] From c2c37b401e65ec33b738f7725d5c8dd794ef1b1e Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Sat, 29 Oct 2016 11:18:30 +1300 Subject: [PATCH 27/62] Fix more spans in deriving::generic --- src/libsyntax_ext/deriving/generic/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 687f8c902f25..e6b63be3efc0 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, Vec<(Span, Option, P, &'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) } } From 709a06bc9247936ef64554698716ae554a5ab946 Mon Sep 17 00:00:00 2001 From: Mark-Simulacrum Date: Fri, 28 Oct 2016 19:35:30 -0600 Subject: [PATCH 28/62] Remove outdated fixme comment. --- src/librustc_privacy/lib.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 4ffe2fe38566..77b3e76fc541 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) {} } From 07bff08e4f3b3fd57adb02af63150b5893a864db Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Sat, 29 Oct 2016 15:44:43 -0700 Subject: [PATCH 29/62] Copyediting on documentation for write! and writeln! Fix various sentence fragments, missing articles, and other grammatical issues in the documentation for write! and writeln!. Also fix the links (and link names) for common return types. --- src/libcore/macros.rs | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index e6c3f549ec8e..b73166ebef3d 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -316,26 +316,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 +355,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 /// From 10ce90fca20fce776b8bdad504a5e3b915ded99f Mon Sep 17 00:00:00 2001 From: "Matwey V. Kornilov" Date: Sun, 30 Oct 2016 11:26:25 +0300 Subject: [PATCH 30/62] Fix armv7 autodetection armv7l is armv7 architecture and CFG_CPUTYPE should be armv7 in order to end up with armv7-unknown-linux-gnueabihf.mk rather than arm-unknown-linux-gnueabihf.mk --- configure | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure b/configure index 2bc8c72e3ea1..d62084cb4653 100755 --- a/configure +++ b/configure @@ -508,7 +508,7 @@ case $CFG_CPUTYPE in ;; armv7l) - CFG_CPUTYPE=arm + CFG_CPUTYPE=armv7 CFG_OSTYPE="${CFG_OSTYPE}eabihf" ;; From 9b81f3c81b6340221f9713afa9ead070086d7314 Mon Sep 17 00:00:00 2001 From: "Matwey V. Kornilov" Date: Sun, 30 Oct 2016 11:27:58 +0300 Subject: [PATCH 31/62] Add armv6l autodetection Use arm-unknown-linux-gnueabihf for hardware floating point armv6 variant --- configure | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/configure b/configure index d62084cb4653..4e62e49412e2 100755 --- a/configure +++ b/configure @@ -507,6 +507,11 @@ case $CFG_CPUTYPE in CFG_CPUTYPE=arm ;; + armv6l) + CFG_CPUTYPE=arm + CFG_OSTYPE="${CFG_OSTYPE}eabihf" + ;; + armv7l) CFG_CPUTYPE=armv7 CFG_OSTYPE="${CFG_OSTYPE}eabihf" From f32ce9c1421adfd957d357664e6dc95375ebaab0 Mon Sep 17 00:00:00 2001 From: Srinivas Reddy Thatiparthy Date: Thu, 20 Oct 2016 07:08:43 +0530 Subject: [PATCH 32/62] run rustfmt on librustc_driver folder --- src/librustc_driver/pretty.rs | 278 +++++++++++++------------ src/librustc_driver/target_features.rs | 25 +-- src/librustc_driver/test.rs | 76 +++---- 3 files changed, 191 insertions(+), 188 deletions(-) diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 10ff7dc89f9a..289a7348cc8d 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 { 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::>().join("::") + path.data + .into_iter() + .map(|elem| elem.data.to_string()) + .collect::>() + .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) -> P { fn expr_to_block(rules: ast::BlockCheckMode, e: Option>) -> P { 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, } 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, 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 f2020303089d..ba51947a3330 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 c400610a688a..f8946528a009 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, usize) { let v = msgs.iter().map(|m| m.to_string()).collect(); - (box ExpectErrorEmitter { messages: v } as Box, - msgs.len()) + (box ExpectErrorEmitter { messages: v } as Box, msgs.len()) } fn test_env(source_string: &str, @@ -103,8 +102,12 @@ fn test_env(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 krate_config = Vec::new(); let input = config::Input::Str { @@ -113,9 +116,15 @@ fn test_env(source_string: &str, }; let krate = driver::phase_1_parse_input(&sess, krate_config, &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(); @@ -168,14 +177,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 @@ -214,22 +231,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), }; } } @@ -282,10 +293,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, @@ -293,7 +301,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))) } @@ -395,9 +405,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), } } @@ -405,9 +413,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()); From 956d44fb171aed08c87db60208e7f2c85f8a72fb Mon Sep 17 00:00:00 2001 From: Pieter Frenssen Date: Sun, 30 Oct 2016 15:42:31 +0200 Subject: [PATCH 33/62] Update "Testing" chapter for 1.12 I followed the "Testing" chapter using Rust 1.12.1 but there are some differences. By default the `tests` module is now also generated by `cargo new`, and the console output is updated. --- src/doc/book/testing.md | 74 ++++++++++++++++++++++------------------- 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/src/doc/book/testing.md b/src/doc/book/testing.md index 3bdf1b7b7f22..0e6cdb8f09dd 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 From 9cc98612d70cb2dca1d1f5782648f434645fc7d6 Mon Sep 17 00:00:00 2001 From: Konrad Borowski Date: Sun, 30 Oct 2016 15:24:13 +0100 Subject: [PATCH 34/62] Don't mention "*" dependency version in guessing game example It's a bad practice as far [RFC 1241] is concerned, and introducing it in early tutorial may as well make it feel legitimate. [RFC 1241]: https://github.com/rust-lang/rfcs/blob/master/text/1241-no-wildcard-deps.md --- src/doc/book/guessing-game.md | 1 - 1 file changed, 1 deletion(-) diff --git a/src/doc/book/guessing-game.md b/src/doc/book/guessing-game.md index 4e0e37286894..a3ab4803bc4d 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. From 9802c4c5f41791cdf9ea0049733e81f03eaeccab Mon Sep 17 00:00:00 2001 From: msiglreith Date: Sun, 30 Oct 2016 17:50:28 +0100 Subject: [PATCH 35/62] Fix typo in the BitAndAssign operator documentation --- src/libcore/ops.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 72e951a7c347..3ce0d4a086ec 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -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 { - /// 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); } From c8c6d2c73269d759aec764a3356d4e19781de53c Mon Sep 17 00:00:00 2001 From: Corey Farwell Date: Sat, 29 Oct 2016 21:58:52 -0400 Subject: [PATCH 36/62] Use quieter test output when running tests on Travis CI. Fixes https://github.com/rust-lang/rust/issues/36788. --- .travis.yml | 2 +- configure | 1 + src/bootstrap/check.rs | 17 ++++++++++++++++- src/bootstrap/config.rs | 2 ++ 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index c5d8a94f39b0..0bc9a4ad4198 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 2bc8c72e3ea1..5e670c29a74e 100755 --- a/configure +++ b/configure @@ -610,6 +610,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 af76a49fed04..0a281b89c571 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 8c0ad1ccf825..abaa9389d809 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, pub prefix: Option, @@ -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), From c8937e0e6a595b8024881dc42676e8d74ce650a7 Mon Sep 17 00:00:00 2001 From: Andreas Sommer Date: Sun, 30 Oct 2016 01:03:16 +0200 Subject: [PATCH 37/62] Add E0532 error explanation --- src/librustc_resolve/diagnostics.rs | 42 ++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 1fb5db05dd50..5eb269030a00 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 } From 0dfc0467727acbc60f0ec3cf60b3d740bff3ca8e Mon Sep 17 00:00:00 2001 From: Mark-Simulacrum Date: Sun, 30 Oct 2016 20:14:10 -0600 Subject: [PATCH 38/62] Fix ICE when printing closures, and other similar types --- src/librustc/util/ppaux.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 5ca567410291..954e3b1fc13c 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); From 32fb2527d99f76b4bd41e7f4f0de5975c4ec7228 Mon Sep 17 00:00:00 2001 From: Bunts Thy Unholy Date: Mon, 31 Oct 2016 22:45:03 +1100 Subject: [PATCH 39/62] Commented out final 'main' function in order to fit within pattern of other examples and prevent incorrect indentation --- src/doc/book/closures.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/doc/book/closures.md b/src/doc/book/closures.md index 3ed85c1a90b6..b306ce5db169 100644 --- a/src/doc/book/closures.md +++ b/src/doc/book/closures.md @@ -510,6 +510,7 @@ fn factory() -> Box i32> { Box::new(|x| x + num) } + # fn main() { let f = factory(); @@ -540,12 +541,13 @@ fn factory() -> Box i32> { Box::new(move |x| x + num) } -fn main() { + +# 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 From 8483732c9a01064028551e0f8ad454790f650a0f Mon Sep 17 00:00:00 2001 From: Bunts Thy Unholy Date: Mon, 31 Oct 2016 23:41:38 +1100 Subject: [PATCH 40/62] Removed commented main functions entirely. This fits in with other examples in the Closures section --- src/doc/book/closures.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/doc/book/closures.md b/src/doc/book/closures.md index b306ce5db169..b7b67a9f1d09 100644 --- a/src/doc/book/closures.md +++ b/src/doc/book/closures.md @@ -511,12 +511,10 @@ fn factory() -> Box 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: @@ -542,12 +540,10 @@ fn factory() -> Box 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 From 07c8a25f42d1dcd8bd2bd22c8804e4bc5b6583a9 Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Mon, 31 Oct 2016 23:14:27 +0900 Subject: [PATCH 41/62] Remove unused type aliases --- src/librustc_borrowck/borrowck/mir/abs_domain.rs | 6 ++---- src/librustc_borrowck/borrowck/mod.rs | 2 -- src/librustc_incremental/persist/load.rs | 2 -- src/librustc_resolve/macros.rs | 3 --- src/librustc_trans/adt.rs | 6 ------ src/librustc_typeck/astconv.rs | 2 -- src/libstd/collections/hash/table.rs | 4 ---- 7 files changed, 2 insertions(+), 23 deletions(-) diff --git a/src/librustc_borrowck/borrowck/mir/abs_domain.rs b/src/librustc_borrowck/borrowck/mir/abs_domain.rs index dc450433ad9f..5e61c2ec7a29 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 ef6936b6e7db..f85309cf5181 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>; - /////////////////////////////////////////////////////////////////////////// // Loans and loan paths diff --git a/src/librustc_incremental/persist/load.rs b/src/librustc_incremental/persist/load.rs index 1f43e79ace3a..7cef246b6cb2 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>; -type CleanEdges = Vec<(DepNode, DepNode)>; - /// 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_resolve/macros.rs b/src/librustc_resolve/macros.rs index 72e5823598ea..ed46c1d96ad1 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, 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_trans/adt.rs b/src/librustc_trans/adt.rs index c6f3ef0a5bee..4d3361c1873f 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; - /// 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_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 8799050b1b99..1aa502fc443e 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>); - /// 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/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index b357bc3552a5..73e9f1a50043 100644 --- a/src/libstd/collections/hash/table.rs +++ b/src/libstd/collections/hash/table.rs @@ -113,10 +113,6 @@ pub struct FullBucket { table: M, } -pub type EmptyBucketImm<'table, K, V> = EmptyBucket>; -pub type FullBucketImm<'table, K, V> = FullBucket>; - -pub type EmptyBucketMut<'table, K, V> = EmptyBucket>; pub type FullBucketMut<'table, K, V> = FullBucket>; pub enum BucketState { From b926e8d08989a6e45f00c952f1867000fd9f58ea Mon Sep 17 00:00:00 2001 From: Christopher Serr Date: Mon, 31 Oct 2016 19:41:22 +0100 Subject: [PATCH 42/62] Add missing space in mutable_transmutes lint --- src/librustc_lint/builtin.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index eee34324a658..a28109c14719 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))) => { From e593c3b89343a98bdcc76ce9f5869ff18882dfff Mon Sep 17 00:00:00 2001 From: iirelu Date: Sat, 29 Oct 2016 22:54:04 +0100 Subject: [PATCH 43/62] Changed most vec! invocations to use square braces Most of the Rust community agrees that the vec! macro is clearer when called using square brackets [] instead of regular brackets (). Most of these ocurrences are from before macros allowed using different types of brackets. There is one left unchanged in a pretty-print test, as the pretty printer still wants it to have regular brackets. --- src/libcollections/slice.rs | 2 +- src/libcollections/vec.rs | 6 +- src/libcore/option.rs | 4 +- src/libcore/result.rs | 4 +- src/libgetopts/lib.rs | 4 +- src/libgraphviz/lib.rs | 10 +- src/librand/chacha.rs | 12 +- src/librand/distributions/mod.rs | 18 +-- src/librand/isaac.rs | 16 +-- src/librustc/cfg/construct.rs | 6 +- src/librustc/infer/error_reporting.rs | 4 +- src/librustc/lint/context.rs | 10 +- src/librustc/middle/lang_items.rs | 2 +- src/librustc/session/config.rs | 4 +- src/librustc/session/mod.rs | 2 +- src/librustc/traits/project.rs | 8 +- src/librustc/ty/walk.rs | 2 +- src/librustc/ty/wf.rs | 10 +- src/librustc_back/target/dragonfly_base.rs | 4 +- src/librustc_back/target/freebsd_base.rs | 4 +- src/librustc_back/target/le32_unknown_nacl.rs | 6 +- src/librustc_back/target/netbsd_base.rs | 4 +- src/librustc_back/target/openbsd_base.rs | 4 +- src/librustc_back/target/windows_base.rs | 20 +-- .../borrowck/gather_loans/move_error.rs | 2 +- src/librustc_borrowck/borrowck/move_data.rs | 2 +- src/librustc_const_eval/diagnostics.rs | 6 +- src/librustc_metadata/creader.rs | 16 +-- src/librustc_plugin/registry.rs | 10 +- src/librustc_save_analysis/dump_visitor.rs | 8 +- src/librustc_save_analysis/span_utils.rs | 4 +- src/librustc_trans/asm.rs | 2 +- src/librustc_trans/back/rpath.rs | 2 +- src/librustc_trans/back/write.rs | 2 +- src/librustc_trans/cleanup.rs | 8 +- src/librustc_typeck/check/intrinsic.rs | 118 +++++++++--------- src/librustc_typeck/collect.rs | 2 +- src/librustc_typeck/lib.rs | 4 +- src/librustdoc/core.rs | 4 +- src/librustdoc/html/markdown.rs | 2 +- src/librustdoc/html/render.rs | 2 +- src/librustdoc/html/toc.rs | 4 +- src/librustdoc/lib.rs | 4 +- src/librustdoc/test.rs | 4 +- src/libserialize/json.rs | 6 +- src/libstd/io/cursor.rs | 12 +- src/libstd/rand/mod.rs | 2 +- src/libsyntax/ast.rs | 4 +- src/libsyntax/ext/build.rs | 32 ++--- src/libsyntax/ext/quote.rs | 62 ++++----- src/libsyntax/parse/mod.rs | 32 ++--- src/libsyntax/parse/parser.rs | 8 +- src/libsyntax/print/pprust.rs | 2 +- src/libsyntax/test.rs | 2 +- src/libsyntax/util/small_vector.rs | 6 +- src/libsyntax_ext/deriving/cmp/partial_eq.rs | 4 +- src/libsyntax_ext/deriving/cmp/partial_ord.rs | 4 +- src/libsyntax_ext/deriving/decodable.rs | 4 +- src/libsyntax_ext/deriving/encodable.rs | 14 +-- src/libsyntax_ext/deriving/mod.rs | 4 +- src/libtest/lib.rs | 4 +- src/test/compile-fail/E0297.rs | 2 +- .../compile-fail/auto-ref-slice-plus-ref.rs | 2 +- .../borrowck/borrowck-assign-comp-idx.rs | 6 +- .../borrowck-borrowed-uniq-rvalue-2.rs | 2 +- .../borrowck/borrowck-loan-vec-content.rs | 4 +- ...rowck-move-out-of-overloaded-auto-deref.rs | 2 +- .../borrowck/borrowck-move-out-of-vec-tail.rs | 4 +- .../borrowck/borrowck-mut-slice-of-imm-vec.rs | 2 +- ...borrowck-overloaded-index-move-from-vec.rs | 2 +- .../borrowck-vec-pattern-element-loan.rs | 6 +- .../borrowck-vec-pattern-loan-from-mut.rs | 2 +- .../borrowck/borrowck-vec-pattern-nesting.rs | 8 +- .../borrowck-vec-pattern-tail-element-loan.rs | 2 +- .../drop-with-active-borrows-2.rs | 2 +- src/test/compile-fail/integral-indexing.rs | 2 +- src/test/compile-fail/issue-11873.rs | 2 +- src/test/compile-fail/issue-13446.rs | 2 +- src/test/compile-fail/issue-3044.rs | 2 +- src/test/compile-fail/issue-5067.rs | 2 +- .../compile-fail/lint-unused-mut-variables.rs | 4 +- .../compile-fail/match-vec-unreachable.rs | 2 +- .../moves-based-on-type-access-to-field.rs | 2 +- .../compile-fail/moves-based-on-type-exprs.rs | 10 +- src/test/compile-fail/no-capture-arc.rs | 2 +- src/test/compile-fail/no-reuse-move-arc.rs | 2 +- src/test/compile-fail/non-copyable-void.rs | 2 +- src/test/compile-fail/non-exhaustive-match.rs | 8 +- .../compile-fail/on-unimplemented/on-trait.rs | 2 +- .../regions-escape-loop-via-vec.rs | 2 +- .../unboxed-closures-failed-recursive-fn-2.rs | 2 +- ...es-move-upvar-from-non-once-ref-closure.rs | 2 +- .../compile-fail/vec-macro-with-comma-only.rs | 2 +- src/test/compile-fail/vec-mut-iter-borrow.rs | 2 +- src/test/compile-fail/vec-res-add.rs | 4 +- .../compile-fail/writing-to-immutable-vec.rs | 2 +- src/test/debuginfo/issue14411.rs | 2 +- src/test/parse-fail/issue-10412.rs | 2 +- src/test/pretty/block-disambig.rs | 4 +- .../auxiliary/custom_derive_partial_eq.rs | 4 +- src/test/run-pass/assignability-trait.rs | 2 +- ...ciated-types-doubleendediterator-object.rs | 2 +- .../associated-types-iterator-binding.rs | 2 +- src/test/run-pass/auto-loop.rs | 2 +- src/test/run-pass/auto-ref-sliceable.rs | 2 +- src/test/run-pass/autobind.rs | 2 +- src/test/run-pass/block-arg.rs | 2 +- .../run-pass/borrow-by-val-method-receiver.rs | 2 +- .../borrowck/borrowck-binding-mutbl.rs | 2 +- .../borrowck/borrowck-mut-vec-as-imm-slice.rs | 2 +- src/test/run-pass/break.rs | 2 +- src/test/run-pass/byte-literals.rs | 2 +- src/test/run-pass/cci_no_inline_exe.rs | 2 +- .../class-poly-methods-cross-crate.rs | 8 +- src/test/run-pass/class-poly-methods.rs | 8 +- ...nup-rvalue-temp-during-incomplete-alloc.rs | 2 +- .../run-pass/coerce-reborrow-imm-vec-rcvr.rs | 2 +- .../run-pass/coerce-reborrow-mut-vec-arg.rs | 2 +- .../run-pass/coerce-reborrow-mut-vec-rcvr.rs | 2 +- src/test/run-pass/deriving-in-macro.rs | 2 +- .../run-pass/drop-with-type-ascription-2.rs | 2 +- src/test/run-pass/expr-fn.rs | 2 +- src/test/run-pass/expr-match-panic.rs | 2 +- src/test/run-pass/for-destruct.rs | 2 +- src/test/run-pass/foreach-nested.rs | 2 +- src/test/run-pass/generic-ivec-leak.rs | 2 +- src/test/run-pass/generic-static-methods.rs | 2 +- src/test/run-pass/getopts_ref.rs | 2 +- src/test/run-pass/hashmap-memory.rs | 2 +- src/test/run-pass/html-literals.rs | 2 +- src/test/run-pass/ifmt.rs | 2 +- src/test/run-pass/issue-13204.rs | 2 +- src/test/run-pass/issue-14936.rs | 2 +- src/test/run-pass/issue-15080.rs | 2 +- src/test/run-pass/issue-15189.rs | 2 +- src/test/run-pass/issue-15734.rs | 2 +- src/test/run-pass/issue-2631-b.rs | 2 +- src/test/run-pass/issue-2723-b.rs | 2 +- src/test/run-pass/issue-28936.rs | 2 +- src/test/run-pass/issue-2989.rs | 4 +- src/test/run-pass/issue-3389.rs | 4 +- src/test/run-pass/issue-6153.rs | 2 +- src/test/run-pass/ivec-pass-by-value.rs | 2 +- src/test/run-pass/ivec-tag.rs | 4 +- src/test/run-pass/lambda-infer-unresolved.rs | 2 +- src/test/run-pass/linear-for-loop.rs | 2 +- src/test/run-pass/log-poly.rs | 2 +- src/test/run-pass/loop-scope.rs | 2 +- src/test/run-pass/match-vec-rvalue.rs | 2 +- src/test/run-pass/monad.rs | 6 +- src/test/run-pass/move-arg-2-unique.rs | 4 +- src/test/run-pass/move-arg-2.rs | 4 +- src/test/run-pass/newtype-polymorphic.rs | 2 +- .../nullable-pointer-iotareduction.rs | 2 +- ...owned-object-borrowed-method-headerless.rs | 4 +- src/test/run-pass/overloaded-deref.rs | 2 +- src/test/run-pass/rcvr-borrowed-to-slice.rs | 6 +- src/test/run-pass/regions-borrow-evec-uniq.rs | 4 +- .../run-pass/regions-dependent-addr-of.rs | 2 +- .../run-pass/regions-dependent-autoslice.rs | 2 +- .../regions-infer-borrow-scope-view.rs | 2 +- ...ions-on-closures-to-inference-variables.rs | 2 +- src/test/run-pass/seq-compare.rs | 18 +-- src/test/run-pass/size-and-align.rs | 2 +- src/test/run-pass/static-impl.rs | 6 +- src/test/run-pass/swap-2.rs | 2 +- src/test/run-pass/task-comm-16.rs | 2 +- src/test/run-pass/trait-bounds-in-arc.rs | 4 +- src/test/run-pass/trait-generic.rs | 8 +- src/test/run-pass/trait-to-str.rs | 6 +- .../unboxed-closures-counter-not-moved.rs | 2 +- ...ures-move-some-upvars-in-by-ref-closure.rs | 4 +- src/test/run-pass/unique-autoderef-index.rs | 2 +- src/test/run-pass/unique-create.rs | 2 +- src/test/run-pass/unique-drop-complex.rs | 2 +- src/test/run-pass/unique-in-vec-copy.rs | 2 +- src/test/run-pass/unique-in-vec.rs | 2 +- src/test/run-pass/utf8_chars.rs | 2 +- src/test/run-pass/vec-concat.rs | 4 +- src/test/run-pass/vec-growth.rs | 2 +- src/test/run-pass/vec-late-init.rs | 2 +- .../run-pass/vec-macro-with-trailing-comma.rs | 4 +- src/test/run-pass/vec-push.rs | 2 +- src/test/run-pass/vec-to_str.rs | 4 +- src/test/run-pass/vec.rs | 2 +- src/test/run-pass/while-with-break.rs | 2 +- src/tools/compiletest/src/main.rs | 4 +- src/tools/compiletest/src/runtest.rs | 70 +++++------ src/tools/rustbook/book.rs | 10 +- 189 files changed, 511 insertions(+), 511 deletions(-) diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 245579afbbad..75796cf94bfc 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -1170,7 +1170,7 @@ impl [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 7fdf7e903d5c..d94a27917e86 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/option.rs b/src/libcore/option.rs index cb18feff7342..a74979911d34 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -914,12 +914,12 @@ impl> FromIterator> for Option { /// ``` /// use std::u16; /// - /// let v = vec!(1, 2); + /// let v = vec![1, 2]; /// let res: Option> = 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>>(iter: I) -> Option { diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 78230b608044..9cb42124e00b 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -977,12 +977,12 @@ impl> FromIterator> for Result { /// ``` /// use std::u32; /// - /// let v = vec!(1, 2); + /// let v = vec![1, 2]; /// let res: Result, &'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>>(iter: I) -> Result { diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 42200795bb3a..4d2f1b999a2a 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 95c46ec5715e..03057af4a843 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -58,7 +58,7 @@ //! struct Edges(Vec); //! //! pub fn render_to(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(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(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 8ca1738bb18f..7dc0d19e6a61 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::>(); 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::>(); 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 c5588d94876c..41175c81df89 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 974f65ac2c5b..69d5015f1814 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::>(); 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::>(); 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::>(); 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::>(); 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 50d4cbc982e9..1b2976b7435d 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 be6594320244..5e3925b0b3c9 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) -> P { 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/lint/context.rs b/src/librustc/lint/context.rs index cf4115e37cd9..20463f42d3b1 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> { - 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> { - let mut out = vec!(); + let mut out = vec![]; let level = match Level::from_str(&attr.name()) { None => return out, diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 078cce9c49ff..3175230ab6a5 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 { 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 7b5413984a20..87a5c6410a84 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 ce3f2be54b2d..1ce5b223fbef 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -272,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(); diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs index f1f1658cc824..ce882c48377f 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/ty/walk.rs b/src/librustc/ty/walk.rs index dd3a62f7cd2d..bebdebf127a5 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 0557660e98c2..1135199d2254 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_back/target/dragonfly_base.rs b/src/librustc_back/target/dragonfly_base.rs index e2c4003a8b6e..7555181a15cf 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 e2c4003a8b6e..7555181a15cf 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 a98a33feb5e9..891e7dda14a2 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 cc03ed56aa4d..6e038a7ed56e 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 7afdfcd69113..90e6631841be 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 c398ee40f2f9..19ca0df51b9d 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 9fbf1492f5d2..47f8d978704f 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>) 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/move_data.rs b/src/librustc_borrowck/borrowck/move_data.rs index e9ba406389f8..ba036f1a8b15 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>) -> Vec { - 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 092638cdee26..db72057636a8 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> = vec!(Some(1), None); +let xs : Vec> = 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> = vec!(Some(1), None); +let xs : Vec> = 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> = vec!(Some(1), None); +let xs : Vec> = vec![Some(1), None]; for item in xs { if let Some(x) = item { diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index f4558a2871d1..e72ac8419941 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 9c74a644c3d9..88e248e2efa3 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_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 73d0e5e50c6c..8a628289b7f9 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 22c087aba80f..031b9a6a5aa5 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 { - let mut result: Vec = vec!(); + let mut result: Vec = 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/asm.rs b/src/librustc_trans/asm.rs index 308118b1fbc6..8c704cc32993 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 4ed860bd40d8..8758cdcf9d0a 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 { 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 04b814e2b977..9012914deeb0 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 d368ce47430b..b9f24eba9dc1 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/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index cbe3893fbf67..7d2547ec17f3 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 40b19b01cd90..202e176df0db 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 7752690e534b..c16dd788c4ec 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -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, }), diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 5ce758100062..f03b6a5ab3f1 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 f12349e5b7c6..67cf12f4f4a6 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 77a5ff3243a6..a848a011f88d 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 305e6258baa4..a7da1c5cca48 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 0be36eb3a850..cf5e8e5e34a3 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 { 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 { 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 45c3d413500b..1bbd67fb9be3 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, 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 3e976c906283..239d32c8fc8d 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/io/cursor.rs b/src/libstd/io/cursor.rs index ca9452ffe3ec..cb9e7bd32702 100644 --- a/src/libstd/io/cursor.rs +++ b/src/libstd/io/cursor.rs @@ -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/rand/mod.rs b/src/libstd/rand/mod.rs index 69cd37651d5c..f48325218fb4 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/libsyntax/ast.rs b/src/libsyntax/ast.rs index 8864694c932f..f077ead1f8e0 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 0ef47bd6daaa..37bd83be7b4d 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::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> { 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) -> P { 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 { @@ -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 { @@ -812,12 +812,12 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn expr_ok(&self, sp: Span, expr: P) -> P { 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) -> P { 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) -> P { @@ -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>, expr: P) -> 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, arms: Vec) -> P { @@ -970,7 +970,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn lambda1(&self, span: Span, blk: P, ident: ast::Ident) -> P { - self.lambda(span, vec!(ident), blk) + self.lambda(span, vec![ident], blk) } fn lambda_expr(&self, span: Span, ids: Vec, diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index f3497c130bff..f21360755bc2 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { 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 { - 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 { - 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 { - 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 { 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 { 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 { 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 { - 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 { - 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 { } 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 { 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 Vec { let mut seq = vec![]; @@ -737,13 +737,13 @@ fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, matcher: bool) -> Vec { 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 Vec { 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 { @@ -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 7b67c23e1023..12408c7d3c95 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 a75937759a2a..b80aa667be6a 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 149112133b23..b0bd64467430 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 fdc1f45623d9..618878c1f798 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -430,7 +430,7 @@ fn mk_std(cx: &TestCtxt) -> P { 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 57258c76335a..9be7dbd68174 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -105,7 +105,7 @@ impl SmallVector { 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 64b8829dad7b..c46d4b34173f 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 99d60c43c545..597ff306b3dd 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 22b9eb8e7544..10db56d46f6d 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 a4074184b6e8..640296d7f06f 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/mod.rs b/src/libsyntax_ext/deriving/mod.rs index 67747173353d..c2bfead56861 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 8b0fd1ca0cbf..95ae6eb2efe8 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -336,7 +336,7 @@ pub type OptRes = Result; #[cfg_attr(rustfmt, rustfmt_skip)] fn optgroups() -> Vec { - 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::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 32c129b22a16..5792ba06eb0c 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> = vec!(Some(1), None); + let xs : Vec> = 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 f0f0bdfb38ee..324e92596477 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 b18df7f3db60..1e665a12a195 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 7b811f581c1a..9178aadeeebe 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 21d9dea77b26..c5de95f8fc04 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(_v: &isize, f: F) where F: FnOnce() { } fn has_mut_vec_and_does_not_try_to_change_it() { - let mut v: Vec = vec!(1, 2, 3); + let mut v: Vec = vec![1, 2, 3]; takes_imm_elt(&v[0], || {}) } fn has_mut_vec_but_tries_to_change_it() { - let mut v: Vec = vec!(1, 2, 3); + let mut v: Vec = 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 27cef1f3c606..bf4c74741368 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 51e00a0ad2c3..311208f07b88 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 9341758afd82..4e0304e20c00 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 1b62d9c326d7..df72c2b0af72 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 Index for MyVec { } fn main() { - let v = MyVec::> { data: vec!(box 1, box 2, box 3) }; + let v = MyVec::> { 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 63e80b90ac81..eb5d69d49bd6 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 9dfd4d779284..505c8c6d5358 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 ae001e4e34d1..d26364efdbc5 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] = &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] = &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] = &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] = &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 a849e4e2faf3..cd8f3ebefe62 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 e6e1364dd2ca..33e4d3e62c41 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 = vec!("foo ".to_string(), " bar".to_string()); + let raw_lines: Vec = 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 897aca66cbfd..c8f33c3caf8d 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 = vec!(0, 1, 2, 3, 4, 5); + let v: Vec = 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 38956944f63e..4618851529a1 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 53d148628898..6ad3ec67b296 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 b934cbe4b5d8..c7b276da5737 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 = vec!('a', 'f'); + let needlesArr: Vec = 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 b7b5553dc74e..1c543a5fdacb 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 8165dd0fa29c..21cfadb9c799 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) 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 57e3a58b5660..4d9b3aea1124 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 = vec!('a', 'b', 'c'); + let x: Vec = 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 b8572fbd2150..63fb4ff02a4e 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) {} 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 9ad44567a41f..194f278259b6 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 7b7b3c414dde..5e1d22bf63b8 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 1720b40c83bb..76c8a444320d 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 fd245f38a0c9..6067b71280ce 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 = &vec!(1,2,3); + let x : *const Vec = &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 017baacc9d32..74e728d713b1 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] = &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] = &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 ef7695af3e12..3a789f3faeb2 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, B: MyFromIterator>(it: I) -> B { } pub fn main() { - let x = vec!(1u8, 2, 3, 4); + let x = vec![1u8, 2, 3, 4]; let y: Option> = collect(x.iter()); // this should give approximately the same error for x.iter().collect() //~^ ERROR //~^^ NOTE a collection of type `std::option::Option>` cannot be built from an iterator over elements of type `&u8` diff --git a/src/test/compile-fail/regions-escape-loop-via-vec.rs b/src/test/compile-fail/regions-escape-loop-via-vec.rs index f5ea7a2108e7..8982b5cd98de 100644 --- a/src/test/compile-fail/regions-escape-loop-via-vec.rs +++ b/src/test/compile-fail/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/compile-fail/unboxed-closures-failed-recursive-fn-2.rs b/src/test/compile-fail/unboxed-closures-failed-recursive-fn-2.rs index f40c8fc74749..12b48b2a6c8a 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 e66610c14960..cd9f1636c3f4 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) 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 346cf1ec555d..96f58666fdff 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 023ef72c453b..571634e39926 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 = vec!(); + let mut xs: Vec = 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 cf64486c9c7b..27f6fc51164a 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 09c9439b464e..f289b85992ee 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 = vec!(1, 2, 3); + let v: Vec = 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 3b2d372117d0..d334e33f887b 100644 --- a/src/test/debuginfo/issue14411.rs +++ b/src/test/debuginfo/issue14411.rs @@ -20,6 +20,6 @@ fn test(a: &Vec) { } pub fn main() { - let data = vec!(); + let data = vec![]; test(&data); } diff --git a/src/test/parse-fail/issue-10412.rs b/src/test/parse-fail/issue-10412.rs index fc2598d1e9d2..d723d94c02cc 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 for &'self str { //~ ERROR lifetimes cannot use keyword names //~^ ERROR lifetimes cannot use keyword names fn serialize(val : &'self str) -> Vec { //~ 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 5f88f9036780..c645a66b70ef 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 { if true { } vec!(1, 2) } +fn test11() -> Vec { 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 956f789dab83..e750d1fb1e3e 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 c364240f4ad6..bc95d96a8cc9 100644 --- a/src/test/run-pass/assignability-trait.rs +++ b/src/test/run-pass/assignability-trait.rs @@ -38,7 +38,7 @@ fn length>(x: T) -> usize { } pub fn main() { - let x: Vec = vec!(0,1,2,3); + let x: Vec = 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 1661812520b3..dd194447740b 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>) -> 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 be854f820d4d..abd4917cae87 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>(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 babc0db4c319..b0afae79c369 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 5b12edb42756..f6cb314d06e2 100644 --- a/src/test/run-pass/auto-ref-sliceable.rs +++ b/src/test/run-pass/auto-ref-sliceable.rs @@ -21,7 +21,7 @@ impl Pushable for Vec { } 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 1f3d17ad55c0..ed0b9eca0e05 100644 --- a/src/test/run-pass/autobind.rs +++ b/src/test/run-pass/autobind.rs @@ -12,7 +12,7 @@ fn f(x: Vec) -> T { return x.into_iter().next().unwrap(); } -fn g(act: F) -> isize where F: FnOnce(Vec) -> isize { return act(vec!(1, 2, 3)); } +fn g(act: F) -> isize where F: FnOnce(Vec) -> 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 2f530331a2bd..7fca4bccab3f 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 052b60539314..44f4a54610a9 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 187063968f7f..b6c2a3a61ea4 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 d55517c65d66..4699f376313b 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 { } 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 ea136e2dc485..9a32fbc10314 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 9f7b98a57fce..ad779d26f9e4 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 cc76ed530c4b..b105411c284a 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 4d247bde190d..7d266181c9eb 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 = cat::(52_usize, 99, vec!('p')); - let mut kitty = cat(1000_usize, 2, vec!("tabby".to_string())); + let mut nyan : cat = cat::(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 2528ff5128f9..5da858e3c409 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(in_x : usize, in_y : isize, in_info: Vec ) -> cat { } pub fn main() { - let mut nyan : cat = cat::(52, 99, vec!(9)); - let mut kitty = cat(1000, 2, vec!("tabby".to_string())); + let mut nyan : cat = cat::(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 25d3eb3bbe28..c401b529c30d 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 { vec!(x * 2) } +fn get_bar(x: usize) -> Vec { 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 4e116ae14669..e86f20694e10 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 { } 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 ce0bc33905fe..ca4ee4a97d52 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 066b33e007b8..f35735adbcfe 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 b23075e6d0af..adc3e3efd70d 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 cb3712dea322..53005ea5291f 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 aeca388d317b..cc9a2e60dece 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 { vec!(10, 11) } + fn f() -> Vec { 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 89dc7b09c7b1..1a6466048d90 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 963d34a2d2fb..ba78ff4d5393 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 60068185f5a5..2c4d0cc7648c 100644 --- a/src/test/run-pass/foreach-nested.rs +++ b/src/test/run-pass/foreach-nested.rs @@ -13,7 +13,7 @@ fn two(mut it: F) where F: FnMut(isize) { it(0); it(1); } pub fn main() { - let mut a: Vec = vec!(-1, -1, -1, -1); + let mut a: Vec = 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 eb0546063f71..d439c6238018 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 { 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 7a496ebf8ce3..ad501ec7e9ba 100644 --- a/src/test/run-pass/generic-static-methods.rs +++ b/src/test/run-pass/generic-static-methods.rs @@ -25,5 +25,5 @@ impl vec_utils for Vec { } 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 c9595d09e21b..90726c21fac4 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 8efc4cb1b172..2306fa9afa2e 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 a9cfe7a38026..1e1fde4d1e2b 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 c9af2b190b21..2a7a593d2680 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 36f606e5d73c..13e8fe0e964c 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 428d4e4dbb12..8a628b73c006 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 cee0caeb465f..14e003788469 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 35faa5789a9c..54b96d663074 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 66b0aeeb988d..daf14b4c2ffc 100644 --- a/src/test/run-pass/issue-15734.rs +++ b/src/test/run-pass/issue-15734.rs @@ -54,7 +54,7 @@ impl> Index for Row { } 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 365b594c99e3..913b07613e03 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::(&m); diff --git a/src/test/run-pass/issue-2723-b.rs b/src/test/run-pass/issue-2723-b.rs index bab7b0d24db7..a6ba957a1b11 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 2a932cd7756d..992fbdce2689 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, U, F>( where F: Fn(&mut StreamParser) -> 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 8b6eb12f102e..a4342f33402d 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 { struct Storage { storage: Vec } 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 26558bdd30c3..70e3484a0c57 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-6153.rs b/src/test/run-pass/issue-6153.rs index 16e7060f4b9f..1b16418ac425 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) -> Vec where F: FnOnce(Vec) -> Vec { - 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 5b40105a9791..e3b42e60645a 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 ) { } -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 b8238774bc1e..a511db8e9397 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>) { 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 fca700f6e4a8..5109c6fc7772 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 , 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 3da2fc8ceacf..fc6d435b034b 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 d8a69177cafc..b54b4692a41b 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 0c1e7916cdb1..6916bfb8c616 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 a10f9b1d7d61..3d221927b96e 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 b28e5ec64de3..211827f92222 100644 --- a/src/test/run-pass/monad.rs +++ b/src/test/run-pass/monad.rs @@ -45,9 +45,9 @@ fn transform(x: Option) -> Option { 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 bed339e15863..0ff5a66adc26 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> ) { 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 a6a26ab35787..8de487bc3631 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>) { 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 91599608ceed..e7da8d7bf93c 100644 --- a/src/test/run-pass/newtype-polymorphic.rs +++ b/src/test/run-pass/newtype-polymorphic.rs @@ -24,7 +24,7 @@ fn myvec_elt(mv: myvec) -> 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 dffdcfe0af56..7e8d082a286a 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); check_type!("foo".to_string(), String); - check_type!(vec!(20, 22), Vec); + check_type!(vec![20, 22], Vec); 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 176f67fd3a18..768f126e4edf 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> = vec!( + let foos: Vec> = vec![ box BarStruct{ x: 0 } as Box, box BarStruct{ x: 1 } as Box, box BarStruct{ x: 2 } as Box - ); + ]; 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 8541c1c0a898..e2ca880719a8 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 1ec16747181c..efa73ad92ce8 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 ec1f4eda28cc..e61a8d147757 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 a6a179c432c3..e9a3e16438f8 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 7183937fe803..cd140f7aa599 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 f9ba8e82ef71..262e936826e5 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(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 465f43e36b94..8eee54b3fec6 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 f1a21d90ab2d..43612f529772 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 007ce52d7c45..13d55e0172e7 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(v: Vec> ) { } pub fn main() { - let v: Vec> = vec!(clam::b::, clam::b::, clam::a::(42, 17)); + let v: Vec> = vec![clam::b::, clam::b::, clam::a::(42, 17)]; uhoh::(v); } diff --git a/src/test/run-pass/static-impl.rs b/src/test/run-pass/static-impl.rs index 84bb1b871b97..89fd83ced4c8 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_::(|a| *a as usize + 4_usize); + let vect = (vec![3, 4]).map_::(|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 3dbd7f1a6012..4601b7d7cf56 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 = vec!(0, 1, 2, 3, 4, 5, 6); + let mut a: Vec = 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 c6d8f3c0d9b0..0caf21ead396 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 = vec!(0, 1, 2); + let v0: Vec = 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 f7fd86c95707..9877dffe9df0 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, + let arc = Arc::new(vec![box catte as Box, box dogge1 as Box, box fishe as Box, - box dogge2 as Box)); + box dogge2 as Box]); 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 499823662915..eadda5dfe299 100644 --- a/src/test/run-pass/trait-generic.rs +++ b/src/test/run-pass/trait-generic.rs @@ -45,9 +45,9 @@ fn bar>(x: T) -> Vec { } pub fn main() { - assert_eq!(foo(vec!(1)), ["hi".to_string()]); - assert_eq!(bar:: >(vec!(4, 5)), ["4".to_string(), "5".to_string()]); - assert_eq!(bar:: >(vec!("x".to_string(), "y".to_string())), + assert_eq!(foo(vec![1]), ["hi".to_string()]); + assert_eq!(bar:: >(vec![4, 5]), ["4".to_string(), "5".to_string()]); + assert_eq!(bar:: >(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 f5af05d872bd..9671e31d7e48 100644 --- a/src/test/run-pass/trait-to-str.rs +++ b/src/test/run-pass/trait-to-str.rs @@ -30,15 +30,15 @@ impl to_str for Vec { 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(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(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 0b85916d2241..300a0ee63f81 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) 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 99663646254e..b9a16535c420 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) 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 c68ff1f0612f..1ef61008b3c2 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 8469ae702009..6d638bbf562c 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 056acd162082..1910d51bd0bc 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 ab0e3ee809db..ece206caa02e 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> = vec!(box 10); + let mut a: Vec> = 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 026bc0435d91..bd965d41eea2 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> = vec!(box 100); + let vect : Vec> = 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 0f751501293f..0a984429fabb 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 = vec!('e', 'é', '€', '\u{10000}'); + let chs: Vec = vec!['e', 'é', '€', '\u{10000}']; let s: String = chs.iter().cloned().collect(); let schs: Vec = s.chars().collect(); diff --git a/src/test/run-pass/vec-concat.rs b/src/test/run-pass/vec-concat.rs index 5fe9dd60591c..8ba8df57e542 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 = vec!(1, 2, 3, 4, 5); - let b: Vec = vec!(6, 7, 8, 9, 0); + let a: Vec = vec![1, 2, 3, 4, 5]; + let b: Vec = vec![6, 7, 8, 9, 0]; let mut v: Vec = 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 e51d898e1d46..5bf6a457df9b 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 7a8c0739efeb..420f6a429f1f 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 ; - 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 35af249ef5fa..135ecb474984 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 33f01c5bd41c..14a52cc4b5c5 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 f000ada770a4..1fed6a0be486 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 c61b3d56dbfb..9cacb9db20ea 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 = vec!(10, 20); + let v: Vec = 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 ed149ad5109d..4c599e9c4289 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 = - 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/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index e6efd45cad18..2dc7cdbf9350 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 ) -> Config { let groups : Vec = - 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 ) -> 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 e10420bf291e..03c05f919b79 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 36a37dba1fa0..c5f72127a9c8 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> } } - 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> 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 { From e3025a07338eca4092f96c16011caccee149c8d4 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Mon, 31 Oct 2016 16:37:13 -0400 Subject: [PATCH 44/62] ICH: Hash expression spans if their source location is captured for panics --- .../calculate_svh/svh_visitor.rs | 138 ++++++++++---- src/test/incremental/hashes/panic_exprs.rs | 173 ++++++++++++++++++ 2 files changed, 276 insertions(+), 35 deletions(-) create mode 100644 src/test/incremental/hashes/panic_exprs.rs diff --git a/src/librustc_incremental/calculate_svh/svh_visitor.rs b/src/librustc_incremental/calculate_svh/svh_visitor.rs index 51c894e1b78f..80c41f855ba5 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/test/incremental/hashes/panic_exprs.rs b/src/test/incremental/hashes/panic_exprs.rs new file mode 100644 index 000000000000..f5f4c0042b43 --- /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 or the MIT license +// , 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 +} From 6720e0191cc7a735b9991a955c7acf26cbab3c49 Mon Sep 17 00:00:00 2001 From: Mark-Simulacrum Date: Tue, 1 Nov 2016 09:47:09 -0600 Subject: [PATCH 45/62] Add tracking issue number to Result::unwrap_or_default unstable annotation. --- src/libcore/result.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 3d34f6200678..9ba5ff7c3a46 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -821,7 +821,7 @@ impl Result { /// [`FromStr`]: ../../std/str/trait.FromStr.html /// ``` #[inline] - #[unstable(feature = "result_unwrap_or_default", issue = "0")] + #[unstable(feature = "result_unwrap_or_default", issue = "37516")] pub fn unwrap_or_default(self) -> T { match self { Ok(x) => x, From a0e7e357a796f93527d0a0e850fa71c48594b91d Mon Sep 17 00:00:00 2001 From: Mikhail Modin Date: Wed, 26 Oct 2016 19:10:39 +0300 Subject: [PATCH 46/62] Improve "Doesn't live long enough" error case with different lifetime with spans --- src/librustc_borrowck/borrowck/mod.rs | 13 +++++ .../span}/borrowck-ref-into-rvalue.rs | 0 .../ui/span/borrowck-ref-into-rvalue.stderr | 16 ++++++ .../span}/destructor-restrictions.rs | 0 .../ui/span/destructor-restrictions.stderr | 12 ++++ src/test/ui/span/issue-11925.stderr | 4 +- ...338-locals-die-before-temps-of-body.stderr | 8 +-- .../span}/mut-ptr-cant-outlive-ref.rs | 0 .../ui/span/mut-ptr-cant-outlive-ref.stderr | 12 ++++ src/test/{compile-fail => ui/span}/range-2.rs | 0 src/test/ui/span/range-2.stderr | 24 ++++++++ .../regionck-unboxed-closure-lifetimes.rs | 0 .../regionck-unboxed-closure-lifetimes.stderr | 13 +++++ .../regions-close-over-type-parameter-2.rs | 0 ...regions-close-over-type-parameter-2.stderr | 13 +++++ .../span}/regions-escape-loop-via-variable.rs | 0 .../regions-escape-loop-via-variable.stderr | 12 ++++ .../span}/regions-escape-loop-via-vec.rs | 0 .../span/regions-escape-loop-via-vec.stderr | 41 ++++++++++++++ .../regions-infer-borrow-scope-within-loop.rs | 0 ...ions-infer-borrow-scope-within-loop.stderr | 14 +++++ .../send-is-not-static-ensures-scoping.rs | 0 .../send-is-not-static-ensures-scoping.stderr | 28 ++++++++++ .../span}/send-is-not-static-std-sync-2.rs | 0 .../span/send-is-not-static-std-sync-2.stderr | 36 ++++++++++++ .../span}/send-is-not-static-std-sync.rs | 0 .../span/send-is-not-static-std-sync.stderr | 56 +++++++++++++++++++ .../span}/wf-method-late-bound-regions.rs | 0 .../span/wf-method-late-bound-regions.stderr | 13 +++++ 29 files changed, 309 insertions(+), 6 deletions(-) rename src/test/{compile-fail/borrowck => ui/span}/borrowck-ref-into-rvalue.rs (100%) create mode 100644 src/test/ui/span/borrowck-ref-into-rvalue.stderr rename src/test/{compile-fail => ui/span}/destructor-restrictions.rs (100%) create mode 100644 src/test/ui/span/destructor-restrictions.stderr rename src/test/{compile-fail => ui/span}/mut-ptr-cant-outlive-ref.rs (100%) create mode 100644 src/test/ui/span/mut-ptr-cant-outlive-ref.stderr rename src/test/{compile-fail => ui/span}/range-2.rs (100%) create mode 100644 src/test/ui/span/range-2.stderr rename src/test/{compile-fail => ui/span}/regionck-unboxed-closure-lifetimes.rs (100%) create mode 100644 src/test/ui/span/regionck-unboxed-closure-lifetimes.stderr rename src/test/{compile-fail => ui/span}/regions-close-over-type-parameter-2.rs (100%) create mode 100644 src/test/ui/span/regions-close-over-type-parameter-2.stderr rename src/test/{compile-fail => ui/span}/regions-escape-loop-via-variable.rs (100%) create mode 100644 src/test/ui/span/regions-escape-loop-via-variable.stderr rename src/test/{compile-fail => ui/span}/regions-escape-loop-via-vec.rs (100%) create mode 100644 src/test/ui/span/regions-escape-loop-via-vec.stderr rename src/test/{compile-fail => ui/span}/regions-infer-borrow-scope-within-loop.rs (100%) create mode 100644 src/test/ui/span/regions-infer-borrow-scope-within-loop.stderr rename src/test/{compile-fail => ui/span}/send-is-not-static-ensures-scoping.rs (100%) create mode 100644 src/test/ui/span/send-is-not-static-ensures-scoping.stderr rename src/test/{compile-fail => ui/span}/send-is-not-static-std-sync-2.rs (100%) create mode 100644 src/test/ui/span/send-is-not-static-std-sync-2.stderr rename src/test/{compile-fail => ui/span}/send-is-not-static-std-sync.rs (100%) create mode 100644 src/test/ui/span/send-is-not-static-std-sync.stderr rename src/test/{compile-fail => ui/span}/wf-method-late-bound-regions.rs (100%) create mode 100644 src/test/ui/span/wf-method-late-bound-regions.stderr diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index ef6936b6e7db..0d084d9b930d 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -1064,6 +1064,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/test/compile-fail/borrowck/borrowck-ref-into-rvalue.rs b/src/test/ui/span/borrowck-ref-into-rvalue.rs similarity index 100% rename from src/test/compile-fail/borrowck/borrowck-ref-into-rvalue.rs rename to 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 000000000000..adbf39b3f758 --- /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 similarity index 100% rename from src/test/compile-fail/destructor-restrictions.rs rename to 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 000000000000..3253212c5b87 --- /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 3fedb2884bc5..6ad9c27b8b91 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 f10ba0bf2210..85a0002f2418 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/compile-fail/mut-ptr-cant-outlive-ref.rs b/src/test/ui/span/mut-ptr-cant-outlive-ref.rs similarity index 100% rename from src/test/compile-fail/mut-ptr-cant-outlive-ref.rs rename to 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 000000000000..0417eb075af8 --- /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 similarity index 100% rename from src/test/compile-fail/range-2.rs rename to 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 000000000000..9f11de77be7e --- /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 similarity index 100% rename from src/test/compile-fail/regionck-unboxed-closure-lifetimes.rs rename to 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 000000000000..9c369e03e33a --- /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 similarity index 100% rename from src/test/compile-fail/regions-close-over-type-parameter-2.rs rename to 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 000000000000..ea652da7da46 --- /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 similarity index 100% rename from src/test/compile-fail/regions-escape-loop-via-variable.rs rename to 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 000000000000..09f2154905f3 --- /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 similarity index 100% rename from src/test/compile-fail/regions-escape-loop-via-vec.rs rename to src/test/ui/span/regions-escape-loop-via-vec.rs 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 000000000000..58f7849e443f --- /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 similarity index 100% rename from src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs rename to 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 000000000000..0e7b64ec2b36 --- /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 similarity index 100% rename from src/test/compile-fail/send-is-not-static-ensures-scoping.rs rename to 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 000000000000..5897921476d3 --- /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 similarity index 100% rename from src/test/compile-fail/send-is-not-static-std-sync-2.rs rename to 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 000000000000..08f85f17bf8a --- /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 similarity index 100% rename from src/test/compile-fail/send-is-not-static-std-sync.rs rename to 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 000000000000..a86cf1e58846 --- /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 similarity index 100% rename from src/test/compile-fail/wf-method-late-bound-regions.rs rename to 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 000000000000..aeac3102fbf3 --- /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 + From 568840707cd5f98a1970a44d632b833439d5312e Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 30 Sep 2016 20:13:58 +0000 Subject: [PATCH 47/62] std: Move elf TLS to sys::fast_thread_local --- src/libstd/sys/unix/fast_thread_local.rs | 167 +++++++++++++++++++++++ src/libstd/sys/unix/mod.rs | 1 + src/libstd/thread/local.rs | 163 +--------------------- src/libstd/thread/mod.rs | 2 +- src/tools/tidy/src/pal.rs | 1 - 5 files changed, 171 insertions(+), 163 deletions(-) create mode 100644 src/libstd/sys/unix/fast_thread_local.rs 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 000000000000..0c625e7add9d --- /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 or the MIT license +// , 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 { + inner: UnsafeCell>, + + // Metadata to keep track of the state of the destructor. Remember that + // these variables are thread-local, not global. + dtor_registered: Cell, + dtor_running: Cell, +} + +unsafe impl ::marker::Sync for Key { } + +impl Key { + pub const fn new() -> Key { + Key { + inner: UnsafeCell::new(None), + dtor_registered: Cell::new(false), + dtor_running: Cell::new(false) + } + } + + pub fn get(&'static self) -> Option<&'static UnsafeCell>> { + unsafe { + if intrinsics::needs_drop::() && self.dtor_running.get() { + return None + } + self.register_dtor(); + } + Some(&self.inner) + } + + unsafe fn register_dtor(&self) { + if !intrinsics::needs_drop::() || self.dtor_registered.get() { + return + } + + register_dtor(self as *const _ as *mut u8, + destroy_value::); + 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 = 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 = 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(ptr: *mut u8) { + let ptr = ptr as *mut Key; + // 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 66bc9d4a4915..0e28426b32f2 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; diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index 54d3f7930456..f74dd5924951 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 LocalKey { } } -#[cfg(target_thread_local)] -#[doc(hidden)] -pub mod elf { - use cell::{Cell, UnsafeCell}; - use intrinsics; - use ptr; - - pub struct Key { - inner: UnsafeCell>, - - // Metadata to keep track of the state of the destructor. Remember that - // these variables are thread-local, not global. - dtor_registered: Cell, - dtor_running: Cell, - } - - unsafe impl ::marker::Sync for Key { } - - impl Key { - pub const fn new() -> Key { - Key { - inner: UnsafeCell::new(None), - dtor_registered: Cell::new(false), - dtor_running: Cell::new(false) - } - } - - pub fn get(&'static self) -> Option<&'static UnsafeCell>> { - unsafe { - if intrinsics::needs_drop::() && self.dtor_running.get() { - return None - } - self.register_dtor(); - } - Some(&self.inner) - } - - unsafe fn register_dtor(&self) { - if !intrinsics::needs_drop::() || self.dtor_registered.get() { - return - } - - register_dtor(self as *const _ as *mut u8, - destroy_value::); - 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 = 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 = 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(ptr: *mut u8) { - let ptr = ptr as *mut Key; - // 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 150482e4af45..4c3980b3c7b3 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -183,7 +183,7 @@ pub use self::local::{LocalKey, LocalKeyState}; #[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/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 1d04e8fc8eb7..80a2d22691b8 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -69,7 +69,6 @@ const EXCEPTION_PATHS: &'static [&'static str] = &[ "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", From 8b2600dbf9a02a19acc92db5d980986cad2ea38d Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Tue, 4 Oct 2016 18:00:27 +0000 Subject: [PATCH 48/62] Document reasoning for supporting both fast and OS TLS in the same bin --- src/libstd/thread/mod.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 4c3980b3c7b3..255cd2a9bc0f 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -181,6 +181,15 @@ 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 sys::fast_thread_local::Key as __FastLocalKeyInner; From 6d54cd4b2cd864fbd6f2f8d036903f88b6ea79b4 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 30 Sep 2016 21:01:53 +0000 Subject: [PATCH 49/62] std: Move a plattform-specific constant to sys::stdio --- src/libstd/io/mod.rs | 2 +- src/libstd/io/stdio.rs | 10 +--------- src/libstd/sys/common/io.rs | 2 ++ src/libstd/sys/unix/stdio.rs | 1 + src/libstd/sys/windows/stdio.rs | 5 +++++ src/tools/tidy/src/pal.rs | 1 - 6 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 37c3f70d54dd..193f396c0d4a 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 c24ee8ff303c..1777b79ea1b5 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/sys/common/io.rs b/src/libstd/sys/common/io.rs index 0483725dd83b..23daeeb5187b 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/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs index 947ba2cc7523..273341b1918d 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/stdio.rs b/src/libstd/sys/windows/stdio.rs index 5f097d2631d9..72788776dedd 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/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 80a2d22691b8..6ce5f7ee7fe2 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -66,7 +66,6 @@ const EXCEPTION_PATHS: &'static [&'static str] = &[ "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/sys/common/mod.rs", From 219c018894b31fec7059ca89bb1ab0606068aeaf Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 30 Sep 2016 22:11:46 +0000 Subject: [PATCH 50/62] std: Move platform-specific code out of libstd/lib.rs --- src/libstd/lib.rs | 5 +---- src/libstd/sys/mod.rs | 19 +++++++++++++++++++ src/libstd/sys/windows/mod.rs | 6 +++--- src/tools/tidy/src/pal.rs | 6 +++--- 4 files changed, 26 insertions(+), 10 deletions(-) create mode 100644 src/libstd/sys/mod.rs diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index e470690b7c6b..1d6c2403c2fe 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -458,10 +458,7 @@ mod memchr; #[macro_use] #[path = "sys/common/mod.rs"] mod sys_common; -#[cfg(unix)] -#[path = "sys/unix/mod.rs"] mod sys; -#[cfg(windows)] -#[path = "sys/windows/mod.rs"] mod sys; +mod sys; pub mod rt; mod panicking; diff --git a/src/libstd/sys/mod.rs b/src/libstd/sys/mod.rs new file mode 100644 index 000000000000..f7e1a0a075a8 --- /dev/null +++ b/src/libstd/sys/mod.rs @@ -0,0 +1,19 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use self::imp::*; + +#[cfg(unix)] +#[path = "unix/mod.rs"] +mod imp; + +#[cfg(windows)] +#[path = "windows/mod.rs"] +mod imp; diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 9cd6e6ca1761..0610a0245ea6 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: I) -> io::Result { +pub fn cvt(i: I) -> io::Result { if i.is_zero() { Err(io::Error::last_os_error()) } else { @@ -201,7 +201,7 @@ fn cvt(i: I) -> io::Result { } } -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: diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 6ce5f7ee7fe2..5caa7f8af440 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -57,13 +57,13 @@ 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/unix", // This is where platform-specific code for unix + "src/libstd/sys/windows", // Ditto for windows + "src/libstd/sys/mod.rs", // This file chooses the platform "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/num/f32.rs", From f3a709dc52bb3e617ccb016a8b20a741c23da77d Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 30 Sep 2016 23:07:04 +0000 Subject: [PATCH 51/62] std: Move platform-specific out of sys_common::util --- src/libstd/sys/common/util.rs | 28 +--------------------------- src/libstd/sys/unix/mod.rs | 11 +++++++++++ src/libstd/sys/windows/mod.rs | 14 ++++++++++++++ src/tools/tidy/src/pal.rs | 1 - 4 files changed, 26 insertions(+), 28 deletions(-) diff --git a/src/libstd/sys/common/util.rs b/src/libstd/sys/common/util.rs index b5d035763387..daa0c15920b6 100644 --- a/src/libstd/sys/common/util.rs +++ b/src/libstd/sys/common/util.rs @@ -33,32 +33,6 @@ pub fn dumb_print(args: fmt::Arguments) { let _ = Stderr::new().map(|mut stderr| stderr.write_fmt(args)); } -// 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 @@ -66,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/unix/mod.rs b/src/libstd/sys/unix/mod.rs index 0e28426b32f2..fd7dc17cccd8 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -163,3 +163,14 @@ pub fn cvt_r(mut f: F) -> io::Result } } } + +// 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/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 0610a0245ea6..defc41c5f46a 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -221,3 +221,17 @@ pub 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/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 5caa7f8af440..68b0c819c5a8 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -70,7 +70,6 @@ const EXCEPTION_PATHS: &'static [&'static str] = &[ "src/libstd/num/f64.rs", "src/libstd/sys/common/mod.rs", "src/libstd/sys/common/net.rs", - "src/libstd/sys/common/util.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 From ca30691813836e1c6896e5ba5d4397eb717e7270 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 30 Sep 2016 23:26:44 +0000 Subject: [PATCH 52/62] std: Move sys_common to libstd/sys_common Make the directory structure reflect the module structure. I've always found the existing structure confusing. --- src/libstd/lib.rs | 3 +-- src/libstd/{sys/common => sys_common}/at_exit_imp.rs | 0 src/libstd/{sys/common => sys_common}/backtrace.rs | 0 src/libstd/{sys/common => sys_common}/condvar.rs | 0 .../{sys/common => sys_common}/gnu/libbacktrace.rs | 0 src/libstd/{sys/common => sys_common}/gnu/mod.rs | 0 src/libstd/{sys/common => sys_common}/io.rs | 0 src/libstd/{sys/common => sys_common}/memchr.rs | 0 src/libstd/{sys/common => sys_common}/mod.rs | 0 src/libstd/{sys/common => sys_common}/mutex.rs | 0 src/libstd/{sys/common => sys_common}/net.rs | 0 src/libstd/{sys/common => sys_common}/poison.rs | 0 src/libstd/{sys/common => sys_common}/remutex.rs | 0 src/libstd/{sys/common => sys_common}/rwlock.rs | 0 src/libstd/{sys/common => sys_common}/thread.rs | 0 src/libstd/{sys/common => sys_common}/thread_info.rs | 0 src/libstd/{sys/common => sys_common}/thread_local.rs | 0 src/libstd/{sys/common => sys_common}/util.rs | 0 src/libstd/{sys/common => sys_common}/wtf8.rs | 0 src/tools/tidy/src/pal.rs | 9 ++++----- 20 files changed, 5 insertions(+), 7 deletions(-) rename src/libstd/{sys/common => sys_common}/at_exit_imp.rs (100%) rename src/libstd/{sys/common => sys_common}/backtrace.rs (100%) rename src/libstd/{sys/common => sys_common}/condvar.rs (100%) rename src/libstd/{sys/common => sys_common}/gnu/libbacktrace.rs (100%) rename src/libstd/{sys/common => sys_common}/gnu/mod.rs (100%) rename src/libstd/{sys/common => sys_common}/io.rs (100%) rename src/libstd/{sys/common => sys_common}/memchr.rs (100%) rename src/libstd/{sys/common => sys_common}/mod.rs (100%) rename src/libstd/{sys/common => sys_common}/mutex.rs (100%) rename src/libstd/{sys/common => sys_common}/net.rs (100%) rename src/libstd/{sys/common => sys_common}/poison.rs (100%) rename src/libstd/{sys/common => sys_common}/remutex.rs (100%) rename src/libstd/{sys/common => sys_common}/rwlock.rs (100%) rename src/libstd/{sys/common => sys_common}/thread.rs (100%) rename src/libstd/{sys/common => sys_common}/thread_info.rs (100%) rename src/libstd/{sys/common => sys_common}/thread_local.rs (100%) rename src/libstd/{sys/common => sys_common}/util.rs (100%) rename src/libstd/{sys/common => sys_common}/wtf8.rs (100%) diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 1d6c2403c2fe..3eb828810909 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -456,8 +456,7 @@ pub mod time; mod memchr; #[macro_use] -#[path = "sys/common/mod.rs"] mod sys_common; - +mod sys_common; mod sys; pub mod rt; diff --git a/src/libstd/sys/common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs similarity index 100% rename from src/libstd/sys/common/at_exit_imp.rs rename to src/libstd/sys_common/at_exit_imp.rs diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys_common/backtrace.rs similarity index 100% rename from src/libstd/sys/common/backtrace.rs rename to src/libstd/sys_common/backtrace.rs diff --git a/src/libstd/sys/common/condvar.rs b/src/libstd/sys_common/condvar.rs similarity index 100% rename from src/libstd/sys/common/condvar.rs rename to src/libstd/sys_common/condvar.rs diff --git a/src/libstd/sys/common/gnu/libbacktrace.rs b/src/libstd/sys_common/gnu/libbacktrace.rs similarity index 100% rename from src/libstd/sys/common/gnu/libbacktrace.rs rename to 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 similarity index 100% rename from src/libstd/sys/common/gnu/mod.rs rename to src/libstd/sys_common/gnu/mod.rs diff --git a/src/libstd/sys/common/io.rs b/src/libstd/sys_common/io.rs similarity index 100% rename from src/libstd/sys/common/io.rs rename to src/libstd/sys_common/io.rs diff --git a/src/libstd/sys/common/memchr.rs b/src/libstd/sys_common/memchr.rs similarity index 100% rename from src/libstd/sys/common/memchr.rs rename to src/libstd/sys_common/memchr.rs diff --git a/src/libstd/sys/common/mod.rs b/src/libstd/sys_common/mod.rs similarity index 100% rename from src/libstd/sys/common/mod.rs rename to src/libstd/sys_common/mod.rs diff --git a/src/libstd/sys/common/mutex.rs b/src/libstd/sys_common/mutex.rs similarity index 100% rename from src/libstd/sys/common/mutex.rs rename to src/libstd/sys_common/mutex.rs diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys_common/net.rs similarity index 100% rename from src/libstd/sys/common/net.rs rename to src/libstd/sys_common/net.rs diff --git a/src/libstd/sys/common/poison.rs b/src/libstd/sys_common/poison.rs similarity index 100% rename from src/libstd/sys/common/poison.rs rename to src/libstd/sys_common/poison.rs diff --git a/src/libstd/sys/common/remutex.rs b/src/libstd/sys_common/remutex.rs similarity index 100% rename from src/libstd/sys/common/remutex.rs rename to src/libstd/sys_common/remutex.rs diff --git a/src/libstd/sys/common/rwlock.rs b/src/libstd/sys_common/rwlock.rs similarity index 100% rename from src/libstd/sys/common/rwlock.rs rename to src/libstd/sys_common/rwlock.rs diff --git a/src/libstd/sys/common/thread.rs b/src/libstd/sys_common/thread.rs similarity index 100% rename from src/libstd/sys/common/thread.rs rename to src/libstd/sys_common/thread.rs diff --git a/src/libstd/sys/common/thread_info.rs b/src/libstd/sys_common/thread_info.rs similarity index 100% rename from src/libstd/sys/common/thread_info.rs rename to 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 similarity index 100% rename from src/libstd/sys/common/thread_local.rs rename to src/libstd/sys_common/thread_local.rs diff --git a/src/libstd/sys/common/util.rs b/src/libstd/sys_common/util.rs similarity index 100% rename from src/libstd/sys/common/util.rs rename to src/libstd/sys_common/util.rs diff --git a/src/libstd/sys/common/wtf8.rs b/src/libstd/sys_common/wtf8.rs similarity index 100% rename from src/libstd/sys/common/wtf8.rs rename to src/libstd/sys_common/wtf8.rs diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 68b0c819c5a8..72970bbe6e3c 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -57,9 +57,8 @@ 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 unix - "src/libstd/sys/windows", // Ditto for windows - "src/libstd/sys/mod.rs", // This file chooses the platform + "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 @@ -68,8 +67,8 @@ const EXCEPTION_PATHS: &'static [&'static str] = &[ "src/libstd/path.rs", "src/libstd/num/f32.rs", "src/libstd/num/f64.rs", - "src/libstd/sys/common/mod.rs", - "src/libstd/sys/common/net.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 From ee71dc54765c161c51b2a8d860f9ebf95c6d7e12 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 30 Sep 2016 23:56:28 +0000 Subject: [PATCH 53/62] Document sys_common and sys --- src/libstd/sys/mod.rs | 22 ++++++++++++++++++++++ src/libstd/sys_common/mod.rs | 14 ++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/libstd/sys/mod.rs b/src/libstd/sys/mod.rs index f7e1a0a075a8..84f41a1c535c 100644 --- a/src/libstd/sys/mod.rs +++ b/src/libstd/sys/mod.rs @@ -8,6 +8,28 @@ // 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(unix)] diff --git a/src/libstd/sys_common/mod.rs b/src/libstd/sys_common/mod.rs index 2845f895f186..ac2b27844dc5 100644 --- a/src/libstd/sys_common/mod.rs +++ b/src/libstd/sys_common/mod.rs @@ -8,6 +8,20 @@ // 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; From 8f5bb1f7c05f92986dcf612d81d9c20312dca2fc Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 30 Sep 2016 23:59:06 +0000 Subject: [PATCH 54/62] std: Remove unused test feature --- src/libstd/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 3eb828810909..d203f80e5e83 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -248,7 +248,6 @@ #![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)] From c2518845752e2c7e7bb3682c29a62ae97cfa18ed Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 1 Oct 2016 01:38:29 +0000 Subject: [PATCH 55/62] Clean up and add more comments to libstd/lib.rs --- src/libstd/lib.rs | 137 +++++++++++++++++------------------ src/libstd/sys_common/mod.rs | 16 +--- 2 files changed, 72 insertions(+), 81 deletions(-) diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index d203f80e5e83..6f9aa6d1e082 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -210,8 +210,27 @@ 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)] @@ -283,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 @@ -325,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")] @@ -362,14 +384,30 @@ 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 core::isize; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::i8; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::i16; +#[stable(feature = "rust1", since = "1.0.0")] +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")] +pub use core::u8; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::u16; +#[stable(feature = "rust1", since = "1.0.0")] +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")] @@ -382,85 +420,46 @@ pub use core_collections::str; 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")] -pub use core::i8; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::i16; -#[stable(feature = "rust1", since = "1.0.0")] -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")] -pub use core::u8; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::u16; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::u32; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::u64; - #[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 */ - #[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] 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/sys_common/mod.rs b/src/libstd/sys_common/mod.rs index ac2b27844dc5..1dd9b73e262c 100644 --- a/src/libstd/sys_common/mod.rs +++ b/src/libstd/sys_common/mod.rs @@ -27,18 +27,6 @@ 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; @@ -101,6 +89,10 @@ pub fn at_exit(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(); From 6135cbc9e2b9a7e62ae274cf57e9921f60f6ec73 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 1 Oct 2016 23:07:17 +0000 Subject: [PATCH 56/62] std: Flatten the num directory to reflect the module layout This makes it dissimilar to how core is structured on disk, but more predictable on its own. --- src/libstd/{num => }/f32.rs | 0 src/libstd/{num => }/f64.rs | 0 src/libstd/lib.rs | 4 ++-- src/libstd/{num/mod.rs => num.rs} | 0 src/tools/tidy/src/pal.rs | 4 ++-- 5 files changed, 4 insertions(+), 4 deletions(-) rename src/libstd/{num => }/f32.rs (100%) rename src/libstd/{num => }/f64.rs (100%) rename src/libstd/{num/mod.rs => num.rs} (100%) diff --git a/src/libstd/num/f32.rs b/src/libstd/f32.rs similarity index 100% rename from src/libstd/num/f32.rs rename to src/libstd/f32.rs diff --git a/src/libstd/num/f64.rs b/src/libstd/f64.rs similarity index 100% rename from src/libstd/num/f64.rs rename to src/libstd/f64.rs diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 6f9aa6d1e082..8d973fc1ade4 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -423,8 +423,8 @@ 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 f32; +pub mod f64; #[macro_use] pub mod thread; diff --git a/src/libstd/num/mod.rs b/src/libstd/num.rs similarity index 100% rename from src/libstd/num/mod.rs rename to src/libstd/num.rs diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 72970bbe6e3c..a5e4e5a4c267 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -65,8 +65,8 @@ const EXCEPTION_PATHS: &'static [&'static str] = &[ // temporary exceptions "src/libstd/rtdeps.rs", // Until rustbuild replaces make "src/libstd/path.rs", - "src/libstd/num/f32.rs", - "src/libstd/num/f64.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 From 7d5b788edffc447946e8c27d683e8604b59443c5 Mon Sep 17 00:00:00 2001 From: Dmitry Gritsay Date: Tue, 1 Nov 2016 23:18:02 +0200 Subject: [PATCH 57/62] Elide lifetimes in DerefMut documentation - Elide lifetimes to increase the readability of `DerefMut` examples --- src/libcore/ops.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 62aa57bbbbf0..5c36d337799e 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -2484,13 +2484,13 @@ impl<'a, T: ?Sized> Deref for &'a mut T { /// impl Deref for DerefMutExample { /// type Target = T; /// -/// fn deref<'a>(&'a self) -> &'a T { +/// fn deref(&self) -> &T { /// &self.value /// } /// } /// /// impl DerefMut for DerefMutExample { -/// fn deref_mut<'a>(&'a mut self) -> &'a mut T { +/// fn deref_mut(&mut self) -> &mut T { /// &mut self.value /// } /// } From 7b33f7e3e77794e8a44d07d97bc7b62ab9f79981 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 20 Oct 2016 16:26:36 +1100 Subject: [PATCH 58/62] Optimize ObligationForest's NodeState handling. This commit partially inlines two functions, `find_cycles_from_node` and `mark_as_waiting_from`, at two call sites in order to avoid function unnecessary function calls on hot paths. It also fully inlines and removes `is_popped`. These changes speeds up rustc-benchmarks/inflate-0.1.0 by about 2% when doing debug builds with a stage1 compiler. --- .../obligation_forest/mod.rs | 71 ++++++++++--------- 1 file changed, 37 insertions(+), 34 deletions(-) diff --git a/src/librustc_data_structures/obligation_forest/mod.rs b/src/librustc_data_structures/obligation_forest/mod.rs index 5e590cb445f7..a2bfa784e8ae 100644 --- a/src/librustc_data_structures/obligation_forest/mod.rs +++ b/src/librustc_data_structures/obligation_forest/mod.rs @@ -377,8 +377,16 @@ impl ObligationForest { { 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 ObligationForest { trace } - /// Marks all nodes that depend on a pending node as NodeState;:Waiting. + #[inline] + fn mark_neighbors_as_waiting_from(&self, node: &Node) { + 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 ObligationForest { 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) { match node.state.get() { - NodeState::Pending | NodeState::Done => {}, NodeState::Waiting | NodeState::Error | NodeState::OnDfsStack => return, - NodeState::Success => { - node.state.set(NodeState::Waiting); - } + NodeState::Success => node.state.set(NodeState::Waiting), + NodeState::Pending | NodeState::Done => {}, } - 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()]); - } + self.mark_neighbors_as_waiting_from(node); } /// Compresses the vector, removing all popped nodes. This adjusts @@ -532,28 +543,28 @@ impl ObligationForest { // 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 Node { 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!() - } - } } From 0e391bf22c4810cdb2f0e026037b4b9d1234c679 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Wed, 2 Nov 2016 10:00:11 -0400 Subject: [PATCH 59/62] ICH: Add test case for when overflow checks are disabled. --- .../hashes/panic_exprs_no_overflow_checks.rs | 251 ++++++++++++++++++ 1 file changed, 251 insertions(+) create mode 100644 src/test/incremental/hashes/panic_exprs_no_overflow_checks.rs 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 000000000000..b84b7f5f378a --- /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 or the MIT license +// , 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 +} From 797e0420e3666b873600038ec4298915fe41db83 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Wed, 2 Nov 2016 12:27:11 -0400 Subject: [PATCH 60/62] add #32791 test case --- .../run-pass/issue-37291/auxiliary/lib.rs | 52 +++++++++++++++++++ src/test/run-pass/issue-37291/main.rs | 29 +++++++++++ 2 files changed, 81 insertions(+) create mode 100644 src/test/run-pass/issue-37291/auxiliary/lib.rs create mode 100644 src/test/run-pass/issue-37291/main.rs 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 000000000000..67cdea807bee --- /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 or the MIT license +// , 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(pub T); +pub struct WrapperC(pub T); + +impl Mul::AT>> for WrapperC + where C1: C +{ + type Output = u8; + fn mul(self, _: WrapperB<::AT>) -> Self::Output { + loop {} + } +} +impl Mul> for WrapperC { + type Output = u8; + fn mul(self, _: WrapperC) -> 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 000000000000..2461f7485f26 --- /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 or the MIT license +// , 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 `::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; + } +} From d9bc86032d0aa20db522e04a550deb1034005784 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Wed, 2 Nov 2016 11:50:16 -0400 Subject: [PATCH 61/62] normalize trait-ref in context of impl The `specializes()` function was trying to normalize the impl trait in an empty environment. This could lead to inexplicable failures. --- src/librustc/traits/specialize/mod.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/librustc/traits/specialize/mod.rs b/src/librustc/traits/specialize/mod.rs index e37425901c8c..6a27558b0b77 100644 --- a/src/librustc/traits/specialize/mod.rs +++ b/src/librustc/traits/specialize/mod.rs @@ -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,21 +179,22 @@ 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| { + // Create a infcx, taking the predicates of impl1 as assumptions: + let result = tcx.infer_ctxt(None, Some(penv), 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| { + infcx.parameter_environment.caller_bounds.extend(normalization_obligations.into_iter().map(|o| { match tcx.lift_to_global(&o.predicate) { Some(predicate) => predicate, None => { @@ -200,9 +203,6 @@ pub fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } })); - // 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() }); From b4f910d9004f09620ef5b1aff5d676c1dab7d42f Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Wed, 2 Nov 2016 18:08:32 -0400 Subject: [PATCH 62/62] just use full-normalization when for the impl trait ref This seems better because I want to avoid the situation where unresolved inference variables make it into the environment. On the other hand, I am not 100% sure that this is correct. My assumption was that the WF check should ensure that this normalization can succeed. But it occurs to me that the WF checks may need to make use of the `specializes` predicate themselves, and hence we may have a kind of cycle here (this is a bigger problem with spec in any case that we need to resolve). On the other hand, this should just cause extra errors I think, so it seems like a safe thing to attempt. Certainly all tests pass. --- src/librustc/traits/specialize/mod.rs | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/librustc/traits/specialize/mod.rs b/src/librustc/traits/specialize/mod.rs index 6a27558b0b77..24cafa7f7253 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; @@ -187,21 +187,16 @@ pub fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, .subst(tcx, &penv.free_substs); // Create a infcx, taking the predicates of impl1 as assumptions: - let result = tcx.infer_ctxt(None, Some(penv), 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) - }; - infcx.parameter_environment.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); + 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); } - } - })); + }; // Attempt to prove that impl2 applies, given all of the above. fulfill_implication(&infcx, impl1_trait_ref, impl2_def_id).is_ok()