From be993beb0b0294c6ce4519bf007f73063187809e Mon Sep 17 00:00:00 2001 From: Thomas Etter Date: Mon, 18 Nov 2019 00:51:18 +0100 Subject: [PATCH 01/20] print a more useful error message on should_panic mismatch --- src/libtest/test_result.rs | 22 +++++++++++++++++----- src/libtest/tests.rs | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/src/libtest/test_result.rs b/src/libtest/test_result.rs index 80ca9dea18f5a..5dbbd71554e98 100644 --- a/src/libtest/test_result.rs +++ b/src/libtest/test_result.rs @@ -37,10 +37,12 @@ pub fn calc_result<'a>( let result = match (&desc.should_panic, task_result) { (&ShouldPanic::No, Ok(())) | (&ShouldPanic::Yes, Err(_)) => TestResult::TrOk, (&ShouldPanic::YesWithMessage(msg), Err(ref err)) => { - if err + let maybe_panic_str = err .downcast_ref::() .map(|e| &**e) - .or_else(|| err.downcast_ref::<&'static str>().map(|e| *e)) + .or_else(|| err.downcast_ref::<&'static str>().map(|e| *e)); + + if maybe_panic_str .map(|e| e.contains(msg)) .unwrap_or(false) { @@ -49,9 +51,19 @@ pub fn calc_result<'a>( if desc.allow_fail { TestResult::TrAllowedFail } else { - TestResult::TrFailedMsg( - format!("panic did not include expected string '{}'", msg) - ) + if let Some(panic_str) = maybe_panic_str{ + TestResult::TrFailedMsg( + format!(r#"panic did not contain expected string + panic message: `{:?}`, + expected substring: `{:?}`"#, panic_str, &*msg) + ) + } else { + TestResult::TrFailedMsg( + format!(r#"expected panic with string value, + found non-string value: `{:?}` + expected substring: `{:?}`"#, (**err).type_id(), &*msg) + ) + } } } } diff --git a/src/libtest/tests.rs b/src/libtest/tests.rs index 5f55b647f5e78..fc82bb4f47a4b 100644 --- a/src/libtest/tests.rs +++ b/src/libtest/tests.rs @@ -15,6 +15,7 @@ use crate::{ // TestType, TrFailedMsg, TrIgnored, TrOk, }, }; +use std::any::TypeId; use std::sync::mpsc::channel; use std::time::Duration; @@ -161,7 +162,9 @@ fn test_should_panic_bad_message() { panic!("an error message"); } let expected = "foobar"; - let failed_msg = "panic did not include expected string"; + let failed_msg = r#"panic did not contain expected string + panic message: `"an error message"`, + expected substring: `"foobar"`"#; let desc = TestDescAndFn { desc: TestDesc { name: StaticTestName("whatever"), @@ -175,7 +178,35 @@ fn test_should_panic_bad_message() { let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; - assert!(result == TrFailedMsg(format!("{} '{}'", failed_msg, expected))); + assert_eq!(result, TrFailedMsg(failed_msg.to_string())); +} + +// FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251) +#[test] +#[cfg(not(target_os = "emscripten"))] +fn test_should_panic_non_string_message_type() { + use crate::tests::TrFailedMsg; + fn f() { + panic!(1i32); + } + let expected = "foobar"; + let failed_msg = format!(r#"expected panic with string value, + found non-string value: `{:?}` + expected substring: `"foobar"`"#, TypeId::of::()); + let desc = TestDescAndFn { + desc: TestDesc { + name: StaticTestName("whatever"), + ignore: false, + should_panic: ShouldPanic::YesWithMessage(expected), + allow_fail: false, + test_type: TestType::Unknown, + }, + testfn: DynTestFn(Box::new(f)), + }; + let (tx, rx) = channel(); + run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); + let result = rx.recv().unwrap().result; + assert_eq!(result, TrFailedMsg(failed_msg)); } // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251) From 48a86e0b2cdfaba5a2a684911178d717067e4d28 Mon Sep 17 00:00:00 2001 From: Thomas Etter Date: Mon, 18 Nov 2019 00:52:10 +0100 Subject: [PATCH 02/20] replace some asserts with assert_eq for better error readability --- src/libtest/tests.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/libtest/tests.rs b/src/libtest/tests.rs index fc82bb4f47a4b..0bea2b80ecf5e 100644 --- a/src/libtest/tests.rs +++ b/src/libtest/tests.rs @@ -85,7 +85,7 @@ pub fn do_not_run_ignored_tests() { let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; - assert!(result != TrOk); + assert_ne!(result, TrOk); } #[test] @@ -104,7 +104,7 @@ pub fn ignored_tests_result_in_ignored() { let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; - assert!(result == TrIgnored); + assert_eq!(result, TrIgnored); } // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251) @@ -127,7 +127,7 @@ fn test_should_panic() { let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; - assert!(result == TrOk); + assert_eq!(result, TrOk); } // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251) @@ -150,7 +150,7 @@ fn test_should_panic_good_message() { let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; - assert!(result == TrOk); + assert_eq!(result, TrOk); } // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251) @@ -227,7 +227,7 @@ fn test_should_panic_but_succeeds() { let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; - assert!(result == TrFailedMsg("test did not panic as expected".to_string())); + assert_eq!(result, TrFailedMsg("test did not panic as expected".to_string())); } fn report_time_test_template(report_time: bool) -> Option { @@ -601,7 +601,7 @@ pub fn sort_tests() { ]; for (a, b) in expected.iter().zip(filtered) { - assert!(*a == b.desc.name.to_string()); + assert_eq!(*a, b.desc.name.to_string()); } } From 16bf4f5e1b50773c6b4ec7b7524876440db69d1b Mon Sep 17 00:00:00 2001 From: Thomas Etter Date: Tue, 19 Nov 2019 21:35:07 +0100 Subject: [PATCH 03/20] Simplify if else as suggested in PR feedback --- src/libtest/test_result.rs | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/libtest/test_result.rs b/src/libtest/test_result.rs index 5dbbd71554e98..bfabe1722dbed 100644 --- a/src/libtest/test_result.rs +++ b/src/libtest/test_result.rs @@ -42,29 +42,25 @@ pub fn calc_result<'a>( .map(|e| &**e) .or_else(|| err.downcast_ref::<&'static str>().map(|e| *e)); - if maybe_panic_str - .map(|e| e.contains(msg)) - .unwrap_or(false) - { + if maybe_panic_str.map(|e| e.contains(msg)).unwrap_or(false) { TestResult::TrOk - } else { - if desc.allow_fail { - TestResult::TrAllowedFail - } else { - if let Some(panic_str) = maybe_panic_str{ - TestResult::TrFailedMsg( - format!(r#"panic did not contain expected string + } else if desc.allow_fail { + TestResult::TrAllowedFail + } else if let Some(panic_str) = maybe_panic_str { + TestResult::TrFailedMsg(format!( + r#"panic did not contain expected string panic message: `{:?}`, - expected substring: `{:?}`"#, panic_str, &*msg) - ) - } else { - TestResult::TrFailedMsg( - format!(r#"expected panic with string value, + expected substring: `{:?}`"#, + panic_str, msg + )) + } else { + TestResult::TrFailedMsg(format!( + r#"expected panic with string value, found non-string value: `{:?}` - expected substring: `{:?}`"#, (**err).type_id(), &*msg) - ) - } - } + expected substring: `{:?}`"#, + (**err).type_id(), + msg + )) } } (&ShouldPanic::Yes, Ok(())) => { From 1e91e4e20a5d6e50e281c6e87a3a61cc735e266f Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 22 Nov 2019 23:11:56 +0100 Subject: [PATCH 04/20] enable panic-catching tests in Miri --- src/liballoc/tests/binary_heap.rs | 2 +- src/liballoc/tests/vec.rs | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/liballoc/tests/binary_heap.rs b/src/liballoc/tests/binary_heap.rs index a44cf1eaf6df0..81b22ca815b25 100644 --- a/src/liballoc/tests/binary_heap.rs +++ b/src/liballoc/tests/binary_heap.rs @@ -347,7 +347,7 @@ fn assert_covariance() { // Destructors must be called exactly once per element. // FIXME: re-enable emscripten once it can unwind again #[test] -#[cfg(not(any(miri, target_os = "emscripten")))] // Miri does not support catching panics +#[cfg(not(target_os = "emscripten"))] fn panic_safe() { use std::cmp; use std::panic::{self, AssertUnwindSafe}; diff --git a/src/liballoc/tests/vec.rs b/src/liballoc/tests/vec.rs index 80537217697ad..58b555ecb4eee 100644 --- a/src/liballoc/tests/vec.rs +++ b/src/liballoc/tests/vec.rs @@ -944,10 +944,9 @@ fn drain_filter_complex() { } } -// Miri does not support catching panics // FIXME: re-enable emscripten once it can unwind again #[test] -#[cfg(not(any(miri, target_os = "emscripten")))] +#[cfg(not(target_os = "emscripten"))] fn drain_filter_consumed_panic() { use std::rc::Rc; use std::sync::Mutex; @@ -999,7 +998,7 @@ fn drain_filter_consumed_panic() { // FIXME: Re-enable emscripten once it can catch panics #[test] -#[cfg(not(any(miri, target_os = "emscripten")))] // Miri does not support catching panics +#[cfg(not(target_os = "emscripten"))] fn drain_filter_unconsumed_panic() { use std::rc::Rc; use std::sync::Mutex; From 3277209af5c3369cbf1786d25cbf48c9a131996b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 22 Nov 2019 23:21:20 +0100 Subject: [PATCH 05/20] use catch_panic instead of thread::spawn to catch panics --- src/liballoc/tests/slice.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs index ad2cd7c95eb8f..62b33c02cae37 100644 --- a/src/liballoc/tests/slice.rs +++ b/src/liballoc/tests/slice.rs @@ -4,7 +4,6 @@ use std::mem; use std::panic; use std::rc::Rc; use std::sync::atomic::{Ordering::Relaxed, AtomicUsize}; -use std::thread; use rand::{Rng, RngCore, thread_rng}; use rand::seq::SliceRandom; @@ -1406,11 +1405,10 @@ fn test_box_slice_clone() { #[test] #[allow(unused_must_use)] // here, we care about the side effects of `.clone()` #[cfg_attr(target_os = "emscripten", ignore)] -#[cfg(not(miri))] // Miri does not support threads +#[cfg(not(miri))] // Miri does not support catching panics fn test_box_slice_clone_panics() { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; - use std::thread::spawn; struct Canary { count: Arc, @@ -1446,7 +1444,7 @@ fn test_box_slice_clone_panics() { panics: true, }; - spawn(move || { + std::panic::catch_unwind(move || { // When xs is dropped, +5. let xs = vec![canary.clone(), canary.clone(), canary.clone(), panic, canary] .into_boxed_slice(); @@ -1454,7 +1452,6 @@ fn test_box_slice_clone_panics() { // When panic is cloned, +3. xs.clone(); }) - .join() .unwrap_err(); // Total = 8 @@ -1566,7 +1563,7 @@ macro_rules! test { } let v = $input.to_owned(); - let _ = thread::spawn(move || { + let _ = std::panic::catch_unwind(move || { let mut v = v; let mut panic_countdown = panic_countdown; v.$func(|a, b| { @@ -1577,7 +1574,7 @@ macro_rules! test { panic_countdown -= 1; a.cmp(b) }) - }).join(); + }); // Check that the number of things dropped is exactly // what we expect (i.e., the contents of `v`). @@ -1598,7 +1595,7 @@ thread_local!(static SILENCE_PANIC: Cell = Cell::new(false)); #[test] #[cfg_attr(target_os = "emscripten", ignore)] // no threads -#[cfg(not(miri))] // Miri does not support threads +#[cfg(not(miri))] // Miri does not support catching panics fn panic_safe() { let prev = panic::take_hook(); panic::set_hook(Box::new(move |info| { From 8af2f22985c672bf4cb23b615ac97af00031a2ca Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 22 Nov 2019 23:35:56 +0100 Subject: [PATCH 06/20] enable panic-catching tests in Miri --- src/liballoc/tests/slice.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs index 62b33c02cae37..6433cbd1842d7 100644 --- a/src/liballoc/tests/slice.rs +++ b/src/liballoc/tests/slice.rs @@ -1405,7 +1405,6 @@ fn test_box_slice_clone() { #[test] #[allow(unused_must_use)] // here, we care about the side effects of `.clone()` #[cfg_attr(target_os = "emscripten", ignore)] -#[cfg(not(miri))] // Miri does not support catching panics fn test_box_slice_clone_panics() { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -1595,7 +1594,6 @@ thread_local!(static SILENCE_PANIC: Cell = Cell::new(false)); #[test] #[cfg_attr(target_os = "emscripten", ignore)] // no threads -#[cfg(not(miri))] // Miri does not support catching panics fn panic_safe() { let prev = panic::take_hook(); panic::set_hook(Box::new(move |info| { @@ -1606,7 +1604,12 @@ fn panic_safe() { let mut rng = thread_rng(); - for len in (1..20).chain(70..MAX_LEN) { + #[cfg(not(miri))] // Miri is too slow + let large_range = 70..MAX_LEN; + #[cfg(miri)] + let large_range = 0..0; // empty range + + for len in (1..20).chain(large_range) { for &modulus in &[5, 20, 50] { for &has_runs in &[false, true] { let mut input = (0..len) From a2299799e6193799f4d2cb546e56589c5dd587aa Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 23 Nov 2019 08:53:53 +0100 Subject: [PATCH 07/20] enable more panic-catching tests in Miri --- src/liballoc/tests/binary_heap.rs | 3 +++ src/liballoc/tests/slice.rs | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/liballoc/tests/binary_heap.rs b/src/liballoc/tests/binary_heap.rs index 81b22ca815b25..a896a1064d9e1 100644 --- a/src/liballoc/tests/binary_heap.rs +++ b/src/liballoc/tests/binary_heap.rs @@ -376,7 +376,10 @@ fn panic_safe() { } let mut rng = thread_rng(); const DATASZ: usize = 32; + #[cfg(not(miri))] // Miri is too slow const NTEST: usize = 10; + #[cfg(miri)] + const NTEST: usize = 1; // don't use 0 in the data -- we want to catch the zeroed-out case. let data = (1..=DATASZ).collect::>(); diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs index 6433cbd1842d7..d9707b9574078 100644 --- a/src/liballoc/tests/slice.rs +++ b/src/liballoc/tests/slice.rs @@ -1605,12 +1605,17 @@ fn panic_safe() { let mut rng = thread_rng(); #[cfg(not(miri))] // Miri is too slow - let large_range = 70..MAX_LEN; + let lens = (1..20).chain(70..MAX_LEN); + #[cfg(not(miri))] // Miri is too slow + let moduli = &[5, 20, 50]; + #[cfg(miri)] - let large_range = 0..0; // empty range + let lens = (1..13); + #[cfg(miri)] + let moduli = &[10]; - for len in (1..20).chain(large_range) { - for &modulus in &[5, 20, 50] { + for len in lens { + for &modulus in moduli { for &has_runs in &[false, true] { let mut input = (0..len) .map(|id| { @@ -1643,6 +1648,9 @@ fn panic_safe() { } } } + + // Set default panic hook again. + drop(panic::take_hook()); } #[test] From c66ad1405782c49bc01b9c2a0b3634765a7cecea Mon Sep 17 00:00:00 2001 From: Christian Poveda Date: Tue, 26 Nov 2019 08:27:31 -0500 Subject: [PATCH 08/20] Check SetDiscriminant place --- src/librustc_mir/transform/check_consts/validation.rs | 5 ++++- src/librustc_mir/transform/qualify_min_const_fn.rs | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs index bee37f69a5ec5..5c3cffe3ce82b 100644 --- a/src/librustc_mir/transform/check_consts/validation.rs +++ b/src/librustc_mir/transform/check_consts/validation.rs @@ -566,9 +566,12 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> { StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => { self.check_op(ops::IfOrMatch); } + StatementKind::SetDiscriminant { ref place, .. } => { + let ctx = PlaceContext::MutatingUse(MutatingUseContext::Projection); + self.visit_place(&place, ctx, location) + } // FIXME(eddyb) should these really do nothing? StatementKind::FakeRead(..) | - StatementKind::SetDiscriminant { .. } | StatementKind::StorageLive(_) | StatementKind::StorageDead(_) | StatementKind::InlineAsm {..} | diff --git a/src/librustc_mir/transform/qualify_min_const_fn.rs b/src/librustc_mir/transform/qualify_min_const_fn.rs index 71f13c169d41e..4bfabf4c3e2c1 100644 --- a/src/librustc_mir/transform/qualify_min_const_fn.rs +++ b/src/librustc_mir/transform/qualify_min_const_fn.rs @@ -225,7 +225,7 @@ fn check_statement( StatementKind::FakeRead(_, place) => check_place(tcx, place, span, def_id, body), // just an assignment - StatementKind::SetDiscriminant { .. } => Ok(()), + StatementKind::SetDiscriminant { place, .. } => check_place(tcx, place, span, def_id, body), | StatementKind::InlineAsm { .. } => { Err((span, "cannot use inline assembly in const fn".into())) From d7c09f7e1e446390ed3f02ed576a1efce5279b96 Mon Sep 17 00:00:00 2001 From: Christian Poveda Date: Tue, 26 Nov 2019 17:23:24 -0500 Subject: [PATCH 09/20] Change way of checking SetDiscriminant --- src/librustc_mir/transform/check_consts/validation.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs index 5c3cffe3ce82b..7b26ba58e6154 100644 --- a/src/librustc_mir/transform/check_consts/validation.rs +++ b/src/librustc_mir/transform/check_consts/validation.rs @@ -566,9 +566,8 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> { StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => { self.check_op(ops::IfOrMatch); } - StatementKind::SetDiscriminant { ref place, .. } => { - let ctx = PlaceContext::MutatingUse(MutatingUseContext::Projection); - self.visit_place(&place, ctx, location) + StatementKind::SetDiscriminant { .. } => { + self.super_statement(statement, location) } // FIXME(eddyb) should these really do nothing? StatementKind::FakeRead(..) | From 5d23518a12548fdbbca74fcc3171fdc2f3888334 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 28 Nov 2019 09:03:00 +0100 Subject: [PATCH 10/20] const_prop: detect and avoid catching Miri errors that require allocation --- src/librustc/mir/interpret/error.rs | 20 +++++++++------ src/librustc_mir/transform/const_prop.rs | 32 ++++++++++++++++++------ 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/src/librustc/mir/interpret/error.rs b/src/librustc/mir/interpret/error.rs index 4fe82f03b036e..fadd90c22570f 100644 --- a/src/librustc/mir/interpret/error.rs +++ b/src/librustc/mir/interpret/error.rs @@ -44,14 +44,14 @@ CloneTypeFoldableImpls! { pub type ConstEvalRawResult<'tcx> = Result, ErrorHandled>; pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>; -#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] +#[derive(Clone, Debug)] pub struct ConstEvalErr<'tcx> { pub span: Span, pub error: crate::mir::interpret::InterpError<'tcx>, pub stacktrace: Vec>, } -#[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] +#[derive(Clone, Debug)] pub struct FrameInfo<'tcx> { /// This span is in the caller. pub call_site: Span, @@ -327,7 +327,7 @@ impl fmt::Debug for PanicInfo { /// Error information for when the program we executed turned out not to actually be a valid /// program. This cannot happen in stand-alone Miri, but it can happen during CTFE/ConstProp /// where we work on generic code or execution does not have all information available. -#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] +#[derive(Clone, HashStable)] pub enum InvalidProgramInfo<'tcx> { /// Resolution can fail if we are in a too generic context. TooGeneric, @@ -357,7 +357,7 @@ impl fmt::Debug for InvalidProgramInfo<'tcx> { } /// Error information for when the program caused Undefined Behavior. -#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] +#[derive(Clone, HashStable)] pub enum UndefinedBehaviorInfo { /// Free-form case. Only for errors that are never caught! Ub(String), @@ -390,11 +390,15 @@ impl fmt::Debug for UndefinedBehaviorInfo { /// /// Currently, we also use this as fall-back error kind for errors that have not been /// categorized yet. -#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] +#[derive(Clone, HashStable)] pub enum UnsupportedOpInfo<'tcx> { /// Free-form case. Only for errors that are never caught! Unsupported(String), + /// When const-prop encounters a situation it does not support, it raises this error. + /// This must not allocate for performance reasons. + ConstPropUnsupported(&'tcx str), + // -- Everything below is not categorized yet -- FunctionAbiMismatch(Abi, Abi), FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>), @@ -555,13 +559,15 @@ impl fmt::Debug for UnsupportedOpInfo<'tcx> { not a power of two"), Unsupported(ref msg) => write!(f, "{}", msg), + ConstPropUnsupported(ref msg) => + write!(f, "Constant propagation encountered an unsupported situation: {}", msg), } } } /// Error information for when the program exhausted the resources granted to it /// by the interpreter. -#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] +#[derive(Clone, HashStable)] pub enum ResourceExhaustionInfo { /// The stack grew too big. StackFrameLimitReached, @@ -582,7 +588,7 @@ impl fmt::Debug for ResourceExhaustionInfo { } } -#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] +#[derive(Clone, HashStable)] pub enum InterpError<'tcx> { /// The program panicked. Panic(PanicInfo), diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 6f0b960cab107..c02d07b80faaa 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -168,14 +168,14 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine { _ret: Option<(PlaceTy<'tcx>, BasicBlock)>, _unwind: Option ) -> InterpResult<'tcx> { - throw_unsup_format!("calling intrinsics isn't supported in ConstProp"); + throw_unsup!(ConstPropUnsupported("calling intrinsics isn't supported in ConstProp")); } fn ptr_to_int( _mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer, ) -> InterpResult<'tcx, u64> { - throw_unsup_format!("ptr-to-int casts aren't supported in ConstProp"); + throw_unsup!(ConstPropUnsupported("ptr-to-int casts aren't supported in ConstProp")); } fn binary_ptr_op( @@ -185,7 +185,8 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine { _right: ImmTy<'tcx>, ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> { // We can't do this because aliasing of memory can differ between const eval and llvm - throw_unsup_format!("pointer arithmetic or comparisons aren't supported in ConstProp"); + throw_unsup!(ConstPropUnsupported("pointer arithmetic or comparisons aren't supported \ + in ConstProp")); } fn find_foreign_static( @@ -218,7 +219,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine { _ecx: &mut InterpCx<'mir, 'tcx, Self>, _dest: PlaceTy<'tcx>, ) -> InterpResult<'tcx> { - throw_unsup_format!("can't const prop `box` keyword"); + throw_unsup!(ConstPropUnsupported("can't const prop `box` keyword")); } fn access_local( @@ -229,7 +230,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine { let l = &frame.locals[local]; if l.value == LocalValue::Uninitialized { - throw_unsup_format!("tried to access an uninitialized local"); + throw_unsup!(ConstPropUnsupported("tried to access an uninitialized local")); } l.access() @@ -241,7 +242,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine { // if the static allocation is mutable or if it has relocations (it may be legal to mutate // the memory behind that in the future), then we can't const prop it if allocation.mutability == Mutability::Mutable || allocation.relocations().len() > 0 { - throw_unsup_format!("can't eval mutable statics in ConstProp"); + throw_unsup!(ConstPropUnsupported("can't eval mutable statics in ConstProp")); } Ok(()) @@ -389,9 +390,26 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { let r = match f(self) { Ok(val) => Some(val), Err(error) => { - use rustc::mir::interpret::InterpError::*; + use rustc::mir::interpret::{ + UnsupportedOpInfo, + UndefinedBehaviorInfo, + InterpError::* + }; match error.kind { Exit(_) => bug!("the CTFE program cannot exit"), + + // Some error shouldn't come up because creating them causes + // an allocation, which we should avoid. When that happens, + // dedicated error variants should be introduced instead. + // Only test this in debug builds though to avoid disruptions. + Unsupported(UnsupportedOpInfo::Unsupported(_)) + | Unsupported(UnsupportedOpInfo::ValidationFailure(_)) + | UndefinedBehavior(UndefinedBehaviorInfo::Ub(_)) + | UndefinedBehavior(UndefinedBehaviorInfo::UbExperimental(_)) + if cfg!(debug_assertions) => { + bug!("const-prop encountered allocating error: {:?}", error.kind); + } + Unsupported(_) | UndefinedBehavior(_) | InvalidProgram(_) From 1f853d25b8465e61209035393eebb765968e6173 Mon Sep 17 00:00:00 2001 From: Mark Mansi Date: Sat, 23 Nov 2019 15:11:35 -0600 Subject: [PATCH 11/20] improve lifetime errors with implicit trait object lifetimes --- src/librustc/ty/sty.rs | 2 +- .../error_reporting/outlives_suggestion.rs | 15 ++------ .../error_reporting/region_name.rs | 36 +++++++++++++++---- .../issues/issue-63388-1.nll.stderr | 4 +-- ...s_pin_lifetime_impl_trait-async.nll.stderr | 6 ++-- ...pes_pin_lifetime_mismatch-async.nll.stderr | 17 ++++----- .../self/elision/lt-ref-self-async.nll.stderr | 36 +++++++++---------- .../elision/ref-mut-self-async.nll.stderr | 36 +++++++++---------- .../elision/ref-mut-struct-async.nll.stderr | 30 ++++++++-------- .../self/elision/ref-struct-async.nll.stderr | 30 ++++++++-------- 10 files changed, 114 insertions(+), 98 deletions(-) diff --git a/src/librustc/ty/sty.rs b/src/librustc/ty/sty.rs index b72468a6ff98b..9b3ec59906289 100644 --- a/src/librustc/ty/sty.rs +++ b/src/librustc/ty/sty.rs @@ -69,7 +69,7 @@ pub enum BoundRegion { impl BoundRegion { pub fn is_named(&self) -> bool { match *self { - BoundRegion::BrNamed(..) => true, + BoundRegion::BrNamed(_, name) => name != kw::UnderscoreLifetime, _ => false, } } diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs index c0cf4eb5285c9..907119dd2036f 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs @@ -78,17 +78,7 @@ impl OutlivesSuggestionBuilder<'a> { match name.source { RegionNameSource::NamedEarlyBoundRegion(..) | RegionNameSource::NamedFreeRegion(..) - | RegionNameSource::Static => { - // FIXME: This is a bit hacky. We should ideally have a semantic way for checking - // if the name is `'_`... - if name.name().with(|name| name != "'_") { - debug!("Region {:?} is suggestable", name); - true - } else { - debug!("Region {:?} is NOT suggestable", name); - false - } - } + | RegionNameSource::Static => true, // Don't give suggestions for upvars, closure return types, or other unnamable // regions. @@ -98,7 +88,8 @@ impl OutlivesSuggestionBuilder<'a> { | RegionNameSource::MatchedAdtAndSegment(..) | RegionNameSource::AnonRegionFromUpvar(..) | RegionNameSource::AnonRegionFromOutput(..) - | RegionNameSource::AnonRegionFromYieldTy(..) => { + | RegionNameSource::AnonRegionFromYieldTy(..) + | RegionNameSource::AnonRegionFromTraitObjAsync(..) => { debug!("Region {:?} is NOT suggestable", name); false } diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs index e59928987a03c..519991e815b27 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs @@ -55,7 +55,10 @@ crate enum RegionNameSource { AnonRegionFromUpvar(Span, String), /// The region corresponding to the return type of a closure. AnonRegionFromOutput(Span, String, String), + /// The region from a type yielded by a generator. AnonRegionFromYieldTy(Span, String), + /// An anonymous region from a trait object in an async fn. + AnonRegionFromTraitObjAsync(Span), } /// Records region names that have been assigned before so that we can use the same ones in later @@ -113,7 +116,8 @@ impl RegionName { RegionNameSource::MatchedAdtAndSegment(..) | RegionNameSource::AnonRegionFromUpvar(..) | RegionNameSource::AnonRegionFromOutput(..) | - RegionNameSource::AnonRegionFromYieldTy(..) => false, + RegionNameSource::AnonRegionFromYieldTy(..) | + RegionNameSource::AnonRegionFromTraitObjAsync(..) => false, } } @@ -137,7 +141,8 @@ impl RegionName { RegionNameSource::CannotMatchHirTy(span, type_name) => { diag.span_label(*span, format!("has type `{}`", type_name)); } - RegionNameSource::MatchedHirTy(span) => { + RegionNameSource::MatchedHirTy(span) | + RegionNameSource::AnonRegionFromTraitObjAsync(span) => { diag.span_label( *span, format!("let's call the lifetime of this reference `{}`", self), @@ -287,11 +292,30 @@ impl<'tcx> RegionInferenceContext<'tcx> { ty::ReFree(free_region) => match free_region.bound_region { ty::BoundRegion::BrNamed(_, name) => { + // Get the span to point to, even if we don't use the name. let span = self.get_named_span(tcx, error_region, name); - Some(RegionName { - name, - source: RegionNameSource::NamedFreeRegion(span), - }) + debug!("bound region named: {:?}, is_named: {:?}", + name, free_region.bound_region.is_named()); + + if free_region.bound_region.is_named() { + // A named region that is actually named. + Some(RegionName { + name, + source: RegionNameSource::NamedFreeRegion(span), + }) + } else { + // If we spuriously thought that the region is named, we should let the + // system generate a true name for error messages. Currently this can + // happen if we have an elided name in a trait object used in an async fn + // for example: the compiler will generate a region named `'_`, but + // reporting such a name is not actually useful, so we synthesize a name + // for it instead. + let name = self.synthesize_region_name(renctx); + Some(RegionName { + name, + source: RegionNameSource::AnonRegionFromTraitObjAsync(span), + }) + } } ty::BoundRegion::BrEnv => { diff --git a/src/test/ui/async-await/issues/issue-63388-1.nll.stderr b/src/test/ui/async-await/issues/issue-63388-1.nll.stderr index 22610fe54a4cb..4ae3971e90eae 100644 --- a/src/test/ui/async-await/issues/issue-63388-1.nll.stderr +++ b/src/test/ui/async-await/issues/issue-63388-1.nll.stderr @@ -12,12 +12,12 @@ error: lifetime may not live long enough LL | async fn do_sth<'a>( | -- lifetime `'a` defined here LL | &'a self, foo: &dyn Foo - | - lifetime `'_` defined here + | - let's call the lifetime of this reference `'1` LL | ) -> &dyn Foo LL | / { LL | | foo LL | | } - | |_____^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'_` + | |_____^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1` error: aborting due to 2 previous errors diff --git a/src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr b/src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr index 713d4b759096e..5a63553adc5c8 100644 --- a/src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr +++ b/src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr @@ -2,11 +2,11 @@ error: lifetime may not live long enough --> $DIR/arbitrary_self_types_pin_lifetime_impl_trait-async.rs:8:48 | LL | async fn f(self: Pin<&Self>) -> impl Clone { self } - | - ^^^^^^^^ returning this value requires that `'_` must outlive `'static` + | - ^^^^^^^^ returning this value requires that `'1` must outlive `'static` | | - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` | -help: to allow this `impl Trait` to capture borrowed data with lifetime `'_`, add `'_` as a constraint +help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as a constraint | LL | async fn f(self: Pin<&Self>) -> impl Clone + '_ { self } | ^^^^^^^^^^^^^^^ diff --git a/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr b/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr index 7eec31d36e39e..b16c01de0afc1 100644 --- a/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr +++ b/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr @@ -10,19 +10,19 @@ error: lifetime may not live long enough --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:8:52 | LL | async fn a(self: Pin<&Foo>, f: &Foo) -> &Foo { f } - | - ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | - ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` error: lifetime may not live long enough --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:11:75 | LL | async fn c(self: Pin<&Self>, f: &Foo, g: &Foo) -> (Pin<&Foo>, &Foo) { (self, f) } - | - ^^^^^^^^^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | - ^^^^^^^^^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:17:58 @@ -36,8 +36,9 @@ error: lifetime may not live long enough --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:17:64 | LL | async fn bar<'a>(self: Alias<&Self>, arg: &'a ()) -> &() { arg } - | -- - lifetime `'_` defined here ^^^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'a` - | | + | -- - ^^^ function was supposed to return data with lifetime `'1` but it is returning data with lifetime `'a` + | | | + | | let's call the lifetime of this reference `'1` | lifetime `'a` defined here error: aborting due to 5 previous errors diff --git a/src/test/ui/self/elision/lt-ref-self-async.nll.stderr b/src/test/ui/self/elision/lt-ref-self-async.nll.stderr index 1288759703f69..0bf7f63ca2360 100644 --- a/src/test/ui/self/elision/lt-ref-self-async.nll.stderr +++ b/src/test/ui/self/elision/lt-ref-self-async.nll.stderr @@ -12,10 +12,10 @@ error: lifetime may not live long enough LL | async fn ref_self(&self, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/lt-ref-self-async.rs:18:48 @@ -31,10 +31,10 @@ error: lifetime may not live long enough LL | async fn ref_Self(self: &Self, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/lt-ref-self-async.rs:22:57 @@ -50,10 +50,10 @@ error: lifetime may not live long enough LL | async fn box_ref_Self(self: Box<&Self>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/lt-ref-self-async.rs:26:57 @@ -69,10 +69,10 @@ error: lifetime may not live long enough LL | async fn pin_ref_Self(self: Pin<&Self>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/lt-ref-self-async.rs:30:66 @@ -88,10 +88,10 @@ error: lifetime may not live long enough LL | async fn box_box_ref_Self(self: Box>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/lt-ref-self-async.rs:34:62 @@ -107,10 +107,10 @@ error: lifetime may not live long enough LL | async fn box_pin_Self(self: Box>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error: aborting due to 12 previous errors diff --git a/src/test/ui/self/elision/ref-mut-self-async.nll.stderr b/src/test/ui/self/elision/ref-mut-self-async.nll.stderr index 24e3f7a098fb1..f0987e0d03372 100644 --- a/src/test/ui/self/elision/ref-mut-self-async.nll.stderr +++ b/src/test/ui/self/elision/ref-mut-self-async.nll.stderr @@ -12,10 +12,10 @@ error: lifetime may not live long enough LL | async fn ref_self(&mut self, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-self-async.rs:18:52 @@ -31,10 +31,10 @@ error: lifetime may not live long enough LL | async fn ref_Self(self: &mut Self, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-self-async.rs:22:61 @@ -50,10 +50,10 @@ error: lifetime may not live long enough LL | async fn box_ref_Self(self: Box<&mut Self>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-self-async.rs:26:61 @@ -69,10 +69,10 @@ error: lifetime may not live long enough LL | async fn pin_ref_Self(self: Pin<&mut Self>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-self-async.rs:30:70 @@ -88,10 +88,10 @@ error: lifetime may not live long enough LL | async fn box_box_ref_Self(self: Box>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-self-async.rs:34:70 @@ -107,10 +107,10 @@ error: lifetime may not live long enough LL | async fn box_pin_ref_Self(self: Box>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error: aborting due to 12 previous errors diff --git a/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr b/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr index c0423d1d3e669..5c0261c2f60d2 100644 --- a/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr +++ b/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr @@ -12,10 +12,10 @@ error: lifetime may not live long enough LL | async fn ref_Struct(self: &mut Struct, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-struct-async.rs:16:65 @@ -31,10 +31,10 @@ error: lifetime may not live long enough LL | async fn box_ref_Struct(self: Box<&mut Struct>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-struct-async.rs:20:65 @@ -50,10 +50,10 @@ error: lifetime may not live long enough LL | async fn pin_ref_Struct(self: Pin<&mut Struct>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-struct-async.rs:24:74 @@ -69,10 +69,10 @@ error: lifetime may not live long enough LL | async fn box_box_ref_Struct(self: Box>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-mut-struct-async.rs:28:74 @@ -88,10 +88,10 @@ error: lifetime may not live long enough LL | async fn box_pin_ref_Struct(self: Box>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error: aborting due to 10 previous errors diff --git a/src/test/ui/self/elision/ref-struct-async.nll.stderr b/src/test/ui/self/elision/ref-struct-async.nll.stderr index 6f413a7f49fb8..440facb9be180 100644 --- a/src/test/ui/self/elision/ref-struct-async.nll.stderr +++ b/src/test/ui/self/elision/ref-struct-async.nll.stderr @@ -12,10 +12,10 @@ error: lifetime may not live long enough LL | async fn ref_Struct(self: &Struct, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-struct-async.rs:16:61 @@ -31,10 +31,10 @@ error: lifetime may not live long enough LL | async fn box_ref_Struct(self: Box<&Struct>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-struct-async.rs:20:61 @@ -50,10 +50,10 @@ error: lifetime may not live long enough LL | async fn pin_ref_Struct(self: Pin<&Struct>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-struct-async.rs:24:70 @@ -69,10 +69,10 @@ error: lifetime may not live long enough LL | async fn box_box_ref_Struct(self: Box>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds --> $DIR/ref-struct-async.rs:28:66 @@ -88,10 +88,10 @@ error: lifetime may not live long enough LL | async fn box_pin_Struct(self: Box>, f: &u32) -> &u32 { | - | | - | lifetime `'_` defined here - | lifetime `'_` defined here + | let's call the lifetime of this reference `'1` + | let's call the lifetime of this reference `'2` LL | f - | ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_` + | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` error: aborting due to 10 previous errors From 59a768ce14ca8b439107dce0b575ee1c36244758 Mon Sep 17 00:00:00 2001 From: Mark Mansi Date: Sun, 24 Nov 2019 18:47:15 -0600 Subject: [PATCH 12/20] rename to AnonRegionFromAsyncFn --- .../error_reporting/outlives_suggestion.rs | 2 +- .../region_infer/error_reporting/region_name.rs | 17 ++++++++--------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs index 907119dd2036f..938059c2a923b 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs @@ -89,7 +89,7 @@ impl OutlivesSuggestionBuilder<'a> { | RegionNameSource::AnonRegionFromUpvar(..) | RegionNameSource::AnonRegionFromOutput(..) | RegionNameSource::AnonRegionFromYieldTy(..) - | RegionNameSource::AnonRegionFromTraitObjAsync(..) => { + | RegionNameSource::AnonRegionFromAsyncFn(..) => { debug!("Region {:?} is NOT suggestable", name); false } diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs index 519991e815b27..46c87db7af160 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs @@ -57,8 +57,8 @@ crate enum RegionNameSource { AnonRegionFromOutput(Span, String, String), /// The region from a type yielded by a generator. AnonRegionFromYieldTy(Span, String), - /// An anonymous region from a trait object in an async fn. - AnonRegionFromTraitObjAsync(Span), + /// An anonymous region from an async fn. + AnonRegionFromAsyncFn(Span), } /// Records region names that have been assigned before so that we can use the same ones in later @@ -117,7 +117,7 @@ impl RegionName { RegionNameSource::AnonRegionFromUpvar(..) | RegionNameSource::AnonRegionFromOutput(..) | RegionNameSource::AnonRegionFromYieldTy(..) | - RegionNameSource::AnonRegionFromTraitObjAsync(..) => false, + RegionNameSource::AnonRegionFromAsyncFn(..) => false, } } @@ -142,7 +142,7 @@ impl RegionName { diag.span_label(*span, format!("has type `{}`", type_name)); } RegionNameSource::MatchedHirTy(span) | - RegionNameSource::AnonRegionFromTraitObjAsync(span) => { + RegionNameSource::AnonRegionFromAsyncFn(span) => { diag.span_label( *span, format!("let's call the lifetime of this reference `{}`", self), @@ -306,14 +306,13 @@ impl<'tcx> RegionInferenceContext<'tcx> { } else { // If we spuriously thought that the region is named, we should let the // system generate a true name for error messages. Currently this can - // happen if we have an elided name in a trait object used in an async fn - // for example: the compiler will generate a region named `'_`, but - // reporting such a name is not actually useful, so we synthesize a name - // for it instead. + // happen if we have an elided name in an async fn for example: the + // compiler will generate a region named `'_`, but reporting such a name is + // not actually useful, so we synthesize a name for it instead. let name = self.synthesize_region_name(renctx); Some(RegionName { name, - source: RegionNameSource::AnonRegionFromTraitObjAsync(span), + source: RegionNameSource::AnonRegionFromAsyncFn(span), }) } } From 05db660d399d5f53adf8f6bafd11c03fb9cdfd52 Mon Sep 17 00:00:00 2001 From: Mark Mansi Date: Mon, 25 Nov 2019 12:36:53 -0600 Subject: [PATCH 13/20] remove get_named_span --- .../error_reporting/region_name.rs | 44 +++---------------- ...pes_pin_lifetime_mismatch-async.nll.stderr | 12 ++--- .../self/elision/lt-ref-self-async.nll.stderr | 18 +++----- .../elision/ref-mut-self-async.nll.stderr | 18 +++----- .../elision/ref-mut-struct-async.nll.stderr | 15 +++---- .../self/elision/ref-struct-async.nll.stderr | 15 +++---- 6 files changed, 33 insertions(+), 89 deletions(-) diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs index 46c87db7af160..b775ffdad1b55 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs @@ -13,13 +13,13 @@ use rustc::hir::def_id::DefId; use rustc::infer::InferCtxt; use rustc::mir::{Local, Body}; use rustc::ty::subst::{SubstsRef, GenericArgKind}; -use rustc::ty::{self, RegionKind, RegionVid, Ty, TyCtxt}; +use rustc::ty::{self, RegionVid, Ty, TyCtxt}; use rustc::ty::print::RegionHighlightMode; use rustc_index::vec::IndexVec; use rustc_errors::DiagnosticBuilder; use syntax::symbol::kw; use rustc_data_structures::fx::FxHashMap; -use syntax_pos::{Span, symbol::Symbol}; +use syntax_pos::{Span, symbol::Symbol, DUMMY_SP}; /// A name for a particular region used in emitting diagnostics. This name could be a generated /// name like `'1`, a name used by the user like `'a`, or a name like `'static`. @@ -275,7 +275,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { match error_region { ty::ReEarlyBound(ebr) => { if ebr.has_name() { - let span = self.get_named_span(tcx, error_region, ebr.name); + let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP); Some(RegionName { name: ebr.name, source: RegionNameSource::NamedEarlyBoundRegion(span), @@ -291,9 +291,9 @@ impl<'tcx> RegionInferenceContext<'tcx> { }), ty::ReFree(free_region) => match free_region.bound_region { - ty::BoundRegion::BrNamed(_, name) => { + ty::BoundRegion::BrNamed(region_def_id, name) => { // Get the span to point to, even if we don't use the name. - let span = self.get_named_span(tcx, error_region, name); + let span = tcx.hir().span_if_local(region_def_id).unwrap_or(DUMMY_SP); debug!("bound region named: {:?}, is_named: {:?}", name, free_region.bound_region.is_named()); @@ -373,40 +373,6 @@ impl<'tcx> RegionInferenceContext<'tcx> { } } - /// Gets a span of a named region to provide context for error messages that - /// mention that span, for example: - /// - /// ``` - /// | - /// | fn two_regions<'a, 'b, T>(cell: Cell<&'a ()>, t: T) - /// | -- -- lifetime `'b` defined here - /// | | - /// | lifetime `'a` defined here - /// | - /// | with_signature(cell, t, |cell, t| require(cell, t)); - /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'b` must - /// | outlive `'a` - /// ``` - fn get_named_span( - &self, - tcx: TyCtxt<'tcx>, - error_region: &RegionKind, - name: Symbol, - ) -> Span { - let scope = error_region.free_region_binding_scope(tcx); - let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID); - - let span = tcx.sess.source_map().def_span(tcx.hir().span(node)); - if let Some(param) = tcx.hir() - .get_generics(scope) - .and_then(|generics| generics.get_named(name)) - { - param.span - } else { - span - } - } - /// Finds an argument that contains `fr` and label it with a fully /// elaborated type, returning something like `'1`. Result looks /// like: diff --git a/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr b/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr index b16c01de0afc1..b05940fd273a1 100644 --- a/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr +++ b/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr @@ -10,18 +10,18 @@ error: lifetime may not live long enough --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:8:52 | LL | async fn a(self: Pin<&Foo>, f: &Foo) -> &Foo { f } - | - ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` - | | - | let's call the lifetime of this reference `'1` + | - - ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` + | | | + | | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` error: lifetime may not live long enough --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:11:75 | LL | async fn c(self: Pin<&Self>, f: &Foo, g: &Foo) -> (Pin<&Foo>, &Foo) { (self, f) } - | - ^^^^^^^^^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` - | | - | let's call the lifetime of this reference `'1` + | - - ^^^^^^^^^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` + | | | + | | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds diff --git a/src/test/ui/self/elision/lt-ref-self-async.nll.stderr b/src/test/ui/self/elision/lt-ref-self-async.nll.stderr index 0bf7f63ca2360..8dd823a220497 100644 --- a/src/test/ui/self/elision/lt-ref-self-async.nll.stderr +++ b/src/test/ui/self/elision/lt-ref-self-async.nll.stderr @@ -10,9 +10,8 @@ error: lifetime may not live long enough --> $DIR/lt-ref-self-async.rs:13:9 | LL | async fn ref_self(&self, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -29,9 +28,8 @@ error: lifetime may not live long enough --> $DIR/lt-ref-self-async.rs:19:9 | LL | async fn ref_Self(self: &Self, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -48,9 +46,8 @@ error: lifetime may not live long enough --> $DIR/lt-ref-self-async.rs:23:9 | LL | async fn box_ref_Self(self: Box<&Self>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -67,9 +64,8 @@ error: lifetime may not live long enough --> $DIR/lt-ref-self-async.rs:27:9 | LL | async fn pin_ref_Self(self: Pin<&Self>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -86,9 +82,8 @@ error: lifetime may not live long enough --> $DIR/lt-ref-self-async.rs:31:9 | LL | async fn box_box_ref_Self(self: Box>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -105,9 +100,8 @@ error: lifetime may not live long enough --> $DIR/lt-ref-self-async.rs:35:9 | LL | async fn box_pin_Self(self: Box>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` diff --git a/src/test/ui/self/elision/ref-mut-self-async.nll.stderr b/src/test/ui/self/elision/ref-mut-self-async.nll.stderr index f0987e0d03372..768f532c18317 100644 --- a/src/test/ui/self/elision/ref-mut-self-async.nll.stderr +++ b/src/test/ui/self/elision/ref-mut-self-async.nll.stderr @@ -10,9 +10,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-self-async.rs:13:9 | LL | async fn ref_self(&mut self, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -29,9 +28,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-self-async.rs:19:9 | LL | async fn ref_Self(self: &mut Self, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -48,9 +46,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-self-async.rs:23:9 | LL | async fn box_ref_Self(self: Box<&mut Self>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -67,9 +64,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-self-async.rs:27:9 | LL | async fn pin_ref_Self(self: Pin<&mut Self>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -86,9 +82,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-self-async.rs:31:9 | LL | async fn box_box_ref_Self(self: Box>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -105,9 +100,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-self-async.rs:35:9 | LL | async fn box_pin_ref_Self(self: Box>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` diff --git a/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr b/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr index 5c0261c2f60d2..9e26e411d30bd 100644 --- a/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr +++ b/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr @@ -10,9 +10,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-struct-async.rs:13:9 | LL | async fn ref_Struct(self: &mut Struct, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -29,9 +28,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-struct-async.rs:17:9 | LL | async fn box_ref_Struct(self: Box<&mut Struct>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -48,9 +46,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-struct-async.rs:21:9 | LL | async fn pin_ref_Struct(self: Pin<&mut Struct>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -67,9 +64,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-struct-async.rs:25:9 | LL | async fn box_box_ref_Struct(self: Box>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -86,9 +82,8 @@ error: lifetime may not live long enough --> $DIR/ref-mut-struct-async.rs:29:9 | LL | async fn box_pin_ref_Struct(self: Box>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` diff --git a/src/test/ui/self/elision/ref-struct-async.nll.stderr b/src/test/ui/self/elision/ref-struct-async.nll.stderr index 440facb9be180..cbf051205ed96 100644 --- a/src/test/ui/self/elision/ref-struct-async.nll.stderr +++ b/src/test/ui/self/elision/ref-struct-async.nll.stderr @@ -10,9 +10,8 @@ error: lifetime may not live long enough --> $DIR/ref-struct-async.rs:13:9 | LL | async fn ref_Struct(self: &Struct, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -29,9 +28,8 @@ error: lifetime may not live long enough --> $DIR/ref-struct-async.rs:17:9 | LL | async fn box_ref_Struct(self: Box<&Struct>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -48,9 +46,8 @@ error: lifetime may not live long enough --> $DIR/ref-struct-async.rs:21:9 | LL | async fn pin_ref_Struct(self: Pin<&Struct>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -67,9 +64,8 @@ error: lifetime may not live long enough --> $DIR/ref-struct-async.rs:25:9 | LL | async fn box_box_ref_Struct(self: Box>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` @@ -86,9 +82,8 @@ error: lifetime may not live long enough --> $DIR/ref-struct-async.rs:29:9 | LL | async fn box_pin_Struct(self: Box>, f: &u32) -> &u32 { - | - + | - - let's call the lifetime of this reference `'1` | | - | let's call the lifetime of this reference `'1` | let's call the lifetime of this reference `'2` LL | f | ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` From 2a86b6cb33536efe5d4d10764b04542205abe581 Mon Sep 17 00:00:00 2001 From: Mark Mansi Date: Fri, 29 Nov 2019 11:07:01 -0600 Subject: [PATCH 14/20] minor fix --- .../nll/region_infer/error_reporting/region_name.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs index b775ffdad1b55..0f5d1c5edc498 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs @@ -121,10 +121,6 @@ impl RegionName { } } - crate fn name(&self) -> Symbol { - self.name - } - crate fn highlight_region_name(&self, diag: &mut DiagnosticBuilder<'_>) { match &self.source { RegionNameSource::NamedFreeRegion(span) @@ -309,7 +305,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { // happen if we have an elided name in an async fn for example: the // compiler will generate a region named `'_`, but reporting such a name is // not actually useful, so we synthesize a name for it instead. - let name = self.synthesize_region_name(renctx); + let name = renctx.synthesize_region_name(); Some(RegionName { name, source: RegionNameSource::AnonRegionFromAsyncFn(span), From f8fb24f18fcdea9b5ae7dcdb90fa68d618eb1e0b Mon Sep 17 00:00:00 2001 From: Nixon Date: Fri, 29 Nov 2019 22:16:26 +0000 Subject: [PATCH 15/20] Add explanation message for E0203 --- src/librustc_error_codes/error_codes.rs | 3 +-- src/librustc_error_codes/error_codes/E0203.md | 12 ++++++++++++ src/test/ui/maybe-bounds-where.stderr | 1 + 3 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 src/librustc_error_codes/error_codes/E0203.md diff --git a/src/librustc_error_codes/error_codes.rs b/src/librustc_error_codes/error_codes.rs index 709ccce517a36..7f111b42403b5 100644 --- a/src/librustc_error_codes/error_codes.rs +++ b/src/librustc_error_codes/error_codes.rs @@ -107,6 +107,7 @@ E0199: include_str!("./error_codes/E0199.md"), E0200: include_str!("./error_codes/E0200.md"), E0201: include_str!("./error_codes/E0201.md"), E0202: include_str!("./error_codes/E0202.md"), +E0203: include_str!("./error_codes/E0203.md"), E0204: include_str!("./error_codes/E0204.md"), E0205: include_str!("./error_codes/E0205.md"), E0206: include_str!("./error_codes/E0206.md"), @@ -446,8 +447,6 @@ E0745: include_str!("./error_codes/E0745.md"), // E0190, // deprecated: can only cast a &-pointer to an &-object // E0194, // merged into E0403 // E0196, // cannot determine a type for this closure - E0203, // type parameter has more than one relaxed default bound, - // and only one is supported E0208, // E0209, // builtin traits can only be implemented on structs or enums E0212, // cannot extract an associated type from a higher-ranked trait bound diff --git a/src/librustc_error_codes/error_codes/E0203.md b/src/librustc_error_codes/error_codes/E0203.md new file mode 100644 index 0000000000000..792ed3cb8bb8f --- /dev/null +++ b/src/librustc_error_codes/error_codes/E0203.md @@ -0,0 +1,12 @@ +Having multiple relaxed default bounds is unsuported. + +Erroneous code example: + +```compile_fail,E0203 + +trait Foo {} + +struct S5(*const T) where T: ?Foo + ?Sized; +``` + +Here the type `T` cannot have a relaxed bound for both `Foo` and `Sized` diff --git a/src/test/ui/maybe-bounds-where.stderr b/src/test/ui/maybe-bounds-where.stderr index 15cbce46f0a9b..19f9cd28a9a01 100644 --- a/src/test/ui/maybe-bounds-where.stderr +++ b/src/test/ui/maybe-bounds-where.stderr @@ -42,3 +42,4 @@ LL | struct S5(*const T) where T: ?Trait<'static> + ?Sized; error: aborting due to 6 previous errors +For more information about this error, try `rustc --explain E0203`. From 52426ab42dffadfcaec7d1eb4afa4d63cca11593 Mon Sep 17 00:00:00 2001 From: cad97 Date: Sun, 24 Nov 2019 21:09:37 -0500 Subject: [PATCH 16/20] Use recursion_limit for const eval stack limit --- src/librustc/session/mod.rs | 4 ---- src/librustc_mir/interpret/eval_context.rs | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 0b9d04ca6a3b5..c6c5f3b68df6d 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -95,9 +95,6 @@ pub struct Session { /// The maximum length of types during monomorphization. pub type_length_limit: Once, - /// The maximum number of stackframes allowed in const eval. - pub const_eval_stack_frame_limit: usize, - /// Map from imported macro spans (which consist of /// the localized span for the macro body) to the /// macro name and definition span in the source crate. @@ -1159,7 +1156,6 @@ fn build_session_( features: Once::new(), recursion_limit: Once::new(), type_length_limit: Once::new(), - const_eval_stack_frame_limit: 100, imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())), incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)), cgu_reuse_tracker, diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 626e81fa91186..228e5cad4e367 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -548,7 +548,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance); - if self.stack.len() > self.tcx.sess.const_eval_stack_frame_limit { + if self.stack.len() > *self.tcx.sess.recursion_limit.get() { throw_exhaust!(StackFrameLimitReached) } else { Ok(()) From 1c4d4539690fe841aefea2f54c243be5f0579970 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 29 Nov 2019 19:30:49 -0800 Subject: [PATCH 17/20] Format liballoc with rustfmt --- src/liballoc/alloc/tests.rs | 6 +- src/liballoc/benches/btree/map.rs | 38 ++-- src/liballoc/benches/slice.rs | 63 +++---- src/liballoc/benches/str.rs | 35 ++-- src/liballoc/benches/vec_deque.rs | 2 +- src/liballoc/benches/vec_deque_append.rs | 5 +- src/liballoc/collections/btree/mod.rs | 2 +- src/liballoc/collections/btree/search.rs | 42 +++-- src/liballoc/collections/linked_list/tests.rs | 17 +- src/liballoc/collections/vec_deque/tests.rs | 12 +- src/liballoc/fmt.rs | 22 +-- src/liballoc/prelude/v1.rs | 12 +- src/liballoc/raw_vec/tests.rs | 9 +- src/liballoc/slice.rs | 173 ++++++++++-------- src/liballoc/tests.rs | 6 +- src/liballoc/tests/arc.rs | 39 ++-- src/liballoc/tests/boxed.rs | 2 +- src/liballoc/tests/btree/mod.rs | 7 +- src/liballoc/tests/linked_list.rs | 75 +++----- src/liballoc/tests/rc.rs | 41 ++--- src/liballoc/tests/vec_deque.rs | 166 ++++++++--------- 21 files changed, 373 insertions(+), 401 deletions(-) diff --git a/src/liballoc/alloc/tests.rs b/src/liballoc/alloc/tests.rs index c69f4e49ee1e3..956298d7836b8 100644 --- a/src/liballoc/alloc/tests.rs +++ b/src/liballoc/alloc/tests.rs @@ -1,15 +1,15 @@ use super::*; extern crate test; -use test::Bencher; use crate::boxed::Box; +use test::Bencher; #[test] fn allocate_zeroed() { unsafe { let layout = Layout::from_size_align(1024, 1).unwrap(); - let ptr = Global.alloc_zeroed(layout.clone()) - .unwrap_or_else(|_| handle_alloc_error(layout)); + let ptr = + Global.alloc_zeroed(layout.clone()).unwrap_or_else(|_| handle_alloc_error(layout)); let mut i = ptr.cast::().as_ptr(); let end = i.add(layout.size()); diff --git a/src/liballoc/benches/btree/map.rs b/src/liballoc/benches/btree/map.rs index b541fa94e954e..eb5f51d9adc58 100644 --- a/src/liballoc/benches/btree/map.rs +++ b/src/liballoc/benches/btree/map.rs @@ -1,12 +1,12 @@ +use std::collections::BTreeMap; use std::iter::Iterator; use std::vec::Vec; -use std::collections::BTreeMap; -use rand::{Rng, seq::SliceRandom, thread_rng}; -use test::{Bencher, black_box}; +use rand::{seq::SliceRandom, thread_rng, Rng}; +use test::{black_box, Bencher}; macro_rules! map_insert_rand_bench { - ($name: ident, $n: expr, $map: ident) => ( + ($name: ident, $n: expr, $map: ident) => { #[bench] pub fn $name(b: &mut Bencher) { let n: usize = $n; @@ -27,11 +27,11 @@ macro_rules! map_insert_rand_bench { }); black_box(map); } - ) + }; } macro_rules! map_insert_seq_bench { - ($name: ident, $n: expr, $map: ident) => ( + ($name: ident, $n: expr, $map: ident) => { #[bench] pub fn $name(b: &mut Bencher) { let mut map = $map::new(); @@ -50,11 +50,11 @@ macro_rules! map_insert_seq_bench { }); black_box(map); } - ) + }; } macro_rules! map_find_rand_bench { - ($name: ident, $n: expr, $map: ident) => ( + ($name: ident, $n: expr, $map: ident) => { #[bench] pub fn $name(b: &mut Bencher) { let mut map = $map::new(); @@ -78,11 +78,11 @@ macro_rules! map_find_rand_bench { black_box(t); }) } - ) + }; } macro_rules! map_find_seq_bench { - ($name: ident, $n: expr, $map: ident) => ( + ($name: ident, $n: expr, $map: ident) => { #[bench] pub fn $name(b: &mut Bencher) { let mut map = $map::new(); @@ -101,20 +101,20 @@ macro_rules! map_find_seq_bench { black_box(x); }) } - ) + }; } -map_insert_rand_bench!{insert_rand_100, 100, BTreeMap} -map_insert_rand_bench!{insert_rand_10_000, 10_000, BTreeMap} +map_insert_rand_bench! {insert_rand_100, 100, BTreeMap} +map_insert_rand_bench! {insert_rand_10_000, 10_000, BTreeMap} -map_insert_seq_bench!{insert_seq_100, 100, BTreeMap} -map_insert_seq_bench!{insert_seq_10_000, 10_000, BTreeMap} +map_insert_seq_bench! {insert_seq_100, 100, BTreeMap} +map_insert_seq_bench! {insert_seq_10_000, 10_000, BTreeMap} -map_find_rand_bench!{find_rand_100, 100, BTreeMap} -map_find_rand_bench!{find_rand_10_000, 10_000, BTreeMap} +map_find_rand_bench! {find_rand_100, 100, BTreeMap} +map_find_rand_bench! {find_rand_10_000, 10_000, BTreeMap} -map_find_seq_bench!{find_seq_100, 100, BTreeMap} -map_find_seq_bench!{find_seq_10_000, 10_000, BTreeMap} +map_find_seq_bench! {find_seq_100, 100, BTreeMap} +map_find_seq_bench! {find_seq_10_000, 10_000, BTreeMap} fn bench_iter(b: &mut Bencher, size: i32) { let mut map = BTreeMap::::new(); diff --git a/src/liballoc/benches/slice.rs b/src/liballoc/benches/slice.rs index ef91d801dc72c..e20c043286e6f 100644 --- a/src/liballoc/benches/slice.rs +++ b/src/liballoc/benches/slice.rs @@ -1,9 +1,9 @@ use std::{mem, ptr}; +use rand::distributions::{Alphanumeric, Standard}; use rand::{thread_rng, Rng, SeedableRng}; -use rand::distributions::{Standard, Alphanumeric}; use rand_xorshift::XorShiftRng; -use test::{Bencher, black_box}; +use test::{black_box, Bencher}; #[bench] fn iterator(b: &mut Bencher) { @@ -239,7 +239,7 @@ macro_rules! sort { b.iter(|| v.clone().$f()); b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64; } - } + }; } macro_rules! sort_strings { @@ -251,7 +251,7 @@ macro_rules! sort_strings { b.iter(|| v.clone().$f()); b.bytes = $len * mem::size_of::<&str>() as u64; } - } + }; } macro_rules! sort_expensive { @@ -273,7 +273,7 @@ macro_rules! sort_expensive { }); b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64; } - } + }; } macro_rules! sort_lexicographic { @@ -284,7 +284,7 @@ macro_rules! sort_lexicographic { b.iter(|| v.clone().$f(|x| x.to_string())); b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64; } - } + }; } sort!(sort, sort_small_ascending, gen_ascending, 10); @@ -325,24 +325,25 @@ macro_rules! reverse { fn $name(b: &mut Bencher) { // odd length and offset by 1 to be as unaligned as possible let n = 0xFFFFF; - let mut v: Vec<_> = - (0..1+(n / mem::size_of::<$ty>() as u64)) - .map($f) - .collect(); + let mut v: Vec<_> = (0..1 + (n / mem::size_of::<$ty>() as u64)).map($f).collect(); b.iter(|| black_box(&mut v[1..]).reverse()); b.bytes = n; } - } + }; } reverse!(reverse_u8, u8, |x| x as u8); reverse!(reverse_u16, u16, |x| x as u16); -reverse!(reverse_u8x3, [u8;3], |x| [x as u8, (x>>8) as u8, (x>>16) as u8]); +reverse!(reverse_u8x3, [u8; 3], |x| [x as u8, (x >> 8) as u8, (x >> 16) as u8]); reverse!(reverse_u32, u32, |x| x as u32); reverse!(reverse_u64, u64, |x| x as u64); reverse!(reverse_u128, u128, |x| x as u128); -#[repr(simd)] struct F64x4(f64, f64, f64, f64); -reverse!(reverse_simd_f64x4, F64x4, |x| { let x = x as f64; F64x4(x,x,x,x) }); +#[repr(simd)] +struct F64x4(f64, f64, f64, f64); +reverse!(reverse_simd_f64x4, F64x4, |x| { + let x = x as f64; + F64x4(x, x, x, x) +}); macro_rules! rotate { ($name:ident, $gen:expr, $len:expr, $mid:expr) => { @@ -350,32 +351,32 @@ macro_rules! rotate { fn $name(b: &mut Bencher) { let size = mem::size_of_val(&$gen(1)[0]); let mut v = $gen($len * 8 / size); - b.iter(|| black_box(&mut v).rotate_left(($mid*8+size-1)/size)); + b.iter(|| black_box(&mut v).rotate_left(($mid * 8 + size - 1) / size)); b.bytes = (v.len() * size) as u64; } - } + }; } rotate!(rotate_tiny_by1, gen_random, 16, 1); -rotate!(rotate_tiny_half, gen_random, 16, 16/2); -rotate!(rotate_tiny_half_plus_one, gen_random, 16, 16/2+1); +rotate!(rotate_tiny_half, gen_random, 16, 16 / 2); +rotate!(rotate_tiny_half_plus_one, gen_random, 16, 16 / 2 + 1); rotate!(rotate_medium_by1, gen_random, 9158, 1); rotate!(rotate_medium_by727_u64, gen_random, 9158, 727); rotate!(rotate_medium_by727_bytes, gen_random_bytes, 9158, 727); rotate!(rotate_medium_by727_strings, gen_strings, 9158, 727); -rotate!(rotate_medium_half, gen_random, 9158, 9158/2); -rotate!(rotate_medium_half_plus_one, gen_random, 9158, 9158/2+1); +rotate!(rotate_medium_half, gen_random, 9158, 9158 / 2); +rotate!(rotate_medium_half_plus_one, gen_random, 9158, 9158 / 2 + 1); // Intended to use more RAM than the machine has cache -rotate!(rotate_huge_by1, gen_random, 5*1024*1024, 1); -rotate!(rotate_huge_by9199_u64, gen_random, 5*1024*1024, 9199); -rotate!(rotate_huge_by9199_bytes, gen_random_bytes, 5*1024*1024, 9199); -rotate!(rotate_huge_by9199_strings, gen_strings, 5*1024*1024, 9199); -rotate!(rotate_huge_by9199_big, gen_big_random, 5*1024*1024, 9199); -rotate!(rotate_huge_by1234577_u64, gen_random, 5*1024*1024, 1234577); -rotate!(rotate_huge_by1234577_bytes, gen_random_bytes, 5*1024*1024, 1234577); -rotate!(rotate_huge_by1234577_strings, gen_strings, 5*1024*1024, 1234577); -rotate!(rotate_huge_by1234577_big, gen_big_random, 5*1024*1024, 1234577); -rotate!(rotate_huge_half, gen_random, 5*1024*1024, 5*1024*1024/2); -rotate!(rotate_huge_half_plus_one, gen_random, 5*1024*1024, 5*1024*1024/2+1); +rotate!(rotate_huge_by1, gen_random, 5 * 1024 * 1024, 1); +rotate!(rotate_huge_by9199_u64, gen_random, 5 * 1024 * 1024, 9199); +rotate!(rotate_huge_by9199_bytes, gen_random_bytes, 5 * 1024 * 1024, 9199); +rotate!(rotate_huge_by9199_strings, gen_strings, 5 * 1024 * 1024, 9199); +rotate!(rotate_huge_by9199_big, gen_big_random, 5 * 1024 * 1024, 9199); +rotate!(rotate_huge_by1234577_u64, gen_random, 5 * 1024 * 1024, 1234577); +rotate!(rotate_huge_by1234577_bytes, gen_random_bytes, 5 * 1024 * 1024, 1234577); +rotate!(rotate_huge_by1234577_strings, gen_strings, 5 * 1024 * 1024, 1234577); +rotate!(rotate_huge_by1234577_big, gen_big_random, 5 * 1024 * 1024, 1234577); +rotate!(rotate_huge_half, gen_random, 5 * 1024 * 1024, 5 * 1024 * 1024 / 2); +rotate!(rotate_huge_half_plus_one, gen_random, 5 * 1024 * 1024, 5 * 1024 * 1024 / 2 + 1); diff --git a/src/liballoc/benches/str.rs b/src/liballoc/benches/str.rs index 7f8661bd96888..391475bc0c75d 100644 --- a/src/liballoc/benches/str.rs +++ b/src/liballoc/benches/str.rs @@ -1,4 +1,4 @@ -use test::{Bencher, black_box}; +use test::{black_box, Bencher}; #[bench] fn char_iterator(b: &mut Bencher) { @@ -12,7 +12,9 @@ fn char_iterator_for(b: &mut Bencher) { let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; b.iter(|| { - for ch in s.chars() { black_box(ch); } + for ch in s.chars() { + black_box(ch); + } }); } @@ -40,7 +42,9 @@ fn char_iterator_rev_for(b: &mut Bencher) { let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; b.iter(|| { - for ch in s.chars().rev() { black_box(ch); } + for ch in s.chars().rev() { + black_box(ch); + } }); } @@ -79,7 +83,9 @@ fn split_ascii(b: &mut Bencher) { fn split_extern_fn(b: &mut Bencher) { let s = "Mary had a little lamb, Little lamb, little-lamb."; let len = s.split(' ').count(); - fn pred(c: char) -> bool { c == ' ' } + fn pred(c: char) -> bool { + c == ' ' + } b.iter(|| assert_eq!(s.split(pred).count(), len)); } @@ -185,16 +191,19 @@ fn bench_contains_equal(b: &mut Bencher) { }) } - macro_rules! make_test_inner { ($s:ident, $code:expr, $name:ident, $str:expr, $iters:expr) => { #[bench] fn $name(bencher: &mut Bencher) { let mut $s = $str; black_box(&mut $s); - bencher.iter(|| for _ in 0..$iters { black_box($code); }); + bencher.iter(|| { + for _ in 0..$iters { + black_box($code); + } + }); } - } + }; } macro_rules! make_test { @@ -261,15 +270,9 @@ make_test!(match_indices_a_str, s, s.match_indices("a").count()); make_test!(split_a_str, s, s.split("a").count()); -make_test!(trim_ascii_char, s, { - s.trim_matches(|c: char| c.is_ascii()) -}); -make_test!(trim_start_ascii_char, s, { - s.trim_start_matches(|c: char| c.is_ascii()) -}); -make_test!(trim_end_ascii_char, s, { - s.trim_end_matches(|c: char| c.is_ascii()) -}); +make_test!(trim_ascii_char, s, { s.trim_matches(|c: char| c.is_ascii()) }); +make_test!(trim_start_ascii_char, s, { s.trim_start_matches(|c: char| c.is_ascii()) }); +make_test!(trim_end_ascii_char, s, { s.trim_end_matches(|c: char| c.is_ascii()) }); make_test!(find_underscore_char, s, s.find('_')); make_test!(rfind_underscore_char, s, s.rfind('_')); diff --git a/src/liballoc/benches/vec_deque.rs b/src/liballoc/benches/vec_deque.rs index 7d2d3cfa61225..bf2dffd1e931e 100644 --- a/src/liballoc/benches/vec_deque.rs +++ b/src/liballoc/benches/vec_deque.rs @@ -1,5 +1,5 @@ use std::collections::VecDeque; -use test::{Bencher, black_box}; +use test::{black_box, Bencher}; #[bench] fn bench_new(b: &mut Bencher) { diff --git a/src/liballoc/benches/vec_deque_append.rs b/src/liballoc/benches/vec_deque_append.rs index 78ec91d9e3e9b..5825bdc355f2d 100644 --- a/src/liballoc/benches/vec_deque_append.rs +++ b/src/liballoc/benches/vec_deque_append.rs @@ -30,8 +30,5 @@ fn main() { assert!(BENCH_N % 2 == 0); let median = (durations[(l / 2) - 1] + durations[l / 2]) / 2; - println!( - "\ncustom-bench vec_deque_append {:?} ns/iter\n", - median.as_nanos() - ); + println!("\ncustom-bench vec_deque_append {:?} ns/iter\n", median.as_nanos()); } diff --git a/src/liballoc/collections/btree/mod.rs b/src/liballoc/collections/btree/mod.rs index 8b7dc07063b62..f73a24d09916b 100644 --- a/src/liballoc/collections/btree/mod.rs +++ b/src/liballoc/collections/btree/mod.rs @@ -1,6 +1,6 @@ +pub mod map; mod node; mod search; -pub mod map; pub mod set; #[doc(hidden)] diff --git a/src/liballoc/collections/btree/search.rs b/src/liballoc/collections/btree/search.rs index dfb67d2ea5756..3f3c49a2ef875 100644 --- a/src/liballoc/collections/btree/search.rs +++ b/src/liballoc/collections/btree/search.rs @@ -1,21 +1,23 @@ use core::borrow::Borrow; use core::cmp::Ordering; -use super::node::{Handle, NodeRef, marker, ForceResult::*}; +use super::node::{marker, ForceResult::*, Handle, NodeRef}; use SearchResult::*; pub enum SearchResult { Found(Handle, marker::KV>), - GoDown(Handle, marker::Edge>) + GoDown(Handle, marker::Edge>), } pub fn search_tree( mut node: NodeRef, - key: &Q + key: &Q, ) -> SearchResult - where Q: Ord, K: Borrow { - +where + Q: Ord, + K: Borrow, +{ loop { match search_node(node, key) { Found(handle) => return Found(handle), @@ -25,38 +27,38 @@ pub fn search_tree( node = internal.descend(); continue; } - } + }, } } } pub fn search_node( node: NodeRef, - key: &Q + key: &Q, ) -> SearchResult - where Q: Ord, K: Borrow { - +where + Q: Ord, + K: Borrow, +{ match search_linear(&node, key) { - (idx, true) => Found( - Handle::new_kv(node, idx) - ), - (idx, false) => SearchResult::GoDown( - Handle::new_edge(node, idx) - ) + (idx, true) => Found(Handle::new_kv(node, idx)), + (idx, false) => SearchResult::GoDown(Handle::new_edge(node, idx)), } } pub fn search_linear( node: &NodeRef, - key: &Q + key: &Q, ) -> (usize, bool) - where Q: Ord, K: Borrow { - +where + Q: Ord, + K: Borrow, +{ for (i, k) in node.keys().iter().enumerate() { match key.cmp(k.borrow()) { - Ordering::Greater => {}, + Ordering::Greater => {} Ordering::Equal => return (i, true), - Ordering::Less => return (i, false) + Ordering::Less => return (i, false), } } (node.keys().len(), false) diff --git a/src/liballoc/collections/linked_list/tests.rs b/src/liballoc/collections/linked_list/tests.rs index 1001f6bba3b82..94b92df129400 100644 --- a/src/liballoc/collections/linked_list/tests.rs +++ b/src/liballoc/collections/linked_list/tests.rs @@ -177,8 +177,7 @@ fn test_insert_prev() { } check_links(&m); assert_eq!(m.len(), 3 + len * 2); - assert_eq!(m.into_iter().collect::>(), - [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]); + assert_eq!(m.into_iter().collect::>(), [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]); } #[test] @@ -187,13 +186,13 @@ fn test_insert_prev() { fn test_send() { let n = list_from(&[1, 2, 3]); thread::spawn(move || { - check_links(&n); - let a: &[_] = &[&1, &2, &3]; - assert_eq!(a, &*n.iter().collect::>()); - }) - .join() - .ok() - .unwrap(); + check_links(&n); + let a: &[_] = &[&1, &2, &3]; + assert_eq!(a, &*n.iter().collect::>()); + }) + .join() + .ok() + .unwrap(); } #[test] diff --git a/src/liballoc/collections/vec_deque/tests.rs b/src/liballoc/collections/vec_deque/tests.rs index 09009ff516ac8..8dc097cc08805 100644 --- a/src/liballoc/collections/vec_deque/tests.rs +++ b/src/liballoc/collections/vec_deque/tests.rs @@ -66,11 +66,8 @@ fn test_swap_front_back_remove() { let final_len = usable_cap / 2; for len in 0..final_len { - let expected: VecDeque<_> = if back { - (0..len).collect() - } else { - (0..len).rev().collect() - }; + let expected: VecDeque<_> = + if back { (0..len).collect() } else { (0..len).rev().collect() }; for tail_pos in 0..usable_cap { tester.tail = tail_pos; tester.head = tail_pos; @@ -111,7 +108,6 @@ fn test_insert() { // this test isn't covering what it wants to let cap = tester.capacity(); - // len is the length *after* insertion for len in 1..cap { // 0, 1, 2, .., len - 1 @@ -198,9 +194,7 @@ fn test_drain() { assert!(tester.head < tester.cap()); // We should see the correct values in the VecDeque - let expected: VecDeque<_> = (0..drain_start) - .chain(drain_end..len) - .collect(); + let expected: VecDeque<_> = (0..drain_start).chain(drain_end..len).collect(); assert_eq!(expected, tester); } } diff --git a/src/liballoc/fmt.rs b/src/liballoc/fmt.rs index cbfc55233a1e0..18ebae333098f 100644 --- a/src/liballoc/fmt.rs +++ b/src/liballoc/fmt.rs @@ -516,24 +516,24 @@ #[unstable(feature = "fmt_internals", issue = "0")] pub use core::fmt::rt; +#[stable(feature = "fmt_flags_align", since = "1.28.0")] +pub use core::fmt::Alignment; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::fmt::{Formatter, Result, Write}; +pub use core::fmt::Error; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::fmt::{write, ArgumentV1, Arguments}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Binary, Octal}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Debug, Display}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::fmt::{LowerHex, Pointer, UpperHex}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::fmt::{LowerExp, UpperExp}; +pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::fmt::Error; +pub use core::fmt::{Formatter, Result, Write}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::fmt::{write, ArgumentV1, Arguments}; +pub use core::fmt::{LowerExp, UpperExp}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; -#[stable(feature = "fmt_flags_align", since = "1.28.0")] -pub use core::fmt::{Alignment}; +pub use core::fmt::{LowerHex, Pointer, UpperHex}; use crate::string; @@ -568,8 +568,6 @@ use crate::string; pub fn format(args: Arguments<'_>) -> string::String { let capacity = args.estimated_capacity(); let mut output = string::String::with_capacity(capacity); - output - .write_fmt(args) - .expect("a formatting trait implementation returned an error"); + output.write_fmt(args).expect("a formatting trait implementation returned an error"); output } diff --git a/src/liballoc/prelude/v1.rs b/src/liballoc/prelude/v1.rs index 3cb285bf0492f..6a53b4ca1f6ca 100644 --- a/src/liballoc/prelude/v1.rs +++ b/src/liballoc/prelude/v1.rs @@ -4,7 +4,11 @@ #![unstable(feature = "alloc_prelude", issue = "58935")] -#[unstable(feature = "alloc_prelude", issue = "58935")] pub use crate::borrow::ToOwned; -#[unstable(feature = "alloc_prelude", issue = "58935")] pub use crate::boxed::Box; -#[unstable(feature = "alloc_prelude", issue = "58935")] pub use crate::string::{String, ToString}; -#[unstable(feature = "alloc_prelude", issue = "58935")] pub use crate::vec::Vec; +#[unstable(feature = "alloc_prelude", issue = "58935")] +pub use crate::borrow::ToOwned; +#[unstable(feature = "alloc_prelude", issue = "58935")] +pub use crate::boxed::Box; +#[unstable(feature = "alloc_prelude", issue = "58935")] +pub use crate::string::{String, ToString}; +#[unstable(feature = "alloc_prelude", issue = "58935")] +pub use crate::vec::Vec; diff --git a/src/liballoc/raw_vec/tests.rs b/src/liballoc/raw_vec/tests.rs index d35b62fc1ef15..b214cef301115 100644 --- a/src/liballoc/raw_vec/tests.rs +++ b/src/liballoc/raw_vec/tests.rs @@ -16,7 +16,9 @@ fn allocator_param() { // A dumb allocator that consumes a fixed amount of fuel // before allocation attempts start failing. - struct BoundedAlloc { fuel: usize } + struct BoundedAlloc { + fuel: usize, + } unsafe impl Alloc for BoundedAlloc { unsafe fn alloc(&mut self, layout: Layout) -> Result, AllocErr> { let size = layout.size(); @@ -24,7 +26,10 @@ fn allocator_param() { return Err(AllocErr); } match Global.alloc(layout) { - ok @ Ok(_) => { self.fuel -= size; ok } + ok @ Ok(_) => { + self.fuel -= size; + ok + } err @ Err(_) => err, } } diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 08243ef7c519f..2f6d10c027be3 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -82,7 +82,6 @@ //! [`.chunks`]: ../../std/primitive.slice.html#method.chunks //! [`.windows`]: ../../std/primitive.slice.html#method.windows #![stable(feature = "rust1", since = "1.0.0")] - // Many of the usings in this module are only used in the test configuration. // It's cleaner to just turn off the unused_imports warning than to fix them. #![cfg_attr(test, allow(unused_imports, dead_code))] @@ -91,32 +90,32 @@ use core::borrow::{Borrow, BorrowMut}; use core::cmp::Ordering::{self, Less}; use core::mem::{self, size_of}; use core::ptr; -use core::{u8, u16, u32}; +use core::{u16, u32, u8}; use crate::borrow::ToOwned; use crate::boxed::Box; use crate::vec::Vec; +#[stable(feature = "slice_get_slice", since = "1.28.0")] +pub use core::slice::SliceIndex; +#[stable(feature = "from_ref", since = "1.28.0")] +pub use core::slice::{from_mut, from_ref}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::slice::{Chunks, Windows}; +pub use core::slice::{from_raw_parts, from_raw_parts_mut}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::slice::{Iter, IterMut}; +pub use core::slice::{Chunks, Windows}; +#[stable(feature = "chunks_exact", since = "1.31.0")] +pub use core::slice::{ChunksExact, ChunksExactMut}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::slice::{SplitMut, ChunksMut, Split}; +pub use core::slice::{ChunksMut, Split, SplitMut}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut}; +pub use core::slice::{Iter, IterMut}; +#[stable(feature = "rchunks", since = "1.31.0")] +pub use core::slice::{RChunks, RChunksExact, RChunksExactMut, RChunksMut}; #[stable(feature = "slice_rsplit", since = "1.27.0")] pub use core::slice::{RSplit, RSplitMut}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::slice::{from_raw_parts, from_raw_parts_mut}; -#[stable(feature = "from_ref", since = "1.28.0")] -pub use core::slice::{from_ref, from_mut}; -#[stable(feature = "slice_get_slice", since = "1.28.0")] -pub use core::slice::SliceIndex; -#[stable(feature = "chunks_exact", since = "1.31.0")] -pub use core::slice::{ChunksExact, ChunksExactMut}; -#[stable(feature = "rchunks", since = "1.31.0")] -pub use core::slice::{RChunks, RChunksMut, RChunksExact, RChunksExactMut}; +pub use core::slice::{RSplitN, RSplitNMut, SplitN, SplitNMut}; //////////////////////////////////////////////////////////////////////////////// // Basic slice extension methods @@ -138,9 +137,9 @@ pub use hack::to_vec; // `test_permutations` test mod hack { use crate::boxed::Box; - use crate::vec::Vec; #[cfg(test)] use crate::string::ToString; + use crate::vec::Vec; pub fn into_vec(b: Box<[T]>) -> Vec { unsafe { @@ -153,7 +152,8 @@ mod hack { #[inline] pub fn to_vec(s: &[T]) -> Vec - where T: Clone + where + T: Clone, { let mut vector = Vec::with_capacity(s.len()); vector.extend_from_slice(s); @@ -193,7 +193,8 @@ impl [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn sort(&mut self) - where T: Ord + where + T: Ord, { merge_sort(self, |a, b| a.lt(b)); } @@ -246,7 +247,8 @@ impl [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn sort_by(&mut self, mut compare: F) - where F: FnMut(&T, &T) -> Ordering + where + F: FnMut(&T, &T) -> Ordering, { merge_sort(self, |a, b| compare(a, b) == Less); } @@ -285,7 +287,9 @@ impl [T] { #[stable(feature = "slice_sort_by_key", since = "1.7.0")] #[inline] pub fn sort_by_key(&mut self, mut f: F) - where F: FnMut(&T) -> K, K: Ord + where + F: FnMut(&T) -> K, + K: Ord, { merge_sort(self, |a, b| f(a).lt(&f(b))); } @@ -325,11 +329,13 @@ impl [T] { #[stable(feature = "slice_sort_by_cached_key", since = "1.34.0")] #[inline] pub fn sort_by_cached_key(&mut self, f: F) - where F: FnMut(&T) -> K, K: Ord + where + F: FnMut(&T) -> K, + K: Ord, { // Helper macro for indexing our vector by the smallest possible type, to reduce allocation. macro_rules! sort_by_key { - ($t:ty, $slice:ident, $f:ident) => ({ + ($t:ty, $slice:ident, $f:ident) => {{ let mut indices: Vec<_> = $slice.iter().map($f).enumerate().map(|(i, k)| (k, i as $t)).collect(); // The elements of `indices` are unique, as they are indexed, so any sort will be @@ -344,19 +350,27 @@ impl [T] { indices[i].1 = index; $slice.swap(i, index as usize); } - }) + }}; } - let sz_u8 = mem::size_of::<(K, u8)>(); - let sz_u16 = mem::size_of::<(K, u16)>(); - let sz_u32 = mem::size_of::<(K, u32)>(); + let sz_u8 = mem::size_of::<(K, u8)>(); + let sz_u16 = mem::size_of::<(K, u16)>(); + let sz_u32 = mem::size_of::<(K, u32)>(); let sz_usize = mem::size_of::<(K, usize)>(); let len = self.len(); - if len < 2 { return } - if sz_u8 < sz_u16 && len <= ( u8::MAX as usize) { return sort_by_key!( u8, self, f) } - if sz_u16 < sz_u32 && len <= (u16::MAX as usize) { return sort_by_key!(u16, self, f) } - if sz_u32 < sz_usize && len <= (u32::MAX as usize) { return sort_by_key!(u32, self, f) } + if len < 2 { + return; + } + if sz_u8 < sz_u16 && len <= (u8::MAX as usize) { + return sort_by_key!(u8, self, f); + } + if sz_u16 < sz_u32 && len <= (u16::MAX as usize) { + return sort_by_key!(u16, self, f); + } + if sz_u32 < sz_usize && len <= (u32::MAX as usize) { + return sort_by_key!(u32, self, f); + } sort_by_key!(usize, self, f) } @@ -373,7 +387,8 @@ impl [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_vec(&self) -> Vec - where T: Clone + where + T: Clone, { // N.B., see the `hack` module in this file for more details. hack::to_vec(self) @@ -421,7 +436,10 @@ impl [T] { /// b"0123456789abcdef".repeat(usize::max_value()); /// ``` #[stable(feature = "repeat_generic_slice", since = "1.40.0")] - pub fn repeat(&self, n: usize) -> Vec where T: Copy { + pub fn repeat(&self, n: usize) -> Vec + where + T: Copy, + { if n == 0 { return Vec::new(); } @@ -486,7 +504,8 @@ impl [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn concat(&self) -> >::Output - where Self: Concat + where + Self: Concat, { Concat::concat(self) } @@ -503,7 +522,8 @@ impl [T] { /// ``` #[stable(feature = "rename_connect_to_join", since = "1.3.0")] pub fn join(&self, sep: Separator) -> >::Output - where Self: Join + where + Self: Join, { Join::join(self, sep) } @@ -521,11 +541,11 @@ impl [T] { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")] pub fn connect(&self, sep: Separator) -> >::Output - where Self: Join + where + Self: Join, { Join::join(self, sep) } - } #[lang = "slice_u8_alloc"] @@ -668,8 +688,8 @@ impl> Join<&[T]> for [V] { Some(first) => first, None => return vec![], }; - let size = slice.iter().map(|v| v.borrow().len()).sum::() + - sep.len() * (slice.len() - 1); + let size = + slice.iter().map(|v| v.borrow().len()).sum::() + sep.len() * (slice.len() - 1); let mut result = Vec::with_capacity(size); result.extend_from_slice(first.borrow()); @@ -734,7 +754,8 @@ impl ToOwned for [T] { /// /// This is the integral subroutine of insertion sort. fn insert_head(v: &mut [T], is_less: &mut F) - where F: FnMut(&T, &T) -> bool +where + F: FnMut(&T, &T) -> bool, { if v.len() >= 2 && is_less(&v[1], &v[0]) { unsafe { @@ -767,10 +788,7 @@ fn insert_head(v: &mut [T], is_less: &mut F) // If `is_less` panics at any point during the process, `hole` will get dropped and // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it // initially held exactly once. - let mut hole = InsertionHole { - src: &mut *tmp, - dest: &mut v[1], - }; + let mut hole = InsertionHole { src: &mut *tmp, dest: &mut v[1] }; ptr::copy_nonoverlapping(&v[1], &mut v[0], 1); for i in 2..v.len() { @@ -792,7 +810,9 @@ fn insert_head(v: &mut [T], is_less: &mut F) impl Drop for InsertionHole { fn drop(&mut self) { - unsafe { ptr::copy_nonoverlapping(self.src, self.dest, 1); } + unsafe { + ptr::copy_nonoverlapping(self.src, self.dest, 1); + } } } } @@ -805,7 +825,8 @@ fn insert_head(v: &mut [T], is_less: &mut F) /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type. unsafe fn merge(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F) - where F: FnMut(&T, &T) -> bool +where + F: FnMut(&T, &T) -> bool, { let len = v.len(); let v = v.as_mut_ptr(); @@ -834,11 +855,7 @@ unsafe fn merge(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F) if mid <= len - mid { // The left run is shorter. ptr::copy_nonoverlapping(v, buf, mid); - hole = MergeHole { - start: buf, - end: buf.add(mid), - dest: v, - }; + hole = MergeHole { start: buf, end: buf.add(mid), dest: v }; // Initially, these pointers point to the beginnings of their arrays. let left = &mut hole.start; @@ -858,11 +875,7 @@ unsafe fn merge(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F) } else { // The right run is shorter. ptr::copy_nonoverlapping(v_mid, buf, len - mid); - hole = MergeHole { - start: buf, - end: buf.add(len - mid), - dest: v_mid, - }; + hole = MergeHole { start: buf, end: buf.add(len - mid), dest: v_mid }; // Initially, these pointers point past the ends of their arrays. let left = &mut hole.dest; @@ -905,7 +918,9 @@ unsafe fn merge(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F) fn drop(&mut self) { // `T` is not a zero-sized type, so it's okay to divide by its size. let len = (self.end as usize - self.start as usize) / mem::size_of::(); - unsafe { ptr::copy_nonoverlapping(self.start, self.dest, len); } + unsafe { + ptr::copy_nonoverlapping(self.start, self.dest, len); + } } } } @@ -923,7 +938,8 @@ unsafe fn merge(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F) /// /// The invariants ensure that the total running time is `O(n log n)` worst-case. fn merge_sort(v: &mut [T], mut is_less: F) - where F: FnMut(&T, &T) -> bool +where + F: FnMut(&T, &T) -> bool, { // Slices of up to this length get sorted using insertion sort. const MAX_INSERTION: usize = 20; @@ -940,7 +956,7 @@ fn merge_sort(v: &mut [T], mut is_less: F) // Short arrays get sorted in-place via insertion sort to avoid allocations. if len <= MAX_INSERTION { if len >= 2 { - for i in (0..len-1).rev() { + for i in (0..len - 1).rev() { insert_head(&mut v[i..], &mut is_less); } } @@ -966,14 +982,13 @@ fn merge_sort(v: &mut [T], mut is_less: F) start -= 1; unsafe { if is_less(v.get_unchecked(start + 1), v.get_unchecked(start)) { - while start > 0 && is_less(v.get_unchecked(start), - v.get_unchecked(start - 1)) { + while start > 0 && is_less(v.get_unchecked(start), v.get_unchecked(start - 1)) { start -= 1; } v[start..end].reverse(); } else { - while start > 0 && !is_less(v.get_unchecked(start), - v.get_unchecked(start - 1)) { + while start > 0 && !is_less(v.get_unchecked(start), v.get_unchecked(start - 1)) + { start -= 1; } } @@ -988,10 +1003,7 @@ fn merge_sort(v: &mut [T], mut is_less: F) } // Push this run onto the stack. - runs.push(Run { - start, - len: end - start, - }); + runs.push(Run { start, len: end - start }); end = start; // Merge some pairs of adjacent runs to satisfy the invariants. @@ -999,13 +1011,14 @@ fn merge_sort(v: &mut [T], mut is_less: F) let left = runs[r + 1]; let right = runs[r]; unsafe { - merge(&mut v[left.start .. right.start + right.len], left.len, buf.as_mut_ptr(), - &mut is_less); + merge( + &mut v[left.start..right.start + right.len], + left.len, + buf.as_mut_ptr(), + &mut is_less, + ); } - runs[r] = Run { - start: left.start, - len: left.len + right.len, - }; + runs[r] = Run { start: left.start, len: left.len + right.len }; runs.remove(r + 1); } } @@ -1030,15 +1043,13 @@ fn merge_sort(v: &mut [T], mut is_less: F) #[inline] fn collapse(runs: &[Run]) -> Option { let n = runs.len(); - if n >= 2 && (runs[n - 1].start == 0 || - runs[n - 2].len <= runs[n - 1].len || - (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len) || - (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len)) { - if n >= 3 && runs[n - 3].len < runs[n - 1].len { - Some(n - 3) - } else { - Some(n - 2) - } + if n >= 2 + && (runs[n - 1].start == 0 + || runs[n - 2].len <= runs[n - 1].len + || (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len) + || (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len)) + { + if n >= 3 && runs[n - 3].len < runs[n - 1].len { Some(n - 3) } else { Some(n - 2) } } else { None } diff --git a/src/liballoc/tests.rs b/src/liballoc/tests.rs index ed46ba8a1b938..1b6e0bb291c35 100644 --- a/src/liballoc/tests.rs +++ b/src/liballoc/tests.rs @@ -1,12 +1,12 @@ //! Test for `boxed` mod. use core::any::Any; -use core::convert::TryInto; -use core::ops::Deref; -use core::result::Result::{Err, Ok}; use core::clone::Clone; +use core::convert::TryInto; use core::f64; use core::i64; +use core::ops::Deref; +use core::result::Result::{Err, Ok}; use std::boxed::Box; diff --git a/src/liballoc/tests/arc.rs b/src/liballoc/tests/arc.rs index cf2ad2a8e6033..2fbb59b0419e0 100644 --- a/src/liballoc/tests/arc.rs +++ b/src/liballoc/tests/arc.rs @@ -1,9 +1,9 @@ use std::any::Any; -use std::sync::{Arc, Weak}; use std::cell::RefCell; use std::cmp::PartialEq; use std::iter::TrustedLen; use std::mem; +use std::sync::{Arc, Weak}; #[test] fn uninhabited() { @@ -12,7 +12,7 @@ fn uninhabited() { a = a.clone(); assert!(a.upgrade().is_none()); - let mut a: Weak = a; // Unsizing + let mut a: Weak = a; // Unsizing a = a.clone(); assert!(a.upgrade().is_none()); } @@ -20,8 +20,8 @@ fn uninhabited() { #[test] fn slice() { let a: Arc<[u32; 3]> = Arc::new([3, 2, 1]); - let a: Arc<[u32]> = a; // Unsizing - let b: Arc<[u32]> = Arc::from(&[3, 2, 1][..]); // Conversion + let a: Arc<[u32]> = a; // Unsizing + let b: Arc<[u32]> = Arc::from(&[3, 2, 1][..]); // Conversion assert_eq!(a, b); // Exercise is_dangling() with a DST @@ -33,7 +33,7 @@ fn slice() { #[test] fn trait_object() { let a: Arc = Arc::new(4); - let a: Arc = a; // Unsizing + let a: Arc = a; // Unsizing // Exercise is_dangling() with a DST let mut a = Arc::downgrade(&a); @@ -43,7 +43,7 @@ fn trait_object() { let mut b = Weak::::new(); b = b.clone(); assert!(b.upgrade().is_none()); - let mut b: Weak = b; // Unsizing + let mut b: Weak = b; // Unsizing b = b.clone(); assert!(b.upgrade().is_none()); } @@ -57,7 +57,7 @@ fn float_nan_ne() { #[test] fn partial_eq() { - struct TestPEq (RefCell); + struct TestPEq(RefCell); impl PartialEq for TestPEq { fn eq(&self, other: &TestPEq) -> bool { *self.0.borrow_mut() += 1; @@ -74,7 +74,7 @@ fn partial_eq() { #[test] fn eq() { #[derive(Eq)] - struct TestEq (RefCell); + struct TestEq(RefCell); impl PartialEq for TestEq { fn eq(&self, other: &TestEq) -> bool { *self.0.borrow_mut() += 1; @@ -160,13 +160,10 @@ fn shared_from_iter_trustedlen_normal() { fn shared_from_iter_trustedlen_panic() { // Exercise the `TrustedLen` implementation when `size_hint()` matches // `(_, Some(exact_len))` but where `.next()` drops before the last iteration. - let iter = (0..SHARED_ITER_MAX) - .map(|val| { - match val { - 98 => panic!("I've almost got 99 problems."), - _ => Box::new(val), - } - }); + let iter = (0..SHARED_ITER_MAX).map(|val| match val { + 98 => panic!("I've almost got 99 problems."), + _ => Box::new(val), + }); assert_trusted_len(&iter); let _ = iter.collect::>(); @@ -193,16 +190,8 @@ fn shared_from_iter_trustedlen_no_fuse() { } } - let vec = vec![ - Some(Box::new(42)), - Some(Box::new(24)), - None, - Some(Box::new(12)), - ]; + let vec = vec![Some(Box::new(42)), Some(Box::new(24)), None, Some(Box::new(12))]; let iter = Iter(vec.into_iter()); assert_trusted_len(&iter); - assert_eq!( - &[Box::new(42), Box::new(24)], - &*iter.collect::>() - ); + assert_eq!(&[Box::new(42), Box::new(24)], &*iter.collect::>()); } diff --git a/src/liballoc/tests/boxed.rs b/src/liballoc/tests/boxed.rs index bc3d53bf30da3..66782ecbeb7f6 100644 --- a/src/liballoc/tests/boxed.rs +++ b/src/liballoc/tests/boxed.rs @@ -1,5 +1,5 @@ -use std::ptr::NonNull; use std::mem::MaybeUninit; +use std::ptr::NonNull; #[test] fn unitialized_zero_size_box() { diff --git a/src/liballoc/tests/btree/mod.rs b/src/liballoc/tests/btree/mod.rs index 4c704d0f8c28f..1d08ae13e0540 100644 --- a/src/liballoc/tests/btree/mod.rs +++ b/src/liballoc/tests/btree/mod.rs @@ -11,12 +11,7 @@ struct DeterministicRng { impl DeterministicRng { fn new() -> Self { - DeterministicRng { - x: 0x193a6754, - y: 0xa8a7d469, - z: 0x97830e05, - w: 0x113ba7bb, - } + DeterministicRng { x: 0x193a6754, y: 0xa8a7d469, z: 0x97830e05, w: 0x113ba7bb } } fn next(&mut self) -> u32 { diff --git a/src/liballoc/tests/linked_list.rs b/src/liballoc/tests/linked_list.rs index 8a26454c389d7..daa49c48c6a92 100644 --- a/src/liballoc/tests/linked_list.rs +++ b/src/liballoc/tests/linked_list.rs @@ -102,7 +102,6 @@ fn test_split_off() { assert_eq!(m.back(), Some(&1)); assert_eq!(m.front(), Some(&1)); } - } #[test] @@ -305,8 +304,7 @@ fn test_show() { assert_eq!(format!("{:?}", list), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); let list: LinkedList<_> = vec!["just", "one", "test", "more"].iter().cloned().collect(); - assert_eq!(format!("{:?}", list), - "[\"just\", \"one\", \"test\", \"more\"]"); + assert_eq!(format!("{:?}", list), "[\"just\", \"one\", \"test\", \"more\"]"); } #[test] @@ -446,19 +444,14 @@ fn drain_filter_true() { #[test] fn drain_filter_complex() { - - { // [+xxx++++++xxxxx++++x+x++] + { + // [+xxx++++++xxxxx++++x+x++] let mut list = vec![ - 1, - 2, 4, 6, - 7, 9, 11, 13, 15, 17, - 18, 20, 22, 24, 26, - 27, 29, 31, 33, - 34, - 35, - 36, - 37, 39 - ].into_iter().collect::>(); + 1, 2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37, + 39, + ] + .into_iter() + .collect::>(); let removed = list.drain_filter(|x| *x % 2 == 0).collect::>(); assert_eq!(removed.len(), 10); @@ -471,17 +464,13 @@ fn drain_filter_complex() { ); } - { // [xxx++++++xxxxx++++x+x++] + { + // [xxx++++++xxxxx++++x+x++] let mut list = vec![ - 2, 4, 6, - 7, 9, 11, 13, 15, 17, - 18, 20, 22, 24, 26, - 27, 29, 31, 33, - 34, - 35, - 36, - 37, 39 - ].into_iter().collect::>(); + 2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37, 39, + ] + .into_iter() + .collect::>(); let removed = list.drain_filter(|x| *x % 2 == 0).collect::>(); assert_eq!(removed.len(), 10); @@ -494,16 +483,12 @@ fn drain_filter_complex() { ); } - { // [xxx++++++xxxxx++++x+x] - let mut list = vec![ - 2, 4, 6, - 7, 9, 11, 13, 15, 17, - 18, 20, 22, 24, 26, - 27, 29, 31, 33, - 34, - 35, - 36 - ].into_iter().collect::>(); + { + // [xxx++++++xxxxx++++x+x] + let mut list = + vec![2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36] + .into_iter() + .collect::>(); let removed = list.drain_filter(|x| *x % 2 == 0).collect::>(); assert_eq!(removed.len(), 10); @@ -516,11 +501,11 @@ fn drain_filter_complex() { ); } - { // [xxxxxxxxxx+++++++++++] - let mut list = vec![ - 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, - 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 - ].into_iter().collect::>(); + { + // [xxxxxxxxxx+++++++++++] + let mut list = vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + .into_iter() + .collect::>(); let removed = list.drain_filter(|x| *x % 2 == 0).collect::>(); assert_eq!(removed.len(), 10); @@ -530,11 +515,11 @@ fn drain_filter_complex() { assert_eq!(list.into_iter().collect::>(), vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]); } - { // [+++++++++++xxxxxxxxxx] - let mut list = vec![ - 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, - 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 - ].into_iter().collect::>(); + { + // [+++++++++++xxxxxxxxxx] + let mut list = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + .into_iter() + .collect::>(); let removed = list.drain_filter(|x| *x % 2 == 0).collect::>(); assert_eq!(removed.len(), 10); diff --git a/src/liballoc/tests/rc.rs b/src/liballoc/tests/rc.rs index 7854ca0fc16b2..e77c57d9a5a09 100644 --- a/src/liballoc/tests/rc.rs +++ b/src/liballoc/tests/rc.rs @@ -1,9 +1,9 @@ use std::any::Any; -use std::rc::{Rc, Weak}; use std::cell::RefCell; use std::cmp::PartialEq; -use std::mem; use std::iter::TrustedLen; +use std::mem; +use std::rc::{Rc, Weak}; #[test] fn uninhabited() { @@ -12,7 +12,7 @@ fn uninhabited() { a = a.clone(); assert!(a.upgrade().is_none()); - let mut a: Weak = a; // Unsizing + let mut a: Weak = a; // Unsizing a = a.clone(); assert!(a.upgrade().is_none()); } @@ -20,8 +20,8 @@ fn uninhabited() { #[test] fn slice() { let a: Rc<[u32; 3]> = Rc::new([3, 2, 1]); - let a: Rc<[u32]> = a; // Unsizing - let b: Rc<[u32]> = Rc::from(&[3, 2, 1][..]); // Conversion + let a: Rc<[u32]> = a; // Unsizing + let b: Rc<[u32]> = Rc::from(&[3, 2, 1][..]); // Conversion assert_eq!(a, b); // Exercise is_dangling() with a DST @@ -33,7 +33,7 @@ fn slice() { #[test] fn trait_object() { let a: Rc = Rc::new(4); - let a: Rc = a; // Unsizing + let a: Rc = a; // Unsizing // Exercise is_dangling() with a DST let mut a = Rc::downgrade(&a); @@ -43,7 +43,7 @@ fn trait_object() { let mut b = Weak::::new(); b = b.clone(); assert!(b.upgrade().is_none()); - let mut b: Weak = b; // Unsizing + let mut b: Weak = b; // Unsizing b = b.clone(); assert!(b.upgrade().is_none()); } @@ -57,7 +57,7 @@ fn float_nan_ne() { #[test] fn partial_eq() { - struct TestPEq (RefCell); + struct TestPEq(RefCell); impl PartialEq for TestPEq { fn eq(&self, other: &TestPEq) -> bool { *self.0.borrow_mut() += 1; @@ -74,7 +74,7 @@ fn partial_eq() { #[test] fn eq() { #[derive(Eq)] - struct TestEq (RefCell); + struct TestEq(RefCell); impl PartialEq for TestEq { fn eq(&self, other: &TestEq) -> bool { *self.0.borrow_mut() += 1; @@ -156,13 +156,10 @@ fn shared_from_iter_trustedlen_normal() { fn shared_from_iter_trustedlen_panic() { // Exercise the `TrustedLen` implementation when `size_hint()` matches // `(_, Some(exact_len))` but where `.next()` drops before the last iteration. - let iter = (0..SHARED_ITER_MAX) - .map(|val| { - match val { - 98 => panic!("I've almost got 99 problems."), - _ => Box::new(val), - } - }); + let iter = (0..SHARED_ITER_MAX).map(|val| match val { + 98 => panic!("I've almost got 99 problems."), + _ => Box::new(val), + }); assert_trusted_len(&iter); let _ = iter.collect::>(); @@ -189,16 +186,8 @@ fn shared_from_iter_trustedlen_no_fuse() { } } - let vec = vec![ - Some(Box::new(42)), - Some(Box::new(24)), - None, - Some(Box::new(12)), - ]; + let vec = vec![Some(Box::new(42)), Some(Box::new(24)), None, Some(Box::new(12))]; let iter = Iter(vec.into_iter()); assert_trusted_len(&iter); - assert_eq!( - &[Box::new(42), Box::new(24)], - &*iter.collect::>() - ); + assert_eq!(&[Box::new(42), Box::new(24)], &*iter.collect::>()); } diff --git a/src/liballoc/tests/vec_deque.rs b/src/liballoc/tests/vec_deque.rs index d49b553fc0217..5a0162a536175 100644 --- a/src/liballoc/tests/vec_deque.rs +++ b/src/liballoc/tests/vec_deque.rs @@ -1,8 +1,8 @@ -use std::fmt::Debug; -use std::collections::{VecDeque, vec_deque::Drain}; use std::collections::TryReserveError::*; +use std::collections::{vec_deque::Drain, VecDeque}; +use std::fmt::Debug; use std::mem::size_of; -use std::{usize, isize}; +use std::{isize, usize}; use crate::hash; @@ -148,34 +148,20 @@ fn test_param_taggy() { #[test] fn test_param_taggypar() { - test_parameterized::>(Onepar::(1), - Twopar::(1, 2), - Threepar::(1, 2, 3), - Twopar::(17, 42)); + test_parameterized::>( + Onepar::(1), + Twopar::(1, 2), + Threepar::(1, 2, 3), + Twopar::(17, 42), + ); } #[test] fn test_param_reccy() { - let reccy1 = RecCy { - x: 1, - y: 2, - t: One(1), - }; - let reccy2 = RecCy { - x: 345, - y: 2, - t: Two(1, 2), - }; - let reccy3 = RecCy { - x: 1, - y: 777, - t: Three(1, 2, 3), - }; - let reccy4 = RecCy { - x: 19, - y: 252, - t: Two(17, 42), - }; + let reccy1 = RecCy { x: 1, y: 2, t: One(1) }; + let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) }; + let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) }; + let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) }; test_parameterized::(reccy1, reccy2, reccy3, reccy4); } @@ -320,8 +306,7 @@ fn test_mut_rev_iter_wrap() { assert_eq!(d.pop_front(), Some(1)); d.push_back(4); - assert_eq!(d.iter_mut().rev().map(|x| *x).collect::>(), - vec![4, 3, 2]); + assert_eq!(d.iter_mut().rev().map(|x| *x).collect::>(), vec![4, 3, 2]); } #[test] @@ -372,7 +357,6 @@ fn test_mut_rev_iter() { #[test] fn test_into_iter() { - // Empty iter { let d: VecDeque = VecDeque::new(); @@ -431,7 +415,6 @@ fn test_into_iter() { #[test] fn test_drain() { - // Empty iter { let mut d: VecDeque = VecDeque::new(); @@ -650,12 +633,8 @@ fn test_show() { let ringbuf: VecDeque<_> = (0..10).collect(); assert_eq!(format!("{:?}", ringbuf), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); - let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"] - .iter() - .cloned() - .collect(); - assert_eq!(format!("{:?}", ringbuf), - "[\"just\", \"one\", \"test\", \"more\"]"); + let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"].iter().cloned().collect(); + assert_eq!(format!("{:?}", ringbuf), "[\"just\", \"one\", \"test\", \"more\"]"); } #[test] @@ -955,7 +934,6 @@ fn test_append_permutations() { // doesn't pop more values than are pushed for src_pop_back in 0..(src_push_back + src_push_front) { for src_pop_front in 0..(src_push_back + src_push_front - src_pop_back) { - let src = construct_vec_deque( src_push_back, src_pop_back, @@ -966,8 +944,8 @@ fn test_append_permutations() { for dst_push_back in 0..MAX { for dst_push_front in 0..MAX { for dst_pop_back in 0..(dst_push_back + dst_push_front) { - for dst_pop_front - in 0..(dst_push_back + dst_push_front - dst_pop_back) + for dst_pop_front in + 0..(dst_push_back + dst_push_front - dst_pop_back) { let mut dst = construct_vec_deque( dst_push_back, @@ -1124,7 +1102,6 @@ fn test_reserve_exact_2() { #[test] #[cfg(not(miri))] // Miri does not support signalling OOM fn test_try_reserve() { - // These are the interesting cases: // * exactly isize::MAX should never trigger a CapacityOverflow (can be OOM) // * > isize::MAX should always fail @@ -1158,22 +1135,27 @@ fn test_try_reserve() { if guards_against_isize { // Check isize::MAX + 1 does count as overflow if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_CAP + 1) { - } else { panic!("isize::MAX + 1 should trigger an overflow!") } + } else { + panic!("isize::MAX + 1 should trigger an overflow!") + } // Check usize::MAX does count as overflow if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) { - } else { panic!("usize::MAX should trigger an overflow!") } + } else { + panic!("usize::MAX should trigger an overflow!") + } } else { // Check isize::MAX is an OOM // VecDeque starts with capacity 7, always adds 1 to the capacity // and also rounds the number to next power of 2 so this is the // furthest we can go without triggering CapacityOverflow if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_CAP) { - } else { panic!("isize::MAX + 1 should trigger an OOM!") } + } else { + panic!("isize::MAX + 1 should trigger an OOM!") + } } } - { // Same basic idea, but with non-zero len let mut ten_bytes: VecDeque = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); @@ -1186,33 +1168,42 @@ fn test_try_reserve() { } if guards_against_isize { if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 9) { - } else { panic!("isize::MAX + 1 should trigger an overflow!"); } + } else { + panic!("isize::MAX + 1 should trigger an overflow!"); + } } else { if let Err(AllocError { .. }) = ten_bytes.try_reserve(MAX_CAP - 9) { - } else { panic!("isize::MAX + 1 should trigger an OOM!") } + } else { + panic!("isize::MAX + 1 should trigger an OOM!") + } } // Should always overflow in the add-to-len if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_USIZE) { - } else { panic!("usize::MAX should trigger an overflow!") } + } else { + panic!("usize::MAX should trigger an overflow!") + } } - { // Same basic idea, but with interesting type size let mut ten_u32s: VecDeque = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); - if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 10) { + if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 10) { panic!("isize::MAX shouldn't trigger an overflow!"); } - if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 10) { + if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 10) { panic!("isize::MAX shouldn't trigger an overflow!"); } if guards_against_isize { - if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 9) { - } else { panic!("isize::MAX + 1 should trigger an overflow!"); } + if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 9) { + } else { + panic!("isize::MAX + 1 should trigger an overflow!"); + } } else { - if let Err(AllocError { .. }) = ten_u32s.try_reserve(MAX_CAP/4 - 9) { - } else { panic!("isize::MAX + 1 should trigger an OOM!") } + if let Err(AllocError { .. }) = ten_u32s.try_reserve(MAX_CAP / 4 - 9) { + } else { + panic!("isize::MAX + 1 should trigger an OOM!") + } } // Should fail in the mul-by-size if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_USIZE - 20) { @@ -1220,13 +1211,11 @@ fn test_try_reserve() { panic!("usize::MAX should trigger an overflow!"); } } - } #[test] #[cfg(not(miri))] // Miri does not support signalling OOM fn test_try_reserve_exact() { - // This is exactly the same as test_try_reserve with the method changed. // See that test for comments. @@ -1247,21 +1236,26 @@ fn test_try_reserve_exact() { if guards_against_isize { if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_CAP + 1) { - } else { panic!("isize::MAX + 1 should trigger an overflow!") } + } else { + panic!("isize::MAX + 1 should trigger an overflow!") + } if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_USIZE) { - } else { panic!("usize::MAX should trigger an overflow!") } + } else { + panic!("usize::MAX should trigger an overflow!") + } } else { // Check isize::MAX is an OOM // VecDeque starts with capacity 7, always adds 1 to the capacity // and also rounds the number to next power of 2 so this is the // furthest we can go without triggering CapacityOverflow if let Err(AllocError { .. }) = empty_bytes.try_reserve_exact(MAX_CAP) { - } else { panic!("isize::MAX + 1 should trigger an OOM!") } + } else { + panic!("isize::MAX + 1 should trigger an OOM!") + } } } - { let mut ten_bytes: VecDeque = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); @@ -1273,36 +1267,46 @@ fn test_try_reserve_exact() { } if guards_against_isize { if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 9) { - } else { panic!("isize::MAX + 1 should trigger an overflow!"); } + } else { + panic!("isize::MAX + 1 should trigger an overflow!"); + } } else { if let Err(AllocError { .. }) = ten_bytes.try_reserve_exact(MAX_CAP - 9) { - } else { panic!("isize::MAX + 1 should trigger an OOM!") } + } else { + panic!("isize::MAX + 1 should trigger an OOM!") + } } if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_USIZE) { - } else { panic!("usize::MAX should trigger an overflow!") } + } else { + panic!("usize::MAX should trigger an overflow!") + } } - { let mut ten_u32s: VecDeque = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); - if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 10) { + if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 10) { panic!("isize::MAX shouldn't trigger an overflow!"); } - if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 10) { + if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 10) { panic!("isize::MAX shouldn't trigger an overflow!"); } if guards_against_isize { - if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) { - } else { panic!("isize::MAX + 1 should trigger an overflow!"); } + if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 9) { + } else { + panic!("isize::MAX + 1 should trigger an overflow!"); + } } else { - if let Err(AllocError { .. }) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) { - } else { panic!("isize::MAX + 1 should trigger an OOM!") } + if let Err(AllocError { .. }) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 9) { + } else { + panic!("isize::MAX + 1 should trigger an OOM!") + } } if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_USIZE - 20) { - } else { panic!("usize::MAX should trigger an overflow!") } + } else { + panic!("usize::MAX should trigger an overflow!") + } } - } #[test] @@ -1404,9 +1408,8 @@ fn test_rotate_right_parts() { #[test] fn test_rotate_left_random() { let shifts = [ - 6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1, - 4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11, - 9, 4, 12, 3, 12, 9, 11, 1, 7, 9, 7, 2, + 6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1, 4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11, 9, 4, 12, 3, + 12, 9, 11, 1, 7, 9, 7, 2, ]; let n = 12; let mut v: VecDeque<_> = (0..n).collect(); @@ -1423,9 +1426,8 @@ fn test_rotate_left_random() { #[test] fn test_rotate_right_random() { let shifts = [ - 6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1, - 4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11, - 9, 4, 12, 3, 12, 9, 11, 1, 7, 9, 7, 2, + 6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1, 4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11, 9, 4, 12, 3, + 12, 9, 11, 1, 7, 9, 7, 2, ]; let n = 12; let mut v: VecDeque<_> = (0..n).collect(); @@ -1447,8 +1449,7 @@ fn test_try_fold_empty() { #[test] fn test_try_fold_none() { let v: VecDeque = (0..12).collect(); - assert_eq!(None, v.into_iter().try_fold(0, |a, b| - if b < 11 { Some(a + b) } else { None })); + assert_eq!(None, v.into_iter().try_fold(0, |a, b| if b < 11 { Some(a + b) } else { None })); } #[test] @@ -1463,7 +1464,6 @@ fn test_try_fold_unit() { assert_eq!(Some(()), v.into_iter().try_fold((), |(), ()| Some(()))); } - #[test] fn test_try_fold_unit_none() { let v: std::collections::VecDeque<()> = [(); 10].iter().cloned().collect(); @@ -1534,7 +1534,7 @@ fn test_try_rfold_rotated() { #[test] fn test_try_rfold_moves_iter() { - let v : VecDeque<_> = [10, 20, 30, 40, 100, 60, 70, 80, 90].iter().collect(); + let v: VecDeque<_> = [10, 20, 30, 40, 100, 60, 70, 80, 90].iter().collect(); let mut iter = v.into_iter(); assert_eq!(iter.try_rfold(0_i8, |acc, &x| acc.checked_add(x)), None); assert_eq!(iter.next_back(), Some(&70)); From 7f20198632bc2079d4deb4c213ec4876c47ec5d2 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 30 Nov 2019 10:16:19 +0100 Subject: [PATCH 18/20] pass Queries to compiler callbacks --- src/librustc_driver/lib.rs | 26 +++++++++++++++++++------- src/librustc_interface/lib.rs | 1 + 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index c945de8f1e1dc..37fc8d0a55498 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -41,7 +41,7 @@ use rustc::util::common::{set_time_depth, time, print_time_passes_entry, ErrorRe use rustc_metadata::locator; use rustc_codegen_utils::codegen_backend::CodegenBackend; use errors::{PResult, registry::Registry}; -use rustc_interface::interface; +use rustc_interface::{interface, Queries}; use rustc_interface::util::get_codegen_sysroot; use rustc_data_structures::sync::SeqCst; @@ -99,17 +99,29 @@ pub trait Callbacks { fn config(&mut self, _config: &mut interface::Config) {} /// Called after parsing. Return value instructs the compiler whether to /// continue the compilation afterwards (defaults to `Compilation::Continue`) - fn after_parsing(&mut self, _compiler: &interface::Compiler) -> Compilation { + fn after_parsing<'tcx>( + &mut self, + _compiler: &interface::Compiler, + _queries: &'tcx Queries<'tcx>, + ) -> Compilation { Compilation::Continue } /// Called after expansion. Return value instructs the compiler whether to /// continue the compilation afterwards (defaults to `Compilation::Continue`) - fn after_expansion(&mut self, _compiler: &interface::Compiler) -> Compilation { + fn after_expansion<'tcx>( + &mut self, + _compiler: &interface::Compiler, + _queries: &'tcx Queries<'tcx>, + ) -> Compilation { Compilation::Continue } /// Called after analysis. Return value instructs the compiler whether to /// continue the compilation afterwards (defaults to `Compilation::Continue`) - fn after_analysis(&mut self, _compiler: &interface::Compiler) -> Compilation { + fn after_analysis<'tcx>( + &mut self, + _compiler: &interface::Compiler, + _queries: &'tcx Queries<'tcx>, + ) -> Compilation { Compilation::Continue } } @@ -313,7 +325,7 @@ pub fn run_compiler( return early_exit(); } - if callbacks.after_parsing(compiler) == Compilation::Stop { + if callbacks.after_parsing(compiler, queries) == Compilation::Stop { return early_exit(); } @@ -334,7 +346,7 @@ pub fn run_compiler( } queries.expansion()?; - if callbacks.after_expansion(compiler) == Compilation::Stop { + if callbacks.after_expansion(compiler, queries) == Compilation::Stop { return early_exit(); } @@ -383,7 +395,7 @@ pub fn run_compiler( queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?; - if callbacks.after_analysis(compiler) == Compilation::Stop { + if callbacks.after_analysis(compiler, queries) == Compilation::Stop { return early_exit(); } diff --git a/src/librustc_interface/lib.rs b/src/librustc_interface/lib.rs index 53baf6556fb5b..76af4342f5c9e 100644 --- a/src/librustc_interface/lib.rs +++ b/src/librustc_interface/lib.rs @@ -18,6 +18,7 @@ pub mod util; mod proc_macro_decls; pub use interface::{run_compiler, Config}; +pub use queries::Queries; #[cfg(test)] mod tests; From a52eb05ec6407054a0549b336fa746b62e1d22c0 Mon Sep 17 00:00:00 2001 From: Nixon Date: Sat, 30 Nov 2019 10:56:07 +0000 Subject: [PATCH 19/20] Address review comments --- src/librustc_error_codes/error_codes/E0203.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/librustc_error_codes/error_codes/E0203.md b/src/librustc_error_codes/error_codes/E0203.md index 792ed3cb8bb8f..1edb519275f79 100644 --- a/src/librustc_error_codes/error_codes/E0203.md +++ b/src/librustc_error_codes/error_codes/E0203.md @@ -1,12 +1,18 @@ -Having multiple relaxed default bounds is unsuported. +Having multiple relaxed default bounds is unsupported. Erroneous code example: ```compile_fail,E0203 +struct Bad{ + inner: T +} +``` -trait Foo {} +Here the type `T` cannot have a relaxed bound for multiple default traits +(`Sized` and `Send`). This can be fixed by only using one relaxed bound. -struct S5(*const T) where T: ?Foo + ?Sized; ``` - -Here the type `T` cannot have a relaxed bound for both `Foo` and `Sized` +struct Good{ + inner: T +} +``` From 2ced9d96e7b70237daa69bd8d421f0421d57e676 Mon Sep 17 00:00:00 2001 From: Christian Poveda Date: Sat, 30 Nov 2019 12:25:45 -0500 Subject: [PATCH 20/20] Merge match branches --- src/librustc_mir/transform/check_consts/validation.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs index 7b26ba58e6154..829d9ee6fafd7 100644 --- a/src/librustc_mir/transform/check_consts/validation.rs +++ b/src/librustc_mir/transform/check_consts/validation.rs @@ -560,15 +560,12 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> { trace!("visit_statement: statement={:?} location={:?}", statement, location); match statement.kind { - StatementKind::Assign(..) => { + StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => { self.super_statement(statement, location); } StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => { self.check_op(ops::IfOrMatch); } - StatementKind::SetDiscriminant { .. } => { - self.super_statement(statement, location) - } // FIXME(eddyb) should these really do nothing? StatementKind::FakeRead(..) | StatementKind::StorageLive(_) |