From 97bc99a18f8175bf251a902fe5956e4d42fecebb Mon Sep 17 00:00:00 2001 From: okaneco <47607823+okaneco@users.noreply.github.com> Date: Wed, 12 Feb 2025 02:14:33 -0500 Subject: [PATCH 01/20] Implement feature `isolate_most_least_significant_one` for integer types Implement accepted ACP for functions that isolate the most significant set bit and least significant set bit on unsigned, signed, and NonZero integers. Add function `isolate_most_significant_one` Add function `isolate_least_significant_one` Add tests --- library/core/src/num/int_macros.rs | 46 ++++++++++ library/core/src/num/nonzero.rs | 64 +++++++++++++ library/core/src/num/uint_macros.rs | 46 ++++++++++ library/coretests/tests/lib.rs | 1 + library/coretests/tests/nonzero.rs | 100 +++++++++++++++++++++ library/coretests/tests/num/int_macros.rs | 34 +++++++ library/coretests/tests/num/uint_macros.rs | 34 +++++++ 7 files changed, 325 insertions(+) diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 96a290ad5a09d..a26832d8231e6 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -183,6 +183,52 @@ macro_rules! int_impl { (self as $UnsignedT).trailing_ones() } + /// Returns `self` with only the most significant bit set, or `0` if + /// the input is `0`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(isolate_most_least_significant_one)] + /// + #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")] + /// + /// assert_eq!(n.isolate_most_significant_one(), 0b_01000000); + #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_most_significant_one(), 0);")] + /// ``` + #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn isolate_most_significant_one(self) -> Self { + self & (((1 as $SelfT) << (<$SelfT>::BITS - 1)).wrapping_shr(self.leading_zeros())) + } + + /// Returns `self` with only the least significant bit set, or `0` if + /// the input is `0`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(isolate_most_least_significant_one)] + /// + #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")] + /// + /// assert_eq!(n.isolate_least_significant_one(), 0b_00000100); + #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_least_significant_one(), 0);")] + /// ``` + #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn isolate_least_significant_one(self) -> Self { + self & self.wrapping_neg() + } + /// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size. /// /// This produces the same result as an `as` cast, but ensures that the bit-width remains diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index a115acf42b126..b14928514f51c 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -605,6 +605,70 @@ macro_rules! nonzero_integer { } } + /// Returns `self` with only the most significant bit set. + /// + /// # Example + /// + /// Basic usage: + /// + /// ``` + /// #![feature(isolate_most_least_significant_one)] + /// + /// # use core::num::NonZero; + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b_01100100)?;")] + #[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b_01000000)?;")] + /// + /// assert_eq!(a.isolate_most_significant_one(), b); + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn isolate_most_significant_one(self) -> Self { + let n = self.get() & (((1 as $Int) << (<$Int>::BITS - 1)).wrapping_shr(self.leading_zeros())); + + // SAFETY: + // `self` is non-zero, so masking to preserve only the most + // significant set bit will result in a non-zero `n`. + unsafe { NonZero::new_unchecked(n) } + } + + /// Returns `self` with only the least significant bit set. + /// + /// # Example + /// + /// Basic usage: + /// + /// ``` + /// #![feature(isolate_most_least_significant_one)] + /// + /// # use core::num::NonZero; + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b_01100100)?;")] + #[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b_00000100)?;")] + /// + /// assert_eq!(a.isolate_least_significant_one(), b); + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn isolate_least_significant_one(self) -> Self { + let n = self.get(); + let n = n & n.wrapping_neg(); + + // SAFETY: `self` is non-zero, so `self` with only its least + // significant set bit will remain non-zero. + unsafe { NonZero::new_unchecked(n) } + } + /// Returns the number of ones in the binary representation of `self`. /// /// # Examples diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 29f6791ee6ad2..85d80c341f507 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -213,6 +213,52 @@ macro_rules! uint_impl { (!self).trailing_zeros() } + /// Returns `self` with only the most significant bit set, or `0` if + /// the input is `0`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(isolate_most_least_significant_one)] + /// + #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")] + /// + /// assert_eq!(n.isolate_most_significant_one(), 0b_01000000); + #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_most_significant_one(), 0);")] + /// ``` + #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn isolate_most_significant_one(self) -> Self { + self & (((1 as $SelfT) << (<$SelfT>::BITS - 1)).wrapping_shr(self.leading_zeros())) + } + + /// Returns `self` with only the least significant bit set, or `0` if + /// the input is `0`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(isolate_most_least_significant_one)] + /// + #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")] + /// + /// assert_eq!(n.isolate_least_significant_one(), 0b_00000100); + #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_least_significant_one(), 0);")] + /// ``` + #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn isolate_least_significant_one(self) -> Self { + self & self.wrapping_neg() + } + /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size. /// /// This produces the same result as an `as` cast, but ensures that the bit-width remains diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index f1bbed3de3017..a3fd33f9b1a82 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -43,6 +43,7 @@ #![feature(ip)] #![feature(ip_from)] #![feature(is_ascii_octdigit)] +#![feature(isolate_most_least_significant_one)] #![feature(iter_advance_by)] #![feature(iter_array_chunks)] #![feature(iter_chain)] diff --git a/library/coretests/tests/nonzero.rs b/library/coretests/tests/nonzero.rs index 43c279053d829..bdc5701d9fd23 100644 --- a/library/coretests/tests/nonzero.rs +++ b/library/coretests/tests/nonzero.rs @@ -321,6 +321,106 @@ fn nonzero_trailing_zeros() { assert_eq!(TRAILING_ZEROS, 2); } +#[test] +fn test_nonzero_isolate_most_significant_one() { + // Signed most significant one + macro_rules! nonzero_int_impl { + ($($T:ty),+) => { + $( + { + const BITS: $T = -1; + const MOST_SIG_ONE: $T = 1 << (<$T>::BITS - 1); + + // Right shift the most significant one through each + // bit position, starting with all bits set + let mut i = 0; + while i < <$T>::BITS { + assert_eq!( + NonZero::<$T>::new(BITS >> i).unwrap().isolate_most_significant_one(), + NonZero::<$T>::new(MOST_SIG_ONE >> i).unwrap().isolate_most_significant_one() + ); + i += 1; + } + } + )+ + }; + } + + // Unsigned most significant one + macro_rules! nonzero_uint_impl { + ($($T:ty),+) => { + $( + { + const BITS: $T = <$T>::MAX; + const MOST_SIG_ONE: $T = 1 << (<$T>::BITS - 1); + + let mut i = 0; + while i < <$T>::BITS { + assert_eq!( + NonZero::<$T>::new(BITS >> i).unwrap().isolate_most_significant_one(), + NonZero::<$T>::new(MOST_SIG_ONE >> i).unwrap().isolate_most_significant_one(), + ); + i += 1; + } + } + )+ + }; + } + + nonzero_int_impl!(i8, i16, i32, i64, i128, isize); + nonzero_uint_impl!(u8, u16, u32, u64, u128, usize); +} + +#[test] +fn test_nonzero_isolate_least_significant_one() { + // Signed least significant one + macro_rules! nonzero_int_impl { + ($($T:ty),+) => { + $( + { + const BITS: $T = -1; + const LEAST_SIG_ONE: $T = 1; + + // Left shift the least significant one through each + // bit position, starting with all bits set + let mut i = 0; + while i < <$T>::BITS { + assert_eq!( + NonZero::<$T>::new(BITS << i).unwrap().isolate_least_significant_one(), + NonZero::<$T>::new(LEAST_SIG_ONE << i).unwrap().isolate_least_significant_one() + ); + i += 1; + } + } + )+ + }; + } + + // Unsigned least significant one + macro_rules! nonzero_uint_impl { + ($($T:ty),+) => { + $( + { + const BITS: $T = <$T>::MAX; + const LEAST_SIG_ONE: $T = 1; + + let mut i = 0; + while i < <$T>::BITS { + assert_eq!( + NonZero::<$T>::new(BITS << i).unwrap().isolate_least_significant_one(), + NonZero::<$T>::new(LEAST_SIG_ONE << i).unwrap().isolate_least_significant_one(), + ); + i += 1; + } + } + )+ + }; + } + + nonzero_int_impl!(i8, i16, i32, i64, i128, isize); + nonzero_uint_impl!(u8, u16, u32, u64, u128, usize); +} + #[test] fn test_nonzero_uint_div() { let nz = NonZero::new(1).unwrap(); diff --git a/library/coretests/tests/num/int_macros.rs b/library/coretests/tests/num/int_macros.rs index f13b836378b9e..392704e7509ac 100644 --- a/library/coretests/tests/num/int_macros.rs +++ b/library/coretests/tests/num/int_macros.rs @@ -192,6 +192,40 @@ macro_rules! int_module { } } + #[test] + fn test_isolate_most_significant_one() { + const BITS: $T = -1; + const MOST_SIG_ONE: $T = 1 << (<$T>::BITS - 1); + + // Right shift the most significant one through each + // bit position, starting with all bits set + let mut i = 0; + while i < <$T>::BITS { + assert_eq!( + (BITS >> i).isolate_most_significant_one(), + (MOST_SIG_ONE >> i).isolate_most_significant_one() + ); + i += 1; + } + } + + #[test] + fn test_isolate_least_significant_one() { + const BITS: $T = -1; + const LEAST_SIG_ONE: $T = 1; + + // Left shift the least significant one through each + // bit position, starting with all bits set + let mut i = 0; + while i < <$T>::BITS { + assert_eq!( + (BITS << i).isolate_least_significant_one(), + (LEAST_SIG_ONE << i).isolate_least_significant_one() + ); + i += 1; + } + } + #[test] fn test_from_str() { fn from_str(t: &str) -> Option { diff --git a/library/coretests/tests/num/uint_macros.rs b/library/coretests/tests/num/uint_macros.rs index 99a2d4cd462b1..c085ba5a249af 100644 --- a/library/coretests/tests/num/uint_macros.rs +++ b/library/coretests/tests/num/uint_macros.rs @@ -141,6 +141,40 @@ macro_rules! uint_module { } } + #[test] + fn test_isolate_most_significant_one() { + const BITS: $T = <$T>::MAX; + const MOST_SIG_ONE: $T = 1 << (<$T>::BITS - 1); + + // Right shift the most significant one through each + // bit position, starting with all bits set + let mut i = 0; + while i < <$T>::BITS { + assert_eq!( + (BITS >> i).isolate_most_significant_one(), + (MOST_SIG_ONE >> i).isolate_most_significant_one(), + ); + i += 1; + } + } + + #[test] + fn test_isolate_least_significant_one() { + const BITS: $T = <$T>::MAX; + const LEAST_SIG_ONE: $T = 1; + + // Left shift the least significant one through each + // bit position, starting with all bits set + let mut i = 0; + while i < <$T>::BITS { + assert_eq!( + (BITS << i).isolate_least_significant_one(), + (LEAST_SIG_ONE << i).isolate_least_significant_one(), + ); + i += 1; + } + } + fn from_str(t: &str) -> Option { core::str::FromStr::from_str(t).ok() } From 7312747f67996b75c35bfb776c124d94d5720a8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 21 Feb 2025 08:28:42 +0100 Subject: [PATCH 02/20] Add build step log for `run-make-support` I was always confused about what is being built, since nothing was printed in the log :) --- src/bootstrap/src/core/build_steps/test.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index b3f4a7bad99c2..16f5d2c5e3f3f 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1234,6 +1234,14 @@ impl Step for RunMakeSupport { &[], ); + let _guard = builder.msg_tool( + Kind::Build, + Mode::ToolStd, + "run-make-support", + self.compiler.stage, + &self.compiler.host, + &self.target, + ); cargo.into_cmd().run(builder); let lib_name = "librun_make_support.rlib"; From d21c0cf5160328bab7b22b9965dd0f93552237cc Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 6 Feb 2025 11:38:59 +0000 Subject: [PATCH 03/20] Move all alloc integration tests to a new alloctests crate --- library/Cargo.lock | 8 ++++ library/Cargo.toml | 1 + library/alloc/Cargo.toml | 18 -------- .../alloc/src/{raw_vec.rs => raw_vec/mod.rs} | 0 library/alloc/src/{rc.rs => rc/mod.rs} | 0 library/alloctests/Cargo.toml | 46 +++++++++++++++++++ .../benches/binary_heap.rs | 0 .../benches/btree/map.rs | 0 .../benches/btree/mod.rs | 0 .../benches/btree/set.rs | 0 library/{alloc => alloctests}/benches/lib.rs | 0 .../benches/linked_list.rs | 0 .../{alloc => alloctests}/benches/slice.rs | 0 library/{alloc => alloctests}/benches/str.rs | 0 .../{alloc => alloctests}/benches/string.rs | 0 library/{alloc => alloctests}/benches/vec.rs | 0 .../benches/vec_deque.rs | 0 .../benches/vec_deque_append.rs | 0 library/alloctests/lib.rs | 1 + .../tests/alloc_test.rs} | 0 library/{alloc => alloctests}/tests/arc.rs | 0 .../{alloc => alloctests}/tests/autotraits.rs | 0 library/{alloc => alloctests}/tests/borrow.rs | 0 library/{alloc => alloctests}/tests/boxed.rs | 0 .../tests/btree_set_hash.rs | 0 library/{alloc => alloctests}/tests/c_str.rs | 0 library/{alloc => alloctests}/tests/c_str2.rs | 0 .../tests/collections/binary_heap.rs | 0 .../tests/collections/mod.rs | 0 .../{alloc => alloctests}/tests/const_fns.rs | 0 .../{alloc => alloctests}/tests/cow_str.rs | 0 library/{alloc => alloctests}/tests/fmt.rs | 0 library/{alloc => alloctests}/tests/heap.rs | 0 library/{alloc => alloctests}/tests/lib.rs | 3 +- .../tests/linked_list.rs | 0 .../{alloc => alloctests}/tests/misc_tests.rs | 0 library/{alloc => alloctests}/tests/rc.rs | 0 library/{alloc => alloctests}/tests/slice.rs | 0 .../tests/sort/ffi_types.rs | 0 .../tests/sort/known_good_stable_sort.rs | 0 .../{alloc => alloctests}/tests/sort/mod.rs | 0 .../tests/sort/patterns.rs | 0 .../{alloc => alloctests}/tests/sort/tests.rs | 0 .../{alloc => alloctests}/tests/sort/zipf.rs | 0 library/{alloc => alloctests}/tests/str.rs | 0 library/{alloc => alloctests}/tests/string.rs | 0 library/{alloc => alloctests}/tests/sync.rs | 0 library/{alloc => alloctests}/tests/task.rs | 0 .../tests/testing/crash_test.rs | 0 .../tests/testing/mod.rs | 0 .../{alloc => alloctests}/tests/thin_box.rs | 0 library/{alloc => alloctests}/tests/vec.rs | 0 .../{alloc => alloctests}/tests/vec_deque.rs | 0 .../tests/vec_deque_alloc_error.rs | 0 src/bootstrap/mk/Makefile.in | 2 + src/bootstrap/src/core/build_steps/check.rs | 5 +- src/bootstrap/src/core/build_steps/test.rs | 2 +- src/tools/tidy/src/style.rs | 2 +- 58 files changed, 66 insertions(+), 22 deletions(-) rename library/alloc/src/{raw_vec.rs => raw_vec/mod.rs} (100%) rename library/alloc/src/{rc.rs => rc/mod.rs} (100%) create mode 100644 library/alloctests/Cargo.toml rename library/{alloc => alloctests}/benches/binary_heap.rs (100%) rename library/{alloc => alloctests}/benches/btree/map.rs (100%) rename library/{alloc => alloctests}/benches/btree/mod.rs (100%) rename library/{alloc => alloctests}/benches/btree/set.rs (100%) rename library/{alloc => alloctests}/benches/lib.rs (100%) rename library/{alloc => alloctests}/benches/linked_list.rs (100%) rename library/{alloc => alloctests}/benches/slice.rs (100%) rename library/{alloc => alloctests}/benches/str.rs (100%) rename library/{alloc => alloctests}/benches/string.rs (100%) rename library/{alloc => alloctests}/benches/vec.rs (100%) rename library/{alloc => alloctests}/benches/vec_deque.rs (100%) rename library/{alloc => alloctests}/benches/vec_deque_append.rs (100%) create mode 100644 library/alloctests/lib.rs rename library/{alloc/tests/alloc.rs => alloctests/tests/alloc_test.rs} (100%) rename library/{alloc => alloctests}/tests/arc.rs (100%) rename library/{alloc => alloctests}/tests/autotraits.rs (100%) rename library/{alloc => alloctests}/tests/borrow.rs (100%) rename library/{alloc => alloctests}/tests/boxed.rs (100%) rename library/{alloc => alloctests}/tests/btree_set_hash.rs (100%) rename library/{alloc => alloctests}/tests/c_str.rs (100%) rename library/{alloc => alloctests}/tests/c_str2.rs (100%) rename library/{alloc => alloctests}/tests/collections/binary_heap.rs (100%) rename library/{alloc => alloctests}/tests/collections/mod.rs (100%) rename library/{alloc => alloctests}/tests/const_fns.rs (100%) rename library/{alloc => alloctests}/tests/cow_str.rs (100%) rename library/{alloc => alloctests}/tests/fmt.rs (100%) rename library/{alloc => alloctests}/tests/heap.rs (100%) rename library/{alloc => alloctests}/tests/lib.rs (98%) rename library/{alloc => alloctests}/tests/linked_list.rs (100%) rename library/{alloc => alloctests}/tests/misc_tests.rs (100%) rename library/{alloc => alloctests}/tests/rc.rs (100%) rename library/{alloc => alloctests}/tests/slice.rs (100%) rename library/{alloc => alloctests}/tests/sort/ffi_types.rs (100%) rename library/{alloc => alloctests}/tests/sort/known_good_stable_sort.rs (100%) rename library/{alloc => alloctests}/tests/sort/mod.rs (100%) rename library/{alloc => alloctests}/tests/sort/patterns.rs (100%) rename library/{alloc => alloctests}/tests/sort/tests.rs (100%) rename library/{alloc => alloctests}/tests/sort/zipf.rs (100%) rename library/{alloc => alloctests}/tests/str.rs (100%) rename library/{alloc => alloctests}/tests/string.rs (100%) rename library/{alloc => alloctests}/tests/sync.rs (100%) rename library/{alloc => alloctests}/tests/task.rs (100%) rename library/{alloc => alloctests}/tests/testing/crash_test.rs (100%) rename library/{alloc => alloctests}/tests/testing/mod.rs (100%) rename library/{alloc => alloctests}/tests/thin_box.rs (100%) rename library/{alloc => alloctests}/tests/vec.rs (100%) rename library/{alloc => alloctests}/tests/vec_deque.rs (100%) rename library/{alloc => alloctests}/tests/vec_deque_alloc_error.rs (100%) diff --git a/library/Cargo.lock b/library/Cargo.lock index 0be2f9a154939..3d40caa18c971 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -40,6 +40,14 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "alloctests" +version = "0.0.0" +dependencies = [ + "rand", + "rand_xorshift", +] + [[package]] name = "cc" version = "1.2.0" diff --git a/library/Cargo.toml b/library/Cargo.toml index 1205f7c9ed6b5..4d5955593ffcd 100644 --- a/library/Cargo.toml +++ b/library/Cargo.toml @@ -4,6 +4,7 @@ members = [ "std", "sysroot", "coretests", + "alloctests", ] exclude = [ diff --git a/library/alloc/Cargo.toml b/library/alloc/Cargo.toml index c1d7f324f1770..30801664e6587 100644 --- a/library/alloc/Cargo.toml +++ b/library/alloc/Cargo.toml @@ -16,24 +16,6 @@ compiler_builtins = { version = "=0.1.146", features = ['rustc-dep-of-std'] } rand = { version = "0.9.0", default-features = false, features = ["alloc"] } rand_xorshift = "0.4.0" -[[test]] -name = "alloctests" -path = "tests/lib.rs" - -[[test]] -name = "vec_deque_alloc_error" -path = "tests/vec_deque_alloc_error.rs" - -[[bench]] -name = "allocbenches" -path = "benches/lib.rs" -test = true - -[[bench]] -name = "vec_deque_append_bench" -path = "benches/vec_deque_append.rs" -harness = false - [features] compiler-builtins-mem = ['compiler_builtins/mem'] compiler-builtins-c = ["compiler_builtins/c"] diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec/mod.rs similarity index 100% rename from library/alloc/src/raw_vec.rs rename to library/alloc/src/raw_vec/mod.rs diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc/mod.rs similarity index 100% rename from library/alloc/src/rc.rs rename to library/alloc/src/rc/mod.rs diff --git a/library/alloctests/Cargo.toml b/library/alloctests/Cargo.toml new file mode 100644 index 0000000000000..93c7c786e881b --- /dev/null +++ b/library/alloctests/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "alloctests" +version = "0.0.0" +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-lang/rust.git" +description = "Tests for the Rust Allocation Library" +autotests = false +autobenches = false +edition = "2021" + +[lib] +path = "lib.rs" +test = false +bench = false + +[dev-dependencies] +rand = { version = "0.8.5", default-features = false, features = ["alloc"] } +rand_xorshift = "0.3.0" + +[[test]] +name = "alloctests" +path = "tests/lib.rs" + +[[test]] +name = "vec_deque_alloc_error" +path = "tests/vec_deque_alloc_error.rs" + +[[bench]] +name = "allocbenches" +path = "benches/lib.rs" +test = true + +[[bench]] +name = "vec_deque_append_bench" +path = "benches/vec_deque_append.rs" +harness = false + +[lints.rust.unexpected_cfgs] +level = "warn" +check-cfg = [ + 'cfg(bootstrap)', + 'cfg(no_global_oom_handling)', + 'cfg(no_rc)', + 'cfg(no_sync)', + 'cfg(randomized_layouts)', +] diff --git a/library/alloc/benches/binary_heap.rs b/library/alloctests/benches/binary_heap.rs similarity index 100% rename from library/alloc/benches/binary_heap.rs rename to library/alloctests/benches/binary_heap.rs diff --git a/library/alloc/benches/btree/map.rs b/library/alloctests/benches/btree/map.rs similarity index 100% rename from library/alloc/benches/btree/map.rs rename to library/alloctests/benches/btree/map.rs diff --git a/library/alloc/benches/btree/mod.rs b/library/alloctests/benches/btree/mod.rs similarity index 100% rename from library/alloc/benches/btree/mod.rs rename to library/alloctests/benches/btree/mod.rs diff --git a/library/alloc/benches/btree/set.rs b/library/alloctests/benches/btree/set.rs similarity index 100% rename from library/alloc/benches/btree/set.rs rename to library/alloctests/benches/btree/set.rs diff --git a/library/alloc/benches/lib.rs b/library/alloctests/benches/lib.rs similarity index 100% rename from library/alloc/benches/lib.rs rename to library/alloctests/benches/lib.rs diff --git a/library/alloc/benches/linked_list.rs b/library/alloctests/benches/linked_list.rs similarity index 100% rename from library/alloc/benches/linked_list.rs rename to library/alloctests/benches/linked_list.rs diff --git a/library/alloc/benches/slice.rs b/library/alloctests/benches/slice.rs similarity index 100% rename from library/alloc/benches/slice.rs rename to library/alloctests/benches/slice.rs diff --git a/library/alloc/benches/str.rs b/library/alloctests/benches/str.rs similarity index 100% rename from library/alloc/benches/str.rs rename to library/alloctests/benches/str.rs diff --git a/library/alloc/benches/string.rs b/library/alloctests/benches/string.rs similarity index 100% rename from library/alloc/benches/string.rs rename to library/alloctests/benches/string.rs diff --git a/library/alloc/benches/vec.rs b/library/alloctests/benches/vec.rs similarity index 100% rename from library/alloc/benches/vec.rs rename to library/alloctests/benches/vec.rs diff --git a/library/alloc/benches/vec_deque.rs b/library/alloctests/benches/vec_deque.rs similarity index 100% rename from library/alloc/benches/vec_deque.rs rename to library/alloctests/benches/vec_deque.rs diff --git a/library/alloc/benches/vec_deque_append.rs b/library/alloctests/benches/vec_deque_append.rs similarity index 100% rename from library/alloc/benches/vec_deque_append.rs rename to library/alloctests/benches/vec_deque_append.rs diff --git a/library/alloctests/lib.rs b/library/alloctests/lib.rs new file mode 100644 index 0000000000000..b49208cd4eb3a --- /dev/null +++ b/library/alloctests/lib.rs @@ -0,0 +1 @@ +// Intentionally left empty. diff --git a/library/alloc/tests/alloc.rs b/library/alloctests/tests/alloc_test.rs similarity index 100% rename from library/alloc/tests/alloc.rs rename to library/alloctests/tests/alloc_test.rs diff --git a/library/alloc/tests/arc.rs b/library/alloctests/tests/arc.rs similarity index 100% rename from library/alloc/tests/arc.rs rename to library/alloctests/tests/arc.rs diff --git a/library/alloc/tests/autotraits.rs b/library/alloctests/tests/autotraits.rs similarity index 100% rename from library/alloc/tests/autotraits.rs rename to library/alloctests/tests/autotraits.rs diff --git a/library/alloc/tests/borrow.rs b/library/alloctests/tests/borrow.rs similarity index 100% rename from library/alloc/tests/borrow.rs rename to library/alloctests/tests/borrow.rs diff --git a/library/alloc/tests/boxed.rs b/library/alloctests/tests/boxed.rs similarity index 100% rename from library/alloc/tests/boxed.rs rename to library/alloctests/tests/boxed.rs diff --git a/library/alloc/tests/btree_set_hash.rs b/library/alloctests/tests/btree_set_hash.rs similarity index 100% rename from library/alloc/tests/btree_set_hash.rs rename to library/alloctests/tests/btree_set_hash.rs diff --git a/library/alloc/tests/c_str.rs b/library/alloctests/tests/c_str.rs similarity index 100% rename from library/alloc/tests/c_str.rs rename to library/alloctests/tests/c_str.rs diff --git a/library/alloc/tests/c_str2.rs b/library/alloctests/tests/c_str2.rs similarity index 100% rename from library/alloc/tests/c_str2.rs rename to library/alloctests/tests/c_str2.rs diff --git a/library/alloc/tests/collections/binary_heap.rs b/library/alloctests/tests/collections/binary_heap.rs similarity index 100% rename from library/alloc/tests/collections/binary_heap.rs rename to library/alloctests/tests/collections/binary_heap.rs diff --git a/library/alloc/tests/collections/mod.rs b/library/alloctests/tests/collections/mod.rs similarity index 100% rename from library/alloc/tests/collections/mod.rs rename to library/alloctests/tests/collections/mod.rs diff --git a/library/alloc/tests/const_fns.rs b/library/alloctests/tests/const_fns.rs similarity index 100% rename from library/alloc/tests/const_fns.rs rename to library/alloctests/tests/const_fns.rs diff --git a/library/alloc/tests/cow_str.rs b/library/alloctests/tests/cow_str.rs similarity index 100% rename from library/alloc/tests/cow_str.rs rename to library/alloctests/tests/cow_str.rs diff --git a/library/alloc/tests/fmt.rs b/library/alloctests/tests/fmt.rs similarity index 100% rename from library/alloc/tests/fmt.rs rename to library/alloctests/tests/fmt.rs diff --git a/library/alloc/tests/heap.rs b/library/alloctests/tests/heap.rs similarity index 100% rename from library/alloc/tests/heap.rs rename to library/alloctests/tests/heap.rs diff --git a/library/alloc/tests/lib.rs b/library/alloctests/tests/lib.rs similarity index 98% rename from library/alloc/tests/lib.rs rename to library/alloctests/tests/lib.rs index f95be6a6df0b3..8b158a694475e 100644 --- a/library/alloc/tests/lib.rs +++ b/library/alloctests/tests/lib.rs @@ -45,11 +45,12 @@ #![deny(fuzzy_provenance_casts)] #![deny(unsafe_op_in_unsafe_fn)] +extern crate alloc; extern crate test; use std::hash::{DefaultHasher, Hash, Hasher}; -mod alloc; +mod alloc_test; mod arc; mod autotraits; mod borrow; diff --git a/library/alloc/tests/linked_list.rs b/library/alloctests/tests/linked_list.rs similarity index 100% rename from library/alloc/tests/linked_list.rs rename to library/alloctests/tests/linked_list.rs diff --git a/library/alloc/tests/misc_tests.rs b/library/alloctests/tests/misc_tests.rs similarity index 100% rename from library/alloc/tests/misc_tests.rs rename to library/alloctests/tests/misc_tests.rs diff --git a/library/alloc/tests/rc.rs b/library/alloctests/tests/rc.rs similarity index 100% rename from library/alloc/tests/rc.rs rename to library/alloctests/tests/rc.rs diff --git a/library/alloc/tests/slice.rs b/library/alloctests/tests/slice.rs similarity index 100% rename from library/alloc/tests/slice.rs rename to library/alloctests/tests/slice.rs diff --git a/library/alloc/tests/sort/ffi_types.rs b/library/alloctests/tests/sort/ffi_types.rs similarity index 100% rename from library/alloc/tests/sort/ffi_types.rs rename to library/alloctests/tests/sort/ffi_types.rs diff --git a/library/alloc/tests/sort/known_good_stable_sort.rs b/library/alloctests/tests/sort/known_good_stable_sort.rs similarity index 100% rename from library/alloc/tests/sort/known_good_stable_sort.rs rename to library/alloctests/tests/sort/known_good_stable_sort.rs diff --git a/library/alloc/tests/sort/mod.rs b/library/alloctests/tests/sort/mod.rs similarity index 100% rename from library/alloc/tests/sort/mod.rs rename to library/alloctests/tests/sort/mod.rs diff --git a/library/alloc/tests/sort/patterns.rs b/library/alloctests/tests/sort/patterns.rs similarity index 100% rename from library/alloc/tests/sort/patterns.rs rename to library/alloctests/tests/sort/patterns.rs diff --git a/library/alloc/tests/sort/tests.rs b/library/alloctests/tests/sort/tests.rs similarity index 100% rename from library/alloc/tests/sort/tests.rs rename to library/alloctests/tests/sort/tests.rs diff --git a/library/alloc/tests/sort/zipf.rs b/library/alloctests/tests/sort/zipf.rs similarity index 100% rename from library/alloc/tests/sort/zipf.rs rename to library/alloctests/tests/sort/zipf.rs diff --git a/library/alloc/tests/str.rs b/library/alloctests/tests/str.rs similarity index 100% rename from library/alloc/tests/str.rs rename to library/alloctests/tests/str.rs diff --git a/library/alloc/tests/string.rs b/library/alloctests/tests/string.rs similarity index 100% rename from library/alloc/tests/string.rs rename to library/alloctests/tests/string.rs diff --git a/library/alloc/tests/sync.rs b/library/alloctests/tests/sync.rs similarity index 100% rename from library/alloc/tests/sync.rs rename to library/alloctests/tests/sync.rs diff --git a/library/alloc/tests/task.rs b/library/alloctests/tests/task.rs similarity index 100% rename from library/alloc/tests/task.rs rename to library/alloctests/tests/task.rs diff --git a/library/alloc/tests/testing/crash_test.rs b/library/alloctests/tests/testing/crash_test.rs similarity index 100% rename from library/alloc/tests/testing/crash_test.rs rename to library/alloctests/tests/testing/crash_test.rs diff --git a/library/alloc/tests/testing/mod.rs b/library/alloctests/tests/testing/mod.rs similarity index 100% rename from library/alloc/tests/testing/mod.rs rename to library/alloctests/tests/testing/mod.rs diff --git a/library/alloc/tests/thin_box.rs b/library/alloctests/tests/thin_box.rs similarity index 100% rename from library/alloc/tests/thin_box.rs rename to library/alloctests/tests/thin_box.rs diff --git a/library/alloc/tests/vec.rs b/library/alloctests/tests/vec.rs similarity index 100% rename from library/alloc/tests/vec.rs rename to library/alloctests/tests/vec.rs diff --git a/library/alloc/tests/vec_deque.rs b/library/alloctests/tests/vec_deque.rs similarity index 100% rename from library/alloc/tests/vec_deque.rs rename to library/alloctests/tests/vec_deque.rs diff --git a/library/alloc/tests/vec_deque_alloc_error.rs b/library/alloctests/tests/vec_deque_alloc_error.rs similarity index 100% rename from library/alloc/tests/vec_deque_alloc_error.rs rename to library/alloctests/tests/vec_deque_alloc_error.rs diff --git a/src/bootstrap/mk/Makefile.in b/src/bootstrap/mk/Makefile.in index 88aa70d4f2f83..6cb0b19d7632a 100644 --- a/src/bootstrap/mk/Makefile.in +++ b/src/bootstrap/mk/Makefile.in @@ -56,6 +56,7 @@ check-aux: # Run standard library tests in Miri. $(Q)$(BOOTSTRAP) miri --stage 2 \ library/coretests \ + library/alloctests \ library/alloc \ $(BOOTSTRAP_ARGS) \ --no-doc @@ -63,6 +64,7 @@ check-aux: $(Q)MIRIFLAGS="-Zmiri-disable-isolation" \ $(BOOTSTRAP) miri --stage 2 \ library/coretests \ + library/alloctests \ library/alloc \ $(BOOTSTRAP_ARGS) \ --doc diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index 21afb0312033a..62500baea5b9e 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -45,7 +45,10 @@ impl Step for Std { const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.crate_or_deps("sysroot").crate_or_deps("coretests").path("library") + run.crate_or_deps("sysroot") + .crate_or_deps("coretests") + .crate_or_deps("alloctests") + .path("library") } fn make_run(run: RunConfig<'_>) { diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index b3f4a7bad99c2..43e26672fbc33 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -2669,7 +2669,7 @@ impl Step for Crate { const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.crate_or_deps("sysroot").crate_or_deps("coretests") + run.crate_or_deps("sysroot").crate_or_deps("coretests").crate_or_deps("alloctests") } fn make_run(run: RunConfig<'_>) { diff --git a/src/tools/tidy/src/style.rs b/src/tools/tidy/src/style.rs index 21b513629ed8d..32ae1e8f8c246 100644 --- a/src/tools/tidy/src/style.rs +++ b/src/tools/tidy/src/style.rs @@ -462,7 +462,7 @@ pub fn check(path: &Path, bad: &mut bool) { && !trimmed.starts_with("//") && !file.ancestors().any(|a| { (a.ends_with("tests") && a.join("COMPILER_TESTS.md").exists()) - || a.ends_with("library/alloc/tests") + || a.ends_with("library/alloctests") }) && filename != "tests.rs" { From 0b8637ada5d0519eab8918abdf66764e28737ed4 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 6 Feb 2025 12:07:24 +0000 Subject: [PATCH 04/20] Move most Rc tests to alloctests --- library/alloc/src/rc/tests.rs | 649 --------------------------------- library/alloctests/tests/rc.rs | 648 +++++++++++++++++++++++++++++++- 2 files changed, 647 insertions(+), 650 deletions(-) diff --git a/library/alloc/src/rc/tests.rs b/library/alloc/src/rc/tests.rs index 2210a7c24c06a..35ff6b7d570d0 100644 --- a/library/alloc/src/rc/tests.rs +++ b/library/alloc/src/rc/tests.rs @@ -1,64 +1,5 @@ -use std::cell::RefCell; -use std::clone::Clone; - use super::*; -#[test] -fn test_clone() { - let x = Rc::new(RefCell::new(5)); - let y = x.clone(); - *x.borrow_mut() = 20; - assert_eq!(*y.borrow(), 20); -} - -#[test] -fn test_simple() { - let x = Rc::new(5); - assert_eq!(*x, 5); -} - -#[test] -fn test_simple_clone() { - let x = Rc::new(5); - let y = x.clone(); - assert_eq!(*x, 5); - assert_eq!(*y, 5); -} - -#[test] -fn test_destructor() { - let x: Rc> = Rc::new(Box::new(5)); - assert_eq!(**x, 5); -} - -#[test] -fn test_live() { - let x = Rc::new(5); - let y = Rc::downgrade(&x); - assert!(y.upgrade().is_some()); -} - -#[test] -fn test_dead() { - let x = Rc::new(5); - let y = Rc::downgrade(&x); - drop(x); - assert!(y.upgrade().is_none()); -} - -#[test] -fn weak_self_cyclic() { - struct Cycle { - x: RefCell>>, - } - - let a = Rc::new(Cycle { x: RefCell::new(None) }); - let b = Rc::downgrade(&a.clone()); - *a.x.borrow_mut() = Some(b); - - // hopefully we don't double-free (or leak)... -} - #[test] fn is_unique() { let x = Rc::new(3); @@ -72,593 +13,3 @@ fn is_unique() { drop(w); assert!(Rc::is_unique(&x)); } - -#[test] -fn test_strong_count() { - let a = Rc::new(0); - assert!(Rc::strong_count(&a) == 1); - let w = Rc::downgrade(&a); - assert!(Rc::strong_count(&a) == 1); - let b = w.upgrade().expect("upgrade of live rc failed"); - assert!(Rc::strong_count(&b) == 2); - assert!(Rc::strong_count(&a) == 2); - drop(w); - drop(a); - assert!(Rc::strong_count(&b) == 1); - let c = b.clone(); - assert!(Rc::strong_count(&b) == 2); - assert!(Rc::strong_count(&c) == 2); -} - -#[test] -fn test_weak_count() { - let a = Rc::new(0); - assert!(Rc::strong_count(&a) == 1); - assert!(Rc::weak_count(&a) == 0); - let w = Rc::downgrade(&a); - assert!(Rc::strong_count(&a) == 1); - assert!(Rc::weak_count(&a) == 1); - drop(w); - assert!(Rc::strong_count(&a) == 1); - assert!(Rc::weak_count(&a) == 0); - let c = a.clone(); - assert!(Rc::strong_count(&a) == 2); - assert!(Rc::weak_count(&a) == 0); - drop(c); -} - -#[test] -fn weak_counts() { - assert_eq!(Weak::weak_count(&Weak::::new()), 0); - assert_eq!(Weak::strong_count(&Weak::::new()), 0); - - let a = Rc::new(0); - let w = Rc::downgrade(&a); - assert_eq!(Weak::strong_count(&w), 1); - assert_eq!(Weak::weak_count(&w), 1); - let w2 = w.clone(); - assert_eq!(Weak::strong_count(&w), 1); - assert_eq!(Weak::weak_count(&w), 2); - assert_eq!(Weak::strong_count(&w2), 1); - assert_eq!(Weak::weak_count(&w2), 2); - drop(w); - assert_eq!(Weak::strong_count(&w2), 1); - assert_eq!(Weak::weak_count(&w2), 1); - let a2 = a.clone(); - assert_eq!(Weak::strong_count(&w2), 2); - assert_eq!(Weak::weak_count(&w2), 1); - drop(a2); - drop(a); - assert_eq!(Weak::strong_count(&w2), 0); - assert_eq!(Weak::weak_count(&w2), 0); - drop(w2); -} - -#[test] -fn try_unwrap() { - let x = Rc::new(3); - assert_eq!(Rc::try_unwrap(x), Ok(3)); - let x = Rc::new(4); - let _y = x.clone(); - assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4))); - let x = Rc::new(5); - let _w = Rc::downgrade(&x); - assert_eq!(Rc::try_unwrap(x), Ok(5)); -} - -#[test] -fn into_inner() { - let x = Rc::new(3); - assert_eq!(Rc::into_inner(x), Some(3)); - - let x = Rc::new(4); - let y = Rc::clone(&x); - assert_eq!(Rc::into_inner(x), None); - assert_eq!(Rc::into_inner(y), Some(4)); - - let x = Rc::new(5); - let _w = Rc::downgrade(&x); - assert_eq!(Rc::into_inner(x), Some(5)); -} - -#[test] -fn into_from_raw() { - let x = Rc::new(Box::new("hello")); - let y = x.clone(); - - let x_ptr = Rc::into_raw(x); - drop(y); - unsafe { - assert_eq!(**x_ptr, "hello"); - - let x = Rc::from_raw(x_ptr); - assert_eq!(**x, "hello"); - - assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello")); - } -} - -#[test] -fn test_into_from_raw_unsized() { - use std::fmt::Display; - use std::string::ToString; - - let rc: Rc = Rc::from("foo"); - - let ptr = Rc::into_raw(rc.clone()); - let rc2 = unsafe { Rc::from_raw(ptr) }; - - assert_eq!(unsafe { &*ptr }, "foo"); - assert_eq!(rc, rc2); - - let rc: Rc = Rc::new(123); - - let ptr = Rc::into_raw(rc.clone()); - let rc2 = unsafe { Rc::from_raw(ptr) }; - - assert_eq!(unsafe { &*ptr }.to_string(), "123"); - assert_eq!(rc2.to_string(), "123"); -} - -#[test] -fn into_from_weak_raw() { - let x = Rc::new(Box::new("hello")); - let y = Rc::downgrade(&x); - - let y_ptr = Weak::into_raw(y); - unsafe { - assert_eq!(**y_ptr, "hello"); - - let y = Weak::from_raw(y_ptr); - let y_up = Weak::upgrade(&y).unwrap(); - assert_eq!(**y_up, "hello"); - drop(y_up); - - assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello")); - } -} - -#[test] -fn test_into_from_weak_raw_unsized() { - use std::fmt::Display; - use std::string::ToString; - - let arc: Rc = Rc::from("foo"); - let weak: Weak = Rc::downgrade(&arc); - - let ptr = Weak::into_raw(weak.clone()); - let weak2 = unsafe { Weak::from_raw(ptr) }; - - assert_eq!(unsafe { &*ptr }, "foo"); - assert!(weak.ptr_eq(&weak2)); - - let arc: Rc = Rc::new(123); - let weak: Weak = Rc::downgrade(&arc); - - let ptr = Weak::into_raw(weak.clone()); - let weak2 = unsafe { Weak::from_raw(ptr) }; - - assert_eq!(unsafe { &*ptr }.to_string(), "123"); - assert!(weak.ptr_eq(&weak2)); -} - -#[test] -fn get_mut() { - let mut x = Rc::new(3); - *Rc::get_mut(&mut x).unwrap() = 4; - assert_eq!(*x, 4); - let y = x.clone(); - assert!(Rc::get_mut(&mut x).is_none()); - drop(y); - assert!(Rc::get_mut(&mut x).is_some()); - let _w = Rc::downgrade(&x); - assert!(Rc::get_mut(&mut x).is_none()); -} - -#[test] -fn test_cowrc_clone_make_unique() { - let mut cow0 = Rc::new(75); - let mut cow1 = cow0.clone(); - let mut cow2 = cow1.clone(); - - assert!(75 == *Rc::make_mut(&mut cow0)); - assert!(75 == *Rc::make_mut(&mut cow1)); - assert!(75 == *Rc::make_mut(&mut cow2)); - - *Rc::make_mut(&mut cow0) += 1; - *Rc::make_mut(&mut cow1) += 2; - *Rc::make_mut(&mut cow2) += 3; - - assert!(76 == *cow0); - assert!(77 == *cow1); - assert!(78 == *cow2); - - // none should point to the same backing memory - assert!(*cow0 != *cow1); - assert!(*cow0 != *cow2); - assert!(*cow1 != *cow2); -} - -#[test] -fn test_cowrc_clone_unique2() { - let mut cow0 = Rc::new(75); - let cow1 = cow0.clone(); - let cow2 = cow1.clone(); - - assert!(75 == *cow0); - assert!(75 == *cow1); - assert!(75 == *cow2); - - *Rc::make_mut(&mut cow0) += 1; - - assert!(76 == *cow0); - assert!(75 == *cow1); - assert!(75 == *cow2); - - // cow1 and cow2 should share the same contents - // cow0 should have a unique reference - assert!(*cow0 != *cow1); - assert!(*cow0 != *cow2); - assert!(*cow1 == *cow2); -} - -#[test] -fn test_cowrc_clone_weak() { - let mut cow0 = Rc::new(75); - let cow1_weak = Rc::downgrade(&cow0); - - assert!(75 == *cow0); - assert!(75 == *cow1_weak.upgrade().unwrap()); - - *Rc::make_mut(&mut cow0) += 1; - - assert!(76 == *cow0); - assert!(cow1_weak.upgrade().is_none()); -} - -/// This is similar to the doc-test for `Rc::make_mut()`, but on an unsized type (slice). -#[test] -fn test_cowrc_unsized() { - use std::rc::Rc; - - let mut data: Rc<[i32]> = Rc::new([10, 20, 30]); - - Rc::make_mut(&mut data)[0] += 1; // Won't clone anything - let mut other_data = Rc::clone(&data); // Won't clone inner data - Rc::make_mut(&mut data)[1] += 1; // Clones inner data - Rc::make_mut(&mut data)[2] += 1; // Won't clone anything - Rc::make_mut(&mut other_data)[0] *= 10; // Won't clone anything - - // Now `data` and `other_data` point to different allocations. - assert_eq!(*data, [11, 21, 31]); - assert_eq!(*other_data, [110, 20, 30]); -} - -#[test] -fn test_show() { - let foo = Rc::new(75); - assert_eq!(format!("{foo:?}"), "75"); -} - -#[test] -fn test_unsized() { - let foo: Rc<[i32]> = Rc::new([1, 2, 3]); - assert_eq!(foo, foo.clone()); -} - -#[test] -fn test_maybe_thin_unsized() { - // If/when custom thin DSTs exist, this test should be updated to use one - use std::ffi::CStr; - - let x: Rc = Rc::from(c"swordfish"); - assert_eq!(format!("{x:?}"), "\"swordfish\""); - let y: Weak = Rc::downgrade(&x); - drop(x); - - // At this point, the weak points to a dropped DST - assert!(y.upgrade().is_none()); - // But we still need to be able to get the alloc layout to drop. - // CStr has no drop glue, but custom DSTs might, and need to work. - drop(y); -} - -#[test] -fn test_from_owned() { - let foo = 123; - let foo_rc = Rc::from(foo); - assert!(123 == *foo_rc); -} - -#[test] -fn test_new_weak() { - let foo: Weak = Weak::new(); - assert!(foo.upgrade().is_none()); -} - -#[test] -fn test_ptr_eq() { - let five = Rc::new(5); - let same_five = five.clone(); - let other_five = Rc::new(5); - - assert!(Rc::ptr_eq(&five, &same_five)); - assert!(!Rc::ptr_eq(&five, &other_five)); -} - -#[test] -fn test_from_str() { - let r: Rc = Rc::from("foo"); - - assert_eq!(&r[..], "foo"); -} - -#[test] -fn test_copy_from_slice() { - let s: &[u32] = &[1, 2, 3]; - let r: Rc<[u32]> = Rc::from(s); - - assert_eq!(&r[..], [1, 2, 3]); -} - -#[test] -fn test_clone_from_slice() { - #[derive(Clone, Debug, Eq, PartialEq)] - struct X(u32); - - let s: &[X] = &[X(1), X(2), X(3)]; - let r: Rc<[X]> = Rc::from(s); - - assert_eq!(&r[..], s); -} - -#[test] -#[should_panic] -fn test_clone_from_slice_panic() { - use std::string::{String, ToString}; - - struct Fail(u32, String); - - impl Clone for Fail { - fn clone(&self) -> Fail { - if self.0 == 2 { - panic!(); - } - Fail(self.0, self.1.clone()) - } - } - - let s: &[Fail] = - &[Fail(0, "foo".to_string()), Fail(1, "bar".to_string()), Fail(2, "baz".to_string())]; - - // Should panic, but not cause memory corruption - let _r: Rc<[Fail]> = Rc::from(s); -} - -#[test] -fn test_from_box() { - let b: Box = Box::new(123); - let r: Rc = Rc::from(b); - - assert_eq!(*r, 123); -} - -#[test] -fn test_from_box_str() { - use std::string::String; - - let s = String::from("foo").into_boxed_str(); - assert_eq!((&&&s).as_str(), "foo"); - - let r: Rc = Rc::from(s); - assert_eq!((&r).as_str(), "foo"); - assert_eq!(r.as_str(), "foo"); - - assert_eq!(&r[..], "foo"); -} - -#[test] -fn test_from_box_slice() { - let s = vec![1, 2, 3].into_boxed_slice(); - let r: Rc<[u32]> = Rc::from(s); - - assert_eq!(&r[..], [1, 2, 3]); -} - -#[test] -fn test_from_box_trait() { - use std::fmt::Display; - use std::string::ToString; - - let b: Box = Box::new(123); - let r: Rc = Rc::from(b); - - assert_eq!(r.to_string(), "123"); -} - -#[test] -fn test_from_box_trait_zero_sized() { - use std::fmt::Debug; - - let b: Box = Box::new(()); - let r: Rc = Rc::from(b); - - assert_eq!(format!("{r:?}"), "()"); -} - -#[test] -fn test_from_vec() { - let v = vec![1, 2, 3]; - let r: Rc<[u32]> = Rc::from(v); - - assert_eq!(&r[..], [1, 2, 3]); -} - -#[test] -fn test_downcast() { - use std::any::Any; - - let r1: Rc = Rc::new(i32::MAX); - let r2: Rc = Rc::new("abc"); - - assert!(r1.clone().downcast::().is_err()); - - let r1i32 = r1.downcast::(); - assert!(r1i32.is_ok()); - assert_eq!(r1i32.unwrap(), Rc::new(i32::MAX)); - - assert!(r2.clone().downcast::().is_err()); - - let r2str = r2.downcast::<&'static str>(); - assert!(r2str.is_ok()); - assert_eq!(r2str.unwrap(), Rc::new("abc")); -} - -#[test] -fn test_array_from_slice() { - let v = vec![1, 2, 3]; - let r: Rc<[u32]> = Rc::from(v); - - let a: Result, _> = r.clone().try_into(); - assert!(a.is_ok()); - - let a: Result, _> = r.clone().try_into(); - assert!(a.is_err()); -} - -#[test] -fn test_rc_cyclic_with_zero_refs() { - struct ZeroRefs { - inner: Weak, - } - - let zero_refs = Rc::new_cyclic(|inner| { - assert_eq!(inner.strong_count(), 0); - assert!(inner.upgrade().is_none()); - ZeroRefs { inner: Weak::new() } - }); - - assert_eq!(Rc::strong_count(&zero_refs), 1); - assert_eq!(Rc::weak_count(&zero_refs), 0); - assert_eq!(zero_refs.inner.strong_count(), 0); - assert_eq!(zero_refs.inner.weak_count(), 0); -} - -#[test] -fn test_rc_cyclic_with_one_ref() { - struct OneRef { - inner: Weak, - } - - let one_ref = Rc::new_cyclic(|inner| { - assert_eq!(inner.strong_count(), 0); - assert!(inner.upgrade().is_none()); - OneRef { inner: inner.clone() } - }); - - assert_eq!(Rc::strong_count(&one_ref), 1); - assert_eq!(Rc::weak_count(&one_ref), 1); - - let one_ref2 = Weak::upgrade(&one_ref.inner).unwrap(); - assert!(Rc::ptr_eq(&one_ref, &one_ref2)); - - assert_eq!(one_ref.inner.strong_count(), 2); - assert_eq!(one_ref.inner.weak_count(), 1); -} - -#[test] -fn test_rc_cyclic_with_two_ref() { - struct TwoRefs { - inner: Weak, - inner1: Weak, - } - - let two_refs = Rc::new_cyclic(|inner| { - assert_eq!(inner.strong_count(), 0); - assert!(inner.upgrade().is_none()); - TwoRefs { inner: inner.clone(), inner1: inner.clone() } - }); - - assert_eq!(Rc::strong_count(&two_refs), 1); - assert_eq!(Rc::weak_count(&two_refs), 2); - - let two_ref3 = Weak::upgrade(&two_refs.inner).unwrap(); - assert!(Rc::ptr_eq(&two_refs, &two_ref3)); - - let two_ref2 = Weak::upgrade(&two_refs.inner1).unwrap(); - assert!(Rc::ptr_eq(&two_refs, &two_ref2)); - - assert_eq!(Rc::strong_count(&two_refs), 3); - assert_eq!(Rc::weak_count(&two_refs), 2); -} - -#[test] -fn test_unique_rc_weak() { - let rc = UniqueRc::new(42); - let weak = UniqueRc::downgrade(&rc); - assert!(weak.upgrade().is_none()); - - let _rc = UniqueRc::into_rc(rc); - assert_eq!(*weak.upgrade().unwrap(), 42); -} - -#[test] -fn test_unique_rc_drop_weak() { - let rc = UniqueRc::new(42); - let weak = UniqueRc::downgrade(&rc); - mem::drop(weak); - - let rc = UniqueRc::into_rc(rc); - assert_eq!(*rc, 42); -} - -#[test] -fn test_unique_rc_drops_contents() { - let mut dropped = false; - struct DropMe<'a>(&'a mut bool); - impl Drop for DropMe<'_> { - fn drop(&mut self) { - *self.0 = true; - } - } - { - let rc = UniqueRc::new(DropMe(&mut dropped)); - drop(rc); - } - assert!(dropped); -} - -/// Exercise the non-default allocator usage. -#[test] -fn test_unique_rc_with_alloc_drops_contents() { - let mut dropped = false; - struct DropMe<'a>(&'a mut bool); - impl Drop for DropMe<'_> { - fn drop(&mut self) { - *self.0 = true; - } - } - { - let rc = UniqueRc::new_in(DropMe(&mut dropped), std::alloc::System); - drop(rc); - } - assert!(dropped); -} - -#[test] -fn test_unique_rc_weak_clone_holding_ref() { - let mut v = UniqueRc::new(0u8); - let w = UniqueRc::downgrade(&v); - let r = &mut *v; - let _ = w.clone(); // touch weak count - *r = 123; -} - -#[test] -fn test_unique_rc_unsizing_coercion() { - let mut rc: UniqueRc<[u8]> = UniqueRc::new([0u8; 3]); - assert_eq!(rc.len(), 3); - rc[0] = 123; - let rc: Rc<[u8]> = UniqueRc::into_rc(rc); - assert_eq!(*rc, [123, 0, 0]); -} diff --git a/library/alloctests/tests/rc.rs b/library/alloctests/tests/rc.rs index 451765d724283..fc3189e7cc413 100644 --- a/library/alloctests/tests/rc.rs +++ b/library/alloctests/tests/rc.rs @@ -2,7 +2,7 @@ use std::any::Any; use std::cell::{Cell, RefCell}; use std::iter::TrustedLen; use std::mem; -use std::rc::{Rc, Weak}; +use std::rc::{Rc, UniqueRc, Weak}; #[test] fn uninhabited() { @@ -258,3 +258,649 @@ mod pin_coerce_unsized { arg } } + +#[test] +fn test_clone() { + let x = Rc::new(RefCell::new(5)); + let y = x.clone(); + *x.borrow_mut() = 20; + assert_eq!(*y.borrow(), 20); +} + +#[test] +fn test_simple() { + let x = Rc::new(5); + assert_eq!(*x, 5); +} + +#[test] +fn test_simple_clone() { + let x = Rc::new(5); + let y = x.clone(); + assert_eq!(*x, 5); + assert_eq!(*y, 5); +} + +#[test] +fn test_destructor() { + let x: Rc> = Rc::new(Box::new(5)); + assert_eq!(**x, 5); +} + +#[test] +fn test_live() { + let x = Rc::new(5); + let y = Rc::downgrade(&x); + assert!(y.upgrade().is_some()); +} + +#[test] +fn test_dead() { + let x = Rc::new(5); + let y = Rc::downgrade(&x); + drop(x); + assert!(y.upgrade().is_none()); +} + +#[test] +fn weak_self_cyclic() { + struct Cycle { + x: RefCell>>, + } + + let a = Rc::new(Cycle { x: RefCell::new(None) }); + let b = Rc::downgrade(&a.clone()); + *a.x.borrow_mut() = Some(b); + + // hopefully we don't double-free (or leak)... +} + +#[test] +fn test_strong_count() { + let a = Rc::new(0); + assert!(Rc::strong_count(&a) == 1); + let w = Rc::downgrade(&a); + assert!(Rc::strong_count(&a) == 1); + let b = w.upgrade().expect("upgrade of live rc failed"); + assert!(Rc::strong_count(&b) == 2); + assert!(Rc::strong_count(&a) == 2); + drop(w); + drop(a); + assert!(Rc::strong_count(&b) == 1); + let c = b.clone(); + assert!(Rc::strong_count(&b) == 2); + assert!(Rc::strong_count(&c) == 2); +} + +#[test] +fn test_weak_count() { + let a = Rc::new(0); + assert!(Rc::strong_count(&a) == 1); + assert!(Rc::weak_count(&a) == 0); + let w = Rc::downgrade(&a); + assert!(Rc::strong_count(&a) == 1); + assert!(Rc::weak_count(&a) == 1); + drop(w); + assert!(Rc::strong_count(&a) == 1); + assert!(Rc::weak_count(&a) == 0); + let c = a.clone(); + assert!(Rc::strong_count(&a) == 2); + assert!(Rc::weak_count(&a) == 0); + drop(c); +} + +#[test] +fn weak_counts() { + assert_eq!(Weak::weak_count(&Weak::::new()), 0); + assert_eq!(Weak::strong_count(&Weak::::new()), 0); + + let a = Rc::new(0); + let w = Rc::downgrade(&a); + assert_eq!(Weak::strong_count(&w), 1); + assert_eq!(Weak::weak_count(&w), 1); + let w2 = w.clone(); + assert_eq!(Weak::strong_count(&w), 1); + assert_eq!(Weak::weak_count(&w), 2); + assert_eq!(Weak::strong_count(&w2), 1); + assert_eq!(Weak::weak_count(&w2), 2); + drop(w); + assert_eq!(Weak::strong_count(&w2), 1); + assert_eq!(Weak::weak_count(&w2), 1); + let a2 = a.clone(); + assert_eq!(Weak::strong_count(&w2), 2); + assert_eq!(Weak::weak_count(&w2), 1); + drop(a2); + drop(a); + assert_eq!(Weak::strong_count(&w2), 0); + assert_eq!(Weak::weak_count(&w2), 0); + drop(w2); +} + +#[test] +fn try_unwrap() { + let x = Rc::new(3); + assert_eq!(Rc::try_unwrap(x), Ok(3)); + let x = Rc::new(4); + let _y = x.clone(); + assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4))); + let x = Rc::new(5); + let _w = Rc::downgrade(&x); + assert_eq!(Rc::try_unwrap(x), Ok(5)); +} + +#[test] +fn into_inner() { + let x = Rc::new(3); + assert_eq!(Rc::into_inner(x), Some(3)); + + let x = Rc::new(4); + let y = Rc::clone(&x); + assert_eq!(Rc::into_inner(x), None); + assert_eq!(Rc::into_inner(y), Some(4)); + + let x = Rc::new(5); + let _w = Rc::downgrade(&x); + assert_eq!(Rc::into_inner(x), Some(5)); +} + +#[test] +fn into_from_raw() { + let x = Rc::new(Box::new("hello")); + let y = x.clone(); + + let x_ptr = Rc::into_raw(x); + drop(y); + unsafe { + assert_eq!(**x_ptr, "hello"); + + let x = Rc::from_raw(x_ptr); + assert_eq!(**x, "hello"); + + assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello")); + } +} + +#[test] +fn test_into_from_raw_unsized() { + use std::fmt::Display; + use std::string::ToString; + + let rc: Rc = Rc::from("foo"); + + let ptr = Rc::into_raw(rc.clone()); + let rc2 = unsafe { Rc::from_raw(ptr) }; + + assert_eq!(unsafe { &*ptr }, "foo"); + assert_eq!(rc, rc2); + + let rc: Rc = Rc::new(123); + + let ptr = Rc::into_raw(rc.clone()); + let rc2 = unsafe { Rc::from_raw(ptr) }; + + assert_eq!(unsafe { &*ptr }.to_string(), "123"); + assert_eq!(rc2.to_string(), "123"); +} + +#[test] +fn into_from_weak_raw() { + let x = Rc::new(Box::new("hello")); + let y = Rc::downgrade(&x); + + let y_ptr = Weak::into_raw(y); + unsafe { + assert_eq!(**y_ptr, "hello"); + + let y = Weak::from_raw(y_ptr); + let y_up = Weak::upgrade(&y).unwrap(); + assert_eq!(**y_up, "hello"); + drop(y_up); + + assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello")); + } +} + +#[test] +fn test_into_from_weak_raw_unsized() { + use std::fmt::Display; + use std::string::ToString; + + let arc: Rc = Rc::from("foo"); + let weak: Weak = Rc::downgrade(&arc); + + let ptr = Weak::into_raw(weak.clone()); + let weak2 = unsafe { Weak::from_raw(ptr) }; + + assert_eq!(unsafe { &*ptr }, "foo"); + assert!(weak.ptr_eq(&weak2)); + + let arc: Rc = Rc::new(123); + let weak: Weak = Rc::downgrade(&arc); + + let ptr = Weak::into_raw(weak.clone()); + let weak2 = unsafe { Weak::from_raw(ptr) }; + + assert_eq!(unsafe { &*ptr }.to_string(), "123"); + assert!(weak.ptr_eq(&weak2)); +} + +#[test] +fn get_mut() { + let mut x = Rc::new(3); + *Rc::get_mut(&mut x).unwrap() = 4; + assert_eq!(*x, 4); + let y = x.clone(); + assert!(Rc::get_mut(&mut x).is_none()); + drop(y); + assert!(Rc::get_mut(&mut x).is_some()); + let _w = Rc::downgrade(&x); + assert!(Rc::get_mut(&mut x).is_none()); +} + +#[test] +fn test_cowrc_clone_make_unique() { + let mut cow0 = Rc::new(75); + let mut cow1 = cow0.clone(); + let mut cow2 = cow1.clone(); + + assert!(75 == *Rc::make_mut(&mut cow0)); + assert!(75 == *Rc::make_mut(&mut cow1)); + assert!(75 == *Rc::make_mut(&mut cow2)); + + *Rc::make_mut(&mut cow0) += 1; + *Rc::make_mut(&mut cow1) += 2; + *Rc::make_mut(&mut cow2) += 3; + + assert!(76 == *cow0); + assert!(77 == *cow1); + assert!(78 == *cow2); + + // none should point to the same backing memory + assert!(*cow0 != *cow1); + assert!(*cow0 != *cow2); + assert!(*cow1 != *cow2); +} + +#[test] +fn test_cowrc_clone_unique2() { + let mut cow0 = Rc::new(75); + let cow1 = cow0.clone(); + let cow2 = cow1.clone(); + + assert!(75 == *cow0); + assert!(75 == *cow1); + assert!(75 == *cow2); + + *Rc::make_mut(&mut cow0) += 1; + + assert!(76 == *cow0); + assert!(75 == *cow1); + assert!(75 == *cow2); + + // cow1 and cow2 should share the same contents + // cow0 should have a unique reference + assert!(*cow0 != *cow1); + assert!(*cow0 != *cow2); + assert!(*cow1 == *cow2); +} + +#[test] +fn test_cowrc_clone_weak() { + let mut cow0 = Rc::new(75); + let cow1_weak = Rc::downgrade(&cow0); + + assert!(75 == *cow0); + assert!(75 == *cow1_weak.upgrade().unwrap()); + + *Rc::make_mut(&mut cow0) += 1; + + assert!(76 == *cow0); + assert!(cow1_weak.upgrade().is_none()); +} + +/// This is similar to the doc-test for `Rc::make_mut()`, but on an unsized type (slice). +#[test] +fn test_cowrc_unsized() { + use std::rc::Rc; + + let mut data: Rc<[i32]> = Rc::new([10, 20, 30]); + + Rc::make_mut(&mut data)[0] += 1; // Won't clone anything + let mut other_data = Rc::clone(&data); // Won't clone inner data + Rc::make_mut(&mut data)[1] += 1; // Clones inner data + Rc::make_mut(&mut data)[2] += 1; // Won't clone anything + Rc::make_mut(&mut other_data)[0] *= 10; // Won't clone anything + + // Now `data` and `other_data` point to different allocations. + assert_eq!(*data, [11, 21, 31]); + assert_eq!(*other_data, [110, 20, 30]); +} + +#[test] +fn test_show() { + let foo = Rc::new(75); + assert_eq!(format!("{foo:?}"), "75"); +} + +#[test] +fn test_unsized() { + let foo: Rc<[i32]> = Rc::new([1, 2, 3]); + assert_eq!(foo, foo.clone()); +} + +#[test] +fn test_maybe_thin_unsized() { + // If/when custom thin DSTs exist, this test should be updated to use one + use std::ffi::CStr; + + let x: Rc = Rc::from(c"swordfish"); + assert_eq!(format!("{x:?}"), "\"swordfish\""); + let y: Weak = Rc::downgrade(&x); + drop(x); + + // At this point, the weak points to a dropped DST + assert!(y.upgrade().is_none()); + // But we still need to be able to get the alloc layout to drop. + // CStr has no drop glue, but custom DSTs might, and need to work. + drop(y); +} + +#[test] +fn test_from_owned() { + let foo = 123; + let foo_rc = Rc::from(foo); + assert!(123 == *foo_rc); +} + +#[test] +fn test_new_weak() { + let foo: Weak = Weak::new(); + assert!(foo.upgrade().is_none()); +} + +#[test] +fn test_ptr_eq() { + let five = Rc::new(5); + let same_five = five.clone(); + let other_five = Rc::new(5); + + assert!(Rc::ptr_eq(&five, &same_five)); + assert!(!Rc::ptr_eq(&five, &other_five)); +} + +#[test] +fn test_from_str() { + let r: Rc = Rc::from("foo"); + + assert_eq!(&r[..], "foo"); +} + +#[test] +fn test_copy_from_slice() { + let s: &[u32] = &[1, 2, 3]; + let r: Rc<[u32]> = Rc::from(s); + + assert_eq!(&r[..], [1, 2, 3]); +} + +#[test] +fn test_clone_from_slice() { + #[derive(Clone, Debug, Eq, PartialEq)] + struct X(u32); + + let s: &[X] = &[X(1), X(2), X(3)]; + let r: Rc<[X]> = Rc::from(s); + + assert_eq!(&r[..], s); +} + +#[test] +#[should_panic] +fn test_clone_from_slice_panic() { + use std::string::{String, ToString}; + + struct Fail(u32, String); + + impl Clone for Fail { + fn clone(&self) -> Fail { + if self.0 == 2 { + panic!(); + } + Fail(self.0, self.1.clone()) + } + } + + let s: &[Fail] = + &[Fail(0, "foo".to_string()), Fail(1, "bar".to_string()), Fail(2, "baz".to_string())]; + + // Should panic, but not cause memory corruption + let _r: Rc<[Fail]> = Rc::from(s); +} + +#[test] +fn test_from_box() { + let b: Box = Box::new(123); + let r: Rc = Rc::from(b); + + assert_eq!(*r, 123); +} + +#[test] +fn test_from_box_str() { + use std::string::String; + + let s = String::from("foo").into_boxed_str(); + assert_eq!((&&&s).as_str(), "foo"); + + let r: Rc = Rc::from(s); + assert_eq!((&r).as_str(), "foo"); + assert_eq!(r.as_str(), "foo"); + + assert_eq!(&r[..], "foo"); +} + +#[test] +fn test_from_box_slice() { + let s = vec![1, 2, 3].into_boxed_slice(); + let r: Rc<[u32]> = Rc::from(s); + + assert_eq!(&r[..], [1, 2, 3]); +} + +#[test] +fn test_from_box_trait() { + use std::fmt::Display; + use std::string::ToString; + + let b: Box = Box::new(123); + let r: Rc = Rc::from(b); + + assert_eq!(r.to_string(), "123"); +} + +#[test] +fn test_from_box_trait_zero_sized() { + use std::fmt::Debug; + + let b: Box = Box::new(()); + let r: Rc = Rc::from(b); + + assert_eq!(format!("{r:?}"), "()"); +} + +#[test] +fn test_from_vec() { + let v = vec![1, 2, 3]; + let r: Rc<[u32]> = Rc::from(v); + + assert_eq!(&r[..], [1, 2, 3]); +} + +#[test] +fn test_downcast() { + use std::any::Any; + + let r1: Rc = Rc::new(i32::MAX); + let r2: Rc = Rc::new("abc"); + + assert!(r1.clone().downcast::().is_err()); + + let r1i32 = r1.downcast::(); + assert!(r1i32.is_ok()); + assert_eq!(r1i32.unwrap(), Rc::new(i32::MAX)); + + assert!(r2.clone().downcast::().is_err()); + + let r2str = r2.downcast::<&'static str>(); + assert!(r2str.is_ok()); + assert_eq!(r2str.unwrap(), Rc::new("abc")); +} + +#[test] +fn test_array_from_slice() { + let v = vec![1, 2, 3]; + let r: Rc<[u32]> = Rc::from(v); + + let a: Result, _> = r.clone().try_into(); + assert!(a.is_ok()); + + let a: Result, _> = r.clone().try_into(); + assert!(a.is_err()); +} + +#[test] +fn test_rc_cyclic_with_zero_refs() { + struct ZeroRefs { + inner: Weak, + } + + let zero_refs = Rc::new_cyclic(|inner| { + assert_eq!(inner.strong_count(), 0); + assert!(inner.upgrade().is_none()); + ZeroRefs { inner: Weak::new() } + }); + + assert_eq!(Rc::strong_count(&zero_refs), 1); + assert_eq!(Rc::weak_count(&zero_refs), 0); + assert_eq!(zero_refs.inner.strong_count(), 0); + assert_eq!(zero_refs.inner.weak_count(), 0); +} + +#[test] +fn test_rc_cyclic_with_one_ref() { + struct OneRef { + inner: Weak, + } + + let one_ref = Rc::new_cyclic(|inner| { + assert_eq!(inner.strong_count(), 0); + assert!(inner.upgrade().is_none()); + OneRef { inner: inner.clone() } + }); + + assert_eq!(Rc::strong_count(&one_ref), 1); + assert_eq!(Rc::weak_count(&one_ref), 1); + + let one_ref2 = Weak::upgrade(&one_ref.inner).unwrap(); + assert!(Rc::ptr_eq(&one_ref, &one_ref2)); + + assert_eq!(one_ref.inner.strong_count(), 2); + assert_eq!(one_ref.inner.weak_count(), 1); +} + +#[test] +fn test_rc_cyclic_with_two_ref() { + struct TwoRefs { + inner: Weak, + inner1: Weak, + } + + let two_refs = Rc::new_cyclic(|inner| { + assert_eq!(inner.strong_count(), 0); + assert!(inner.upgrade().is_none()); + TwoRefs { inner: inner.clone(), inner1: inner.clone() } + }); + + assert_eq!(Rc::strong_count(&two_refs), 1); + assert_eq!(Rc::weak_count(&two_refs), 2); + + let two_ref3 = Weak::upgrade(&two_refs.inner).unwrap(); + assert!(Rc::ptr_eq(&two_refs, &two_ref3)); + + let two_ref2 = Weak::upgrade(&two_refs.inner1).unwrap(); + assert!(Rc::ptr_eq(&two_refs, &two_ref2)); + + assert_eq!(Rc::strong_count(&two_refs), 3); + assert_eq!(Rc::weak_count(&two_refs), 2); +} + +#[test] +fn test_unique_rc_weak() { + let rc = UniqueRc::new(42); + let weak = UniqueRc::downgrade(&rc); + assert!(weak.upgrade().is_none()); + + let _rc = UniqueRc::into_rc(rc); + assert_eq!(*weak.upgrade().unwrap(), 42); +} + +#[test] +fn test_unique_rc_drop_weak() { + let rc = UniqueRc::new(42); + let weak = UniqueRc::downgrade(&rc); + mem::drop(weak); + + let rc = UniqueRc::into_rc(rc); + assert_eq!(*rc, 42); +} + +#[test] +fn test_unique_rc_drops_contents() { + let mut dropped = false; + struct DropMe<'a>(&'a mut bool); + impl Drop for DropMe<'_> { + fn drop(&mut self) { + *self.0 = true; + } + } + { + let rc = UniqueRc::new(DropMe(&mut dropped)); + drop(rc); + } + assert!(dropped); +} + +/// Exercise the non-default allocator usage. +#[test] +fn test_unique_rc_with_alloc_drops_contents() { + let mut dropped = false; + struct DropMe<'a>(&'a mut bool); + impl Drop for DropMe<'_> { + fn drop(&mut self) { + *self.0 = true; + } + } + { + let rc = UniqueRc::new_in(DropMe(&mut dropped), std::alloc::System); + drop(rc); + } + assert!(dropped); +} + +#[test] +fn test_unique_rc_weak_clone_holding_ref() { + let mut v = UniqueRc::new(0u8); + let w = UniqueRc::downgrade(&v); + let r = &mut *v; + let _ = w.clone(); // touch weak count + *r = 123; +} + +#[test] +fn test_unique_rc_unsizing_coercion() { + let mut rc: UniqueRc<[u8]> = UniqueRc::new([0u8; 3]); + assert_eq!(rc.len(), 3); + rc[0] = 123; + let rc: Rc<[u8]> = UniqueRc::into_rc(rc); + assert_eq!(*rc, [123, 0, 0]); +} From 413dda1f45b69c2e821713faa515fb207b78d1a4 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 6 Feb 2025 12:09:45 +0000 Subject: [PATCH 05/20] Move last remaining Rc test to alloctests --- library/alloc/src/{rc/mod.rs => rc.rs} | 3 --- library/alloc/src/rc/tests.rs | 15 --------------- library/alloctests/tests/rc.rs | 18 ++++++++++++++++++ 3 files changed, 18 insertions(+), 18 deletions(-) rename library/alloc/src/{rc/mod.rs => rc.rs} (99%) delete mode 100644 library/alloc/src/rc/tests.rs diff --git a/library/alloc/src/rc/mod.rs b/library/alloc/src/rc.rs similarity index 99% rename from library/alloc/src/rc/mod.rs rename to library/alloc/src/rc.rs index 09206c2f8b290..2a4d4f264444c 100644 --- a/library/alloc/src/rc/mod.rs +++ b/library/alloc/src/rc.rs @@ -276,9 +276,6 @@ use crate::string::String; #[cfg(not(no_global_oom_handling))] use crate::vec::Vec; -#[cfg(test)] -mod tests; - // This is repr(C) to future-proof against possible field-reordering, which // would interfere with otherwise safe [into|from]_raw() of transmutable // inner types. diff --git a/library/alloc/src/rc/tests.rs b/library/alloc/src/rc/tests.rs deleted file mode 100644 index 35ff6b7d570d0..0000000000000 --- a/library/alloc/src/rc/tests.rs +++ /dev/null @@ -1,15 +0,0 @@ -use super::*; - -#[test] -fn is_unique() { - let x = Rc::new(3); - assert!(Rc::is_unique(&x)); - let y = x.clone(); - assert!(!Rc::is_unique(&x)); - drop(y); - assert!(Rc::is_unique(&x)); - let w = Rc::downgrade(&x); - assert!(!Rc::is_unique(&x)); - drop(w); - assert!(Rc::is_unique(&x)); -} diff --git a/library/alloctests/tests/rc.rs b/library/alloctests/tests/rc.rs index fc3189e7cc413..e967b3eebd13e 100644 --- a/library/alloctests/tests/rc.rs +++ b/library/alloctests/tests/rc.rs @@ -315,6 +315,24 @@ fn weak_self_cyclic() { // hopefully we don't double-free (or leak)... } +#[test] +fn is_unique() { + fn is_unique(this: &Rc) -> bool { + Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1 + } + + let x = Rc::new(3); + assert!(is_unique(&x)); + let y = x.clone(); + assert!(!is_unique(&x)); + drop(y); + assert!(is_unique(&x)); + let w = Rc::downgrade(&x); + assert!(!is_unique(&x)); + drop(w); + assert!(is_unique(&x)); +} + #[test] fn test_strong_count() { let a = Rc::new(0); From e808f6681031bfde4505cd2534c3d87ab2c916b1 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 6 Feb 2025 12:46:33 +0000 Subject: [PATCH 06/20] Fully test the alloc crate through alloctests For the tests that make use of internal implementation details, we include the module to test using #[path] in alloctests now. --- ...le-f16-and-f128-in-compiler-builtins.patch | 6 +- library/Cargo.lock | 2 - library/alloc/Cargo.toml | 8 +- library/alloc/src/alloc.rs | 18 +- library/alloc/src/borrow.rs | 6 +- library/alloc/src/bstr.rs | 20 -- .../alloc/src/collections/binary_heap/mod.rs | 5 +- library/alloc/src/collections/mod.rs | 21 ++ .../alloc/src/collections/vec_deque/mod.rs | 1 + .../src/collections/vec_deque/spec_extend.rs | 2 + .../collections/vec_deque/spec_from_iter.rs | 1 + library/alloc/src/ffi/c_str.rs | 16 +- library/alloc/src/lib.rs | 39 +--- library/alloc/src/macros.rs | 23 +-- library/alloc/src/raw_vec/mod.rs | 1 + library/alloc/src/rc.rs | 7 +- library/alloc/src/slice.rs | 182 +++++++----------- library/alloc/src/str.rs | 3 - library/alloc/src/string.rs | 30 +-- library/alloc/src/sync.rs | 4 +- library/alloc/src/vec/into_iter.rs | 5 - library/alloc/src/vec/mod.rs | 47 +---- library/alloctests/Cargo.toml | 9 +- library/alloctests/lib.rs | 91 ++++++++- .../src => alloctests}/testing/crash_test.rs | 0 .../{alloc/src => alloctests}/testing/mod.rs | 0 .../src => alloctests}/testing/ord_chaos.rs | 0 .../{alloc/src => alloctests}/testing/rng.rs | 0 28 files changed, 234 insertions(+), 313 deletions(-) rename library/{alloc/src => alloctests}/testing/crash_test.rs (100%) rename library/{alloc/src => alloctests}/testing/mod.rs (100%) rename library/{alloc/src => alloctests}/testing/ord_chaos.rs (100%) rename library/{alloc/src => alloctests}/testing/rng.rs (100%) diff --git a/compiler/rustc_codegen_cranelift/patches/0029-stdlib-Disable-f16-and-f128-in-compiler-builtins.patch b/compiler/rustc_codegen_cranelift/patches/0029-stdlib-Disable-f16-and-f128-in-compiler-builtins.patch index e3a9512dda9c6..f430d16d7c181 100644 --- a/compiler/rustc_codegen_cranelift/patches/0029-stdlib-Disable-f16-and-f128-in-compiler-builtins.patch +++ b/compiler/rustc_codegen_cranelift/patches/0029-stdlib-Disable-f16-and-f128-in-compiler-builtins.patch @@ -12,15 +12,15 @@ index 7165c3e48af..968552ad435 100644 --- a/library/alloc/Cargo.toml +++ b/library/alloc/Cargo.toml @@ -11,7 +11,7 @@ test = { path = "../test" } - edition = "2021" + bench = false [dependencies] core = { path = "../core" } -compiler_builtins = { version = "=0.1.146", features = ['rustc-dep-of-std'] } +compiler_builtins = { version = "=0.1.146", features = ['rustc-dep-of-std', 'no-f16-f128'] } - [dev-dependencies] - rand = { version = "0.8.5", default-features = false, features = ["alloc"] } + [features] + compiler-builtins-mem = ['compiler_builtins/mem'] -- 2.34.1 diff --git a/library/Cargo.lock b/library/Cargo.lock index 3d40caa18c971..a06120c939178 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -30,8 +30,6 @@ version = "0.0.0" dependencies = [ "compiler_builtins", "core", - "rand", - "rand_xorshift", ] [[package]] diff --git a/library/alloc/Cargo.toml b/library/alloc/Cargo.toml index 30801664e6587..c7568f67be5ed 100644 --- a/library/alloc/Cargo.toml +++ b/library/alloc/Cargo.toml @@ -8,14 +8,14 @@ autotests = false autobenches = false edition = "2021" +[lib] +test = false +bench = false + [dependencies] core = { path = "../core" } compiler_builtins = { version = "=0.1.146", features = ['rustc-dep-of-std'] } -[dev-dependencies] -rand = { version = "0.9.0", default-features = false, features = ["alloc"] } -rand_xorshift = "0.4.0" - [features] compiler-builtins-mem = ['compiler_builtins/mem'] compiler-builtins-c = ["compiler_builtins/c"] diff --git a/library/alloc/src/alloc.rs b/library/alloc/src/alloc.rs index e686a02f29b0c..8bb616827f66d 100644 --- a/library/alloc/src/alloc.rs +++ b/library/alloc/src/alloc.rs @@ -5,9 +5,7 @@ #[stable(feature = "alloc_module", since = "1.28.0")] #[doc(inline)] pub use core::alloc::*; -#[cfg(not(test))] use core::hint; -#[cfg(not(test))] use core::ptr::{self, NonNull}; unsafe extern "Rust" { @@ -44,14 +42,10 @@ unsafe extern "Rust" { /// accessed through the [free functions in `alloc`](self#functions). #[unstable(feature = "allocator_api", issue = "32838")] #[derive(Copy, Clone, Default, Debug)] -#[cfg(not(test))] // the compiler needs to know when a Box uses the global allocator vs a custom one #[lang = "global_alloc_ty"] pub struct Global; -#[cfg(test)] -pub use std::alloc::Global; - /// Allocates memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::alloc`] method @@ -180,7 +174,6 @@ pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 { } } -#[cfg(not(test))] impl Global { #[inline] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces @@ -246,7 +239,6 @@ impl Global { } #[unstable(feature = "allocator_api", issue = "32838")] -#[cfg(not(test))] unsafe impl Allocator for Global { #[inline] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces @@ -340,7 +332,7 @@ unsafe impl Allocator for Global { } /// The allocator for `Box`. -#[cfg(all(not(no_global_oom_handling), not(test)))] +#[cfg(not(no_global_oom_handling))] #[lang = "exchange_malloc"] #[inline] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces @@ -389,7 +381,7 @@ unsafe extern "Rust" { /// [no_std]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute #[stable(feature = "global_alloc", since = "1.28.0")] #[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")] -#[cfg(all(not(no_global_oom_handling), not(test)))] +#[cfg(not(no_global_oom_handling))] #[cold] #[optimize(size)] pub const fn handle_alloc_error(layout: Layout) -> ! { @@ -413,11 +405,7 @@ pub const fn handle_alloc_error(layout: Layout) -> ! { ct_error(layout) } -// For alloc test `std::alloc::handle_alloc_error` can be used directly. -#[cfg(all(not(no_global_oom_handling), test))] -pub use std::alloc::handle_alloc_error; - -#[cfg(all(not(no_global_oom_handling), not(test)))] +#[cfg(not(no_global_oom_handling))] #[doc(hidden)] #[allow(unused_attributes)] #[unstable(feature = "alloc_internals", issue = "none")] diff --git a/library/alloc/src/borrow.rs b/library/alloc/src/borrow.rs index 17dad3277b95d..07f51b7614ff8 100644 --- a/library/alloc/src/borrow.rs +++ b/library/alloc/src/borrow.rs @@ -32,7 +32,7 @@ where /// implementing the `Clone` trait. But `Clone` works only for going from `&T` /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data /// from any borrow of a given type. -#[cfg_attr(not(test), rustc_diagnostic_item = "ToOwned")] +#[rustc_diagnostic_item = "ToOwned"] #[stable(feature = "rust1", since = "1.0.0")] pub trait ToOwned { /// The resulting type after obtaining ownership. @@ -54,7 +54,7 @@ pub trait ToOwned { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use = "cloning is often expensive and is not expected to have side effects"] - #[cfg_attr(not(test), rustc_diagnostic_item = "to_owned_method")] + #[rustc_diagnostic_item = "to_owned_method"] fn to_owned(&self) -> Self::Owned; /// Uses borrowed data to replace owned data, usually by cloning. @@ -175,7 +175,7 @@ where /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Cow")] +#[rustc_diagnostic_item = "Cow"] pub enum Cow<'a, B: ?Sized + 'a> where B: ToOwned, diff --git a/library/alloc/src/bstr.rs b/library/alloc/src/bstr.rs index 61e61019b508c..338c7ac7f8876 100644 --- a/library/alloc/src/bstr.rs +++ b/library/alloc/src/bstr.rs @@ -12,13 +12,10 @@ use core::ops::{ Deref, DerefMut, DerefPure, Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, }; -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 use core::str::FromStr; use core::{fmt, hash}; -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 use crate::borrow::{Cow, ToOwned}; -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 use crate::boxed::Box; #[cfg(not(no_rc))] use crate::rc::Rc; @@ -181,7 +178,6 @@ impl Default for ByteString { // Omitted due to inference failures // -// #[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 // #[unstable(feature = "bstr", issue = "134915")] // impl<'a, const N: usize> From<&'a [u8; N]> for ByteString { // #[inline] @@ -190,7 +186,6 @@ impl Default for ByteString { // } // } // -// #[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 // #[unstable(feature = "bstr", issue = "134915")] // impl From<[u8; N]> for ByteString { // #[inline] @@ -199,7 +194,6 @@ impl Default for ByteString { // } // } // -// #[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 // #[unstable(feature = "bstr", issue = "134915")] // impl<'a> From<&'a [u8]> for ByteString { // #[inline] @@ -226,7 +220,6 @@ impl From for Vec { // Omitted due to inference failures // -// #[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 // #[unstable(feature = "bstr", issue = "134915")] // impl<'a> From<&'a str> for ByteString { // #[inline] @@ -243,7 +236,6 @@ impl From for Vec { // } // } -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl<'a> From<&'a ByteStr> for ByteString { #[inline] @@ -252,7 +244,6 @@ impl<'a> From<&'a ByteStr> for ByteString { } } -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl<'a> From for Cow<'a, ByteStr> { #[inline] @@ -261,7 +252,6 @@ impl<'a> From for Cow<'a, ByteStr> { } } -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl<'a> From<&'a ByteString> for Cow<'a, ByteStr> { #[inline] @@ -330,7 +320,6 @@ impl FromIterator for ByteString { } } -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl FromStr for ByteString { type Err = core::convert::Infallible; @@ -488,7 +477,6 @@ impl PartialEq for ByteString { macro_rules! impl_partial_eq_ord_cow { ($lhs:ty, $rhs:ty) => { - #[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[allow(unused_lifetimes)] #[unstable(feature = "bstr", issue = "134915")] impl<'a> PartialEq<$rhs> for $lhs { @@ -499,7 +487,6 @@ macro_rules! impl_partial_eq_ord_cow { } } - #[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[allow(unused_lifetimes)] #[unstable(feature = "bstr", issue = "134915")] impl<'a> PartialEq<$lhs> for $rhs { @@ -510,7 +497,6 @@ macro_rules! impl_partial_eq_ord_cow { } } - #[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[allow(unused_lifetimes)] #[unstable(feature = "bstr", issue = "134915")] impl<'a> PartialOrd<$rhs> for $lhs { @@ -521,7 +507,6 @@ macro_rules! impl_partial_eq_ord_cow { } } - #[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[allow(unused_lifetimes)] #[unstable(feature = "bstr", issue = "134915")] impl<'a> PartialOrd<$lhs> for $rhs { @@ -572,7 +557,6 @@ impl PartialOrd for ByteString { } } -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl ToOwned for ByteStr { type Owned = ByteString; @@ -605,7 +589,6 @@ impl<'a> TryFrom<&'a ByteString> for &'a str { // Additional impls for `ByteStr` that require types from `alloc`: -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl Clone for Box { #[inline] @@ -614,7 +597,6 @@ impl Clone for Box { } } -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl<'a> From<&'a ByteStr> for Cow<'a, ByteStr> { #[inline] @@ -623,7 +605,6 @@ impl<'a> From<&'a ByteStr> for Cow<'a, ByteStr> { } } -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl From> for Box { #[inline] @@ -633,7 +614,6 @@ impl From> for Box { } } -#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/135100 #[unstable(feature = "bstr", issue = "134915")] impl From> for Box<[u8]> { #[inline] diff --git a/library/alloc/src/collections/binary_heap/mod.rs b/library/alloc/src/collections/binary_heap/mod.rs index 965fd63a52981..b764b8fa5d977 100644 --- a/library/alloc/src/collections/binary_heap/mod.rs +++ b/library/alloc/src/collections/binary_heap/mod.rs @@ -153,7 +153,9 @@ use core::{fmt, ptr}; use crate::alloc::Global; use crate::collections::TryReserveError; use crate::slice; -use crate::vec::{self, AsVecIntoIter, Vec}; +#[cfg(not(test))] +use crate::vec::AsVecIntoIter; +use crate::vec::{self, Vec}; /// A priority queue implemented with a binary heap. /// @@ -1600,6 +1602,7 @@ unsafe impl InPlaceIterable for IntoIter { const MERGE_BY: Option> = NonZero::new(1); } +#[cfg(not(test))] unsafe impl AsVecIntoIter for IntoIter { type Item = I; diff --git a/library/alloc/src/collections/mod.rs b/library/alloc/src/collections/mod.rs index 020cf4d736510..1414f797e8a45 100644 --- a/library/alloc/src/collections/mod.rs +++ b/library/alloc/src/collections/mod.rs @@ -24,41 +24,54 @@ pub mod btree_map { pub mod btree_set { //! An ordered set based on a B-Tree. #[stable(feature = "rust1", since = "1.0.0")] + #[cfg(not(test))] pub use super::btree::set::*; } +#[cfg(not(test))] use core::fmt::Display; #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] +#[cfg(not(test))] pub use binary_heap::BinaryHeap; #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] +#[cfg(not(test))] pub use btree_map::BTreeMap; #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] +#[cfg(not(test))] pub use btree_set::BTreeSet; #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] +#[cfg(not(test))] pub use linked_list::LinkedList; #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] +#[cfg(not(test))] pub use vec_deque::VecDeque; +#[cfg(not(test))] use crate::alloc::{Layout, LayoutError}; /// The error type for `try_reserve` methods. #[derive(Clone, PartialEq, Eq, Debug)] #[stable(feature = "try_reserve", since = "1.57.0")] +#[cfg(not(test))] pub struct TryReserveError { kind: TryReserveErrorKind, } +#[cfg(test)] +pub use realalloc::collections::TryReserveError; + +#[cfg(not(test))] impl TryReserveError { /// Details about the allocation that caused the error #[inline] @@ -80,6 +93,7 @@ impl TryReserveError { reason = "Uncertain how much info should be exposed", issue = "48043" )] +#[cfg(not(test))] pub enum TryReserveErrorKind { /// Error due to the computed capacity exceeding the collection's maximum /// (usually `isize::MAX` bytes). @@ -103,11 +117,15 @@ pub enum TryReserveErrorKind { }, } +#[cfg(test)] +pub use realalloc::collections::TryReserveErrorKind; + #[unstable( feature = "try_reserve_kind", reason = "Uncertain how much info should be exposed", issue = "48043" )] +#[cfg(not(test))] impl From for TryReserveError { #[inline] fn from(kind: TryReserveErrorKind) -> Self { @@ -116,6 +134,7 @@ impl From for TryReserveError { } #[unstable(feature = "try_reserve_kind", reason = "new API", issue = "48043")] +#[cfg(not(test))] impl From for TryReserveErrorKind { /// Always evaluates to [`TryReserveErrorKind::CapacityOverflow`]. #[inline] @@ -125,6 +144,7 @@ impl From for TryReserveErrorKind { } #[stable(feature = "try_reserve", since = "1.57.0")] +#[cfg(not(test))] impl Display for TryReserveError { fn fmt( &self, @@ -152,4 +172,5 @@ trait SpecExtend { } #[stable(feature = "try_reserve", since = "1.57.0")] +#[cfg(not(test))] impl core::error::Error for TryReserveError {} diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 299c8b8679e3d..f8844e2d3a5cb 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -645,6 +645,7 @@ impl VecDeque { /// initialized rather than only supporting `0..len`. Requires that /// `initialized.start` ≤ `initialized.end` ≤ `capacity`. #[inline] + #[cfg(not(test))] pub(crate) unsafe fn from_contiguous_raw_parts_in( ptr: *mut T, initialized: Range, diff --git a/library/alloc/src/collections/vec_deque/spec_extend.rs b/library/alloc/src/collections/vec_deque/spec_extend.rs index d246385ca8419..7c7072c4c3a1b 100644 --- a/library/alloc/src/collections/vec_deque/spec_extend.rs +++ b/library/alloc/src/collections/vec_deque/spec_extend.rs @@ -3,6 +3,7 @@ use core::slice; use super::VecDeque; use crate::alloc::Allocator; +#[cfg(not(test))] use crate::vec; // Specialization trait used for VecDeque::extend @@ -78,6 +79,7 @@ where } } +#[cfg(not(test))] impl SpecExtend> for VecDeque { #[track_caller] fn spec_extend(&mut self, mut iterator: vec::IntoIter) { diff --git a/library/alloc/src/collections/vec_deque/spec_from_iter.rs b/library/alloc/src/collections/vec_deque/spec_from_iter.rs index 1efe84d6d7d7d..c80a30c2103dd 100644 --- a/library/alloc/src/collections/vec_deque/spec_from_iter.rs +++ b/library/alloc/src/collections/vec_deque/spec_from_iter.rs @@ -19,6 +19,7 @@ where } } +#[cfg(not(test))] impl SpecFromIter> for VecDeque { #[inline] fn spec_from_iter(iterator: crate::vec::IntoIter) -> Self { diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index fd93045a5ac4d..f6743c6571095 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -10,7 +10,6 @@ use core::{fmt, mem, ops, ptr, slice}; use crate::borrow::{Cow, ToOwned}; use crate::boxed::Box; use crate::rc::Rc; -use crate::slice::hack::into_vec; use crate::string::String; #[cfg(target_has_atomic = "ptr")] use crate::sync::Arc; @@ -103,7 +102,7 @@ use crate::vec::Vec; /// of `CString` instances can lead to invalid memory accesses, memory leaks, /// and other memory errors. #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)] -#[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")] +#[rustc_diagnostic_item = "cstring_type"] #[stable(feature = "alloc_c_string", since = "1.64.0")] pub struct CString { // Invariant 1: the slice ends with a zero byte and has a length of at least one. @@ -491,7 +490,7 @@ impl CString { #[must_use = "`self` will be dropped if the result is not used"] #[stable(feature = "cstring_into", since = "1.7.0")] pub fn into_bytes(self) -> Vec { - let mut vec = into_vec(self.into_inner()); + let mut vec = self.into_inner().into_vec(); let _nul = vec.pop(); debug_assert_eq!(_nul, Some(0u8)); vec @@ -512,7 +511,7 @@ impl CString { #[must_use = "`self` will be dropped if the result is not used"] #[stable(feature = "cstring_into", since = "1.7.0")] pub fn into_bytes_with_nul(self) -> Vec { - into_vec(self.into_inner()) + self.into_inner().into_vec() } /// Returns the contents of this `CString` as a slice of bytes. @@ -573,7 +572,7 @@ impl CString { #[inline] #[must_use] #[stable(feature = "as_c_str", since = "1.20.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "cstring_as_c_str")] + #[rustc_diagnostic_item = "cstring_as_c_str"] pub fn as_c_str(&self) -> &CStr { &*self } @@ -755,7 +754,6 @@ impl<'a> From> for CString { } } -#[cfg(not(test))] #[stable(feature = "box_from_c_str", since = "1.17.0")] impl From<&CStr> for Box { /// Converts a `&CStr` into a `Box`, @@ -766,7 +764,6 @@ impl From<&CStr> for Box { } } -#[cfg(not(test))] #[stable(feature = "box_from_mut_slice", since = "1.84.0")] impl From<&mut CStr> for Box { /// Converts a `&mut CStr` into a `Box`, @@ -845,7 +842,6 @@ impl TryFrom for String { } } -#[cfg(not(test))] #[stable(feature = "more_box_slice_clone", since = "1.29.0")] impl Clone for Box { #[inline] @@ -971,7 +967,6 @@ impl Default for Rc { } } -#[cfg(not(test))] #[stable(feature = "default_box_extra", since = "1.17.0")] impl Default for Box { fn default() -> Box { @@ -1080,7 +1075,7 @@ impl ToOwned for CStr { } fn clone_into(&self, target: &mut CString) { - let mut b = into_vec(mem::take(&mut target.inner)); + let mut b = mem::take(&mut target.inner).into_vec(); self.to_bytes_with_nul().clone_into(&mut b); target.inner = b.into_boxed_slice(); } @@ -1113,7 +1108,6 @@ impl AsRef for CString { } } -#[cfg(not(test))] impl CStr { /// Converts a `CStr` into a [Cow]<[str]>. /// diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index b16d40e988e15..2371deffc2615 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -92,7 +92,6 @@ // // Library features: // tidy-alphabetical-start -#![cfg_attr(test, feature(str_as_str))] #![feature(alloc_layout_extra)] #![feature(allocator_api)] #![feature(array_chunks)] @@ -161,13 +160,11 @@ // // Language features: // tidy-alphabetical-start -#![cfg_attr(not(test), feature(coroutine_trait))] -#![cfg_attr(test, feature(panic_update_hook))] -#![cfg_attr(test, feature(test))] #![feature(allocator_internals)] #![feature(allow_internal_unstable)] #![feature(cfg_sanitize)] #![feature(const_precise_live_drops)] +#![feature(coroutine_trait)] #![feature(decl_macro)] #![feature(dropck_eyepatch)] #![feature(fundamental)] @@ -200,15 +197,6 @@ // from other crates, but since this can only appear for lang items, it doesn't seem worth fixing. #![feature(intra_doc_pointers)] -// Allow testing this library -#[cfg(test)] -#[macro_use] -extern crate std; -#[cfg(test)] -extern crate test; -#[cfg(test)] -mod testing; - // Module with internal macros used by other modules (needs to be included before other modules). #[macro_use] mod macros; @@ -216,7 +204,6 @@ mod macros; mod raw_vec; // Heaps provided for low-level allocation strategies - pub mod alloc; // Primitive types using the heaps above @@ -224,13 +211,8 @@ pub mod alloc; // Need to conditionally define the mod from `boxed.rs` to avoid // duplicating the lang-items when building in test cfg; but also need // to allow code to have `use boxed::Box;` declarations. -#[cfg(not(test))] -pub mod boxed; -#[cfg(test)] -mod boxed { - pub(crate) use std::boxed::Box; -} pub mod borrow; +pub mod boxed; #[unstable(feature = "bstr", issue = "134915")] pub mod bstr; pub mod collections; @@ -254,20 +236,3 @@ pub mod __export { pub use core::format_args; pub use core::hint::must_use; } - -#[cfg(test)] -#[allow(dead_code)] // Not used in all configurations -pub(crate) mod test_helpers { - /// Copied from `std::test_helpers::test_rng`, since these tests rely on the - /// seed not being the same for every RNG invocation too. - pub(crate) fn test_rng() -> rand_xorshift::XorShiftRng { - use std::hash::{BuildHasher, Hash, Hasher}; - let mut hasher = std::hash::RandomState::new().build_hasher(); - std::panic::Location::caller().hash(&mut hasher); - let hc64 = hasher.finish(); - let seed_vec = - hc64.to_le_bytes().into_iter().chain(0u8..8).collect::>(); - let seed: [u8; 16] = seed_vec.as_slice().try_into().unwrap(); - rand::SeedableRng::from_seed(seed) - } -} diff --git a/library/alloc/src/macros.rs b/library/alloc/src/macros.rs index c000fd6f4efa7..214192b8c9a9b 100644 --- a/library/alloc/src/macros.rs +++ b/library/alloc/src/macros.rs @@ -34,7 +34,7 @@ /// be mindful of side effects. /// /// [`Vec`]: crate::vec::Vec -#[cfg(all(not(no_global_oom_handling), not(test)))] +#[cfg(not(no_global_oom_handling))] #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "vec_macro"] @@ -55,25 +55,6 @@ macro_rules! vec { ); } -// HACK(japaric): with cfg(test) the inherent `[T]::into_vec` method, which is -// required for this macro definition, is not available. Instead use the -// `slice::into_vec` function which is only available with cfg(test) -// NB see the slice::hack module in slice.rs for more information -#[cfg(all(not(no_global_oom_handling), test))] -#[allow(unused_macro_rules)] -macro_rules! vec { - () => ( - $crate::vec::Vec::new() - ); - ($elem:expr; $n:expr) => ( - $crate::vec::from_elem($elem, $n) - ); - ($($x:expr),*) => ( - $crate::slice::into_vec($crate::boxed::Box::new([$($x),*])) - ); - ($($x:expr,)*) => (vec![$($x),*]) -} - /// Creates a `String` using interpolation of runtime expressions. /// /// The first argument `format!` receives is a format string. This must be a string @@ -120,7 +101,7 @@ macro_rules! vec { #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] #[allow_internal_unstable(hint_must_use, liballoc_internals)] -#[cfg_attr(not(test), rustc_diagnostic_item = "format_macro")] +#[rustc_diagnostic_item = "format_macro"] macro_rules! format { ($($arg:tt)*) => { $crate::__export::must_use({ diff --git a/library/alloc/src/raw_vec/mod.rs b/library/alloc/src/raw_vec/mod.rs index b80d1fc788947..fda4858f9d85d 100644 --- a/library/alloc/src/raw_vec/mod.rs +++ b/library/alloc/src/raw_vec/mod.rs @@ -1,4 +1,5 @@ #![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")] +#![cfg_attr(test, allow(dead_code))] use core::marker::PhantomData; use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties}; diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 2a4d4f264444c..fe0b25f31b923 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -262,14 +262,11 @@ use core::ptr::{self, NonNull, drop_in_place}; #[cfg(not(no_global_oom_handling))] use core::slice::from_raw_parts_mut; use core::{borrow, fmt, hint}; -#[cfg(test)] -use std::boxed::Box; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; use crate::alloc::{AllocError, Allocator, Global, Layout}; use crate::borrow::{Cow, ToOwned}; -#[cfg(not(test))] use crate::boxed::Box; #[cfg(not(no_global_oom_handling))] use crate::string::String; @@ -306,7 +303,7 @@ fn rc_inner_layout_for_value_layout(layout: Layout) -> Layout { /// /// [get_mut]: Rc::get_mut #[doc(search_unbox)] -#[cfg_attr(not(test), rustc_diagnostic_item = "Rc")] +#[rustc_diagnostic_item = "Rc"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_insignificant_dtor] pub struct Rc< @@ -2981,7 +2978,7 @@ impl> ToRcSlice for I { /// /// [`upgrade`]: Weak::upgrade #[stable(feature = "rc_weak", since = "1.4.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "RcWeak")] +#[rustc_diagnostic_item = "RcWeak"] pub struct Weak< T: ?Sized, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global, diff --git a/library/alloc/src/slice.rs b/library/alloc/src/slice.rs index c83b1962eb691..833d703bbd7b9 100644 --- a/library/alloc/src/slice.rs +++ b/library/alloc/src/slice.rs @@ -8,9 +8,6 @@ //! A few functions are provided to create a slice from a value reference //! or from a raw pointer. #![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))] use core::borrow::{Borrow, BorrowMut}; #[cfg(not(no_global_oom_handling))] @@ -63,16 +60,6 @@ pub use core::slice::{range, try_range}; //////////////////////////////////////////////////////////////////////////////// // Basic slice extension methods //////////////////////////////////////////////////////////////////////////////// - -// HACK(japaric) needed for the implementation of `vec!` macro during testing -// N.B., see the `hack` module in this file for more details. -#[cfg(test)] -pub use hack::into_vec; -// HACK(japaric) needed for the implementation of `Vec::clone` during testing -// N.B., see the `hack` module in this file for more details. -#[cfg(test)] -pub use hack::to_vec; - use crate::alloc::Allocator; #[cfg(not(no_global_oom_handling))] use crate::alloc::Global; @@ -81,98 +68,6 @@ use crate::borrow::ToOwned; use crate::boxed::Box; use crate::vec::Vec; -// HACK(japaric): With cfg(test) `impl [T]` is not available, these three -// functions are actually methods that are in `impl [T]` but not in -// `core::slice::SliceExt` - we need to supply these functions for the -// `test_permutations` test -#[allow(unreachable_pub)] // cfg(test) pub above -pub(crate) mod hack { - use core::alloc::Allocator; - - use crate::boxed::Box; - use crate::vec::Vec; - - // We shouldn't add inline attribute to this since this is used in - // `vec!` macro mostly and causes perf regression. See #71204 for - // discussion and perf results. - #[allow(missing_docs)] - pub fn into_vec(b: Box<[T], A>) -> Vec { - unsafe { - let len = b.len(); - let (b, alloc) = Box::into_raw_with_allocator(b); - Vec::from_raw_parts_in(b as *mut T, len, len, alloc) - } - } - - #[cfg(not(no_global_oom_handling))] - #[allow(missing_docs)] - #[inline] - pub fn to_vec(s: &[T], alloc: A) -> Vec { - T::to_vec(s, alloc) - } - - #[cfg(not(no_global_oom_handling))] - pub trait ConvertVec { - fn to_vec(s: &[Self], alloc: A) -> Vec - where - Self: Sized; - } - - #[cfg(not(no_global_oom_handling))] - impl ConvertVec for T { - #[inline] - default fn to_vec(s: &[Self], alloc: A) -> Vec { - struct DropGuard<'a, T, A: Allocator> { - vec: &'a mut Vec, - num_init: usize, - } - impl<'a, T, A: Allocator> Drop for DropGuard<'a, T, A> { - #[inline] - fn drop(&mut self) { - // SAFETY: - // items were marked initialized in the loop below - unsafe { - self.vec.set_len(self.num_init); - } - } - } - let mut vec = Vec::with_capacity_in(s.len(), alloc); - let mut guard = DropGuard { vec: &mut vec, num_init: 0 }; - let slots = guard.vec.spare_capacity_mut(); - // .take(slots.len()) is necessary for LLVM to remove bounds checks - // and has better codegen than zip. - for (i, b) in s.iter().enumerate().take(slots.len()) { - guard.num_init = i; - slots[i].write(b.clone()); - } - core::mem::forget(guard); - // SAFETY: - // the vec was allocated and initialized above to at least this length. - unsafe { - vec.set_len(s.len()); - } - vec - } - } - - #[cfg(not(no_global_oom_handling))] - impl ConvertVec for T { - #[inline] - fn to_vec(s: &[Self], alloc: A) -> Vec { - let mut v = Vec::with_capacity_in(s.len(), alloc); - // SAFETY: - // allocated above with the capacity of `s`, and initialize to `s.len()` in - // ptr::copy_to_non_overlapping below. - unsafe { - s.as_ptr().copy_to_nonoverlapping(v.as_mut_ptr(), s.len()); - v.set_len(s.len()); - } - v - } - } -} - -#[cfg(not(test))] impl [T] { /// Sorts the slice, preserving initial order of equal elements. /// @@ -501,8 +396,64 @@ impl [T] { where T: Clone, { - // N.B., see the `hack` module in this file for more details. - hack::to_vec(self, alloc) + return T::to_vec(self, alloc); + + trait ConvertVec { + fn to_vec(s: &[Self], alloc: A) -> Vec + where + Self: Sized; + } + + impl ConvertVec for T { + #[inline] + default fn to_vec(s: &[Self], alloc: A) -> Vec { + struct DropGuard<'a, T, A: Allocator> { + vec: &'a mut Vec, + num_init: usize, + } + impl<'a, T, A: Allocator> Drop for DropGuard<'a, T, A> { + #[inline] + fn drop(&mut self) { + // SAFETY: + // items were marked initialized in the loop below + unsafe { + self.vec.set_len(self.num_init); + } + } + } + let mut vec = Vec::with_capacity_in(s.len(), alloc); + let mut guard = DropGuard { vec: &mut vec, num_init: 0 }; + let slots = guard.vec.spare_capacity_mut(); + // .take(slots.len()) is necessary for LLVM to remove bounds checks + // and has better codegen than zip. + for (i, b) in s.iter().enumerate().take(slots.len()) { + guard.num_init = i; + slots[i].write(b.clone()); + } + core::mem::forget(guard); + // SAFETY: + // the vec was allocated and initialized above to at least this length. + unsafe { + vec.set_len(s.len()); + } + vec + } + } + + impl ConvertVec for T { + #[inline] + fn to_vec(s: &[Self], alloc: A) -> Vec { + let mut v = Vec::with_capacity_in(s.len(), alloc); + // SAFETY: + // allocated above with the capacity of `s`, and initialize to `s.len()` in + // ptr::copy_to_non_overlapping below. + unsafe { + s.as_ptr().copy_to_nonoverlapping(v.as_mut_ptr(), s.len()); + v.set_len(s.len()); + } + v + } + } } /// Converts `self` into a vector without clones or allocation. @@ -522,10 +473,13 @@ impl [T] { #[rustc_allow_incoherent_impl] #[stable(feature = "rust1", since = "1.0.0")] #[inline] - #[cfg_attr(not(test), rustc_diagnostic_item = "slice_into_vec")] + #[rustc_diagnostic_item = "slice_into_vec"] pub fn into_vec(self: Box) -> Vec { - // N.B., see the `hack` module in this file for more details. - hack::into_vec(self) + unsafe { + let len = self.len(); + let (b, alloc) = Box::into_raw_with_allocator(self); + Vec::from_raw_parts_in(b as *mut T, len, len, alloc) + } } /// Creates a vector by copying a slice `n` times. @@ -666,7 +620,6 @@ impl [T] { } } -#[cfg(not(test))] impl [u8] { /// Returns a vector containing a copy of this slice where each byte /// is mapped to its ASCII upper case equivalent. @@ -883,14 +836,9 @@ impl SpecCloneIntoVec for [T] { #[stable(feature = "rust1", since = "1.0.0")] impl ToOwned for [T] { type Owned = Vec; - #[cfg(not(test))] - fn to_owned(&self) -> Vec { - self.to_vec() - } - #[cfg(test)] fn to_owned(&self) -> Vec { - hack::to_vec(self, Global) + self.to_vec() } fn clone_into(&self, target: &mut Vec) { diff --git a/library/alloc/src/str.rs b/library/alloc/src/str.rs index 6fee8d3fe3346..0664f2c3cf2c1 100644 --- a/library/alloc/src/str.rs +++ b/library/alloc/src/str.rs @@ -219,7 +219,6 @@ impl ToOwned for str { } /// Methods for string slices. -#[cfg(not(test))] impl str { /// Converts a `Box` into a `Box<[u8]>` without copying or allocating. /// @@ -631,7 +630,6 @@ pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box { #[unstable(feature = "str_internals", issue = "none")] #[doc(hidden)] #[inline] -#[cfg(not(test))] #[cfg(not(no_global_oom_handling))] pub fn convert_while_ascii(s: &str, convert: fn(&u8) -> u8) -> (String, &str) { // Process the input in chunks of 16 bytes to enable auto-vectorization. @@ -704,7 +702,6 @@ pub fn convert_while_ascii(s: &str, convert: fn(&u8) -> u8) -> (String, &str) { } } #[inline] -#[cfg(not(test))] #[cfg(not(no_global_oom_handling))] #[allow(dead_code)] /// Faster implementation of string replacement for ASCII to ASCII cases. diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 9446afd4b24b0..9856f918c4f3d 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -358,7 +358,7 @@ use crate::vec::{self, Vec}; /// [`as_str()`]: String::as_str #[derive(PartialEq, PartialOrd, Eq, Ord)] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), lang = "String")] +#[lang = "String"] pub struct String { vec: Vec, } @@ -440,7 +440,7 @@ impl String { /// ``` #[inline] #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "string_new")] + #[rustc_diagnostic_item = "string_new"] #[stable(feature = "rust1", since = "1.0.0")] #[must_use] pub const fn new() -> String { @@ -503,17 +503,6 @@ impl String { Ok(String { vec: Vec::try_with_capacity(capacity)? }) } - // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is - // required for this method definition, is not available. Since we don't - // require this method for testing purposes, I'll just stub it - // NB see the slice::hack module in slice.rs for more information - #[inline] - #[cfg(test)] - #[allow(missing_docs)] - pub fn from_str(_: &str) -> String { - panic!("not available with cfg(test)"); - } - /// Converts a vector of bytes to a `String`. /// /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes @@ -572,7 +561,7 @@ impl String { /// [`into_bytes`]: String::into_bytes #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "string_from_utf8")] + #[rustc_diagnostic_item = "string_from_utf8"] pub fn from_utf8(vec: Vec) -> Result { match str::from_utf8(&vec) { Ok(..) => Ok(String { vec }), @@ -1076,7 +1065,7 @@ impl String { #[inline] #[must_use] #[stable(feature = "string_as_str", since = "1.7.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "string_as_str")] + #[rustc_diagnostic_item = "string_as_str"] #[rustc_const_unstable(feature = "const_vec_string_slice", issue = "129041")] pub const fn as_str(&self) -> &str { // SAFETY: String contents are stipulated to be valid UTF-8, invalid contents are an error @@ -1099,7 +1088,7 @@ impl String { #[inline] #[must_use] #[stable(feature = "string_as_str", since = "1.7.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "string_as_mut_str")] + #[rustc_diagnostic_item = "string_as_mut_str"] #[rustc_const_unstable(feature = "const_vec_string_slice", issue = "129041")] pub const fn as_mut_str(&mut self) -> &mut str { // SAFETY: String contents are stipulated to be valid UTF-8, invalid contents are an error @@ -1122,7 +1111,7 @@ impl String { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_confusables("append", "push")] - #[cfg_attr(not(test), rustc_diagnostic_item = "string_push_str")] + #[rustc_diagnostic_item = "string_push_str"] pub fn push_str(&mut self, string: &str) { self.vec.extend_from_slice(string.as_bytes()) } @@ -1761,7 +1750,7 @@ impl String { #[cfg(not(no_global_oom_handling))] #[inline] #[stable(feature = "insert_str", since = "1.16.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "string_insert_str")] + #[rustc_diagnostic_item = "string_insert_str"] pub fn insert_str(&mut self, idx: usize, string: &str) { assert!(self.is_char_boundary(idx)); @@ -2730,7 +2719,7 @@ impl FromStr for String { /// implementation for free. /// /// [`Display`]: fmt::Display -#[cfg_attr(not(test), rustc_diagnostic_item = "ToString")] +#[rustc_diagnostic_item = "ToString"] #[stable(feature = "rust1", since = "1.0.0")] pub trait ToString { /// Converts the given value to a `String`. @@ -2745,7 +2734,7 @@ pub trait ToString { /// ``` #[rustc_conversion_suggestion] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "to_string_method")] + #[rustc_diagnostic_item = "to_string_method"] fn to_string(&self) -> String; } @@ -2985,7 +2974,6 @@ impl From<&String> for String { } // note: test pulls in std, which causes errors here -#[cfg(not(test))] #[stable(feature = "string_from_box", since = "1.18.0")] impl From> for String { /// Converts the given boxed `str` slice to a [`String`]. diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index dba1449347ac0..ac88ac1034d44 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -234,7 +234,7 @@ macro_rules! acquire { /// /// [rc_examples]: crate::rc#examples #[doc(search_unbox)] -#[cfg_attr(not(test), rustc_diagnostic_item = "Arc")] +#[rustc_diagnostic_item = "Arc"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_insignificant_dtor] pub struct Arc< @@ -311,7 +311,7 @@ impl Arc { /// /// [`upgrade`]: Weak::upgrade #[stable(feature = "arc_weak", since = "1.4.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "ArcWeak")] +#[rustc_diagnostic_item = "ArcWeak"] pub struct Weak< T: ?Sized, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global, diff --git a/library/alloc/src/vec/into_iter.rs b/library/alloc/src/vec/into_iter.rs index 9a6745fdbc0a3..80da2f9abe19d 100644 --- a/library/alloc/src/vec/into_iter.rs +++ b/library/alloc/src/vec/into_iter.rs @@ -472,14 +472,9 @@ where #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_into_iter_clone", since = "1.8.0")] impl Clone for IntoIter { - #[cfg(not(test))] fn clone(&self) -> Self { self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter() } - #[cfg(test)] - fn clone(&self) -> Self { - crate::slice::to_vec(self.as_slice(), self.alloc.deref().clone()).into_iter() - } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 7d02a15ed7a51..58a6b538acc9b 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -392,7 +392,7 @@ mod spec_extend; /// [`MaybeUninit`]: core::mem::MaybeUninit /// [owned slice]: Box #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Vec")] +#[rustc_diagnostic_item = "Vec"] #[rustc_insignificant_dtor] pub struct Vec { buf: RawVec, @@ -416,7 +416,7 @@ impl Vec { /// ``` #[inline] #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "vec_new")] + #[rustc_diagnostic_item = "vec_new"] #[stable(feature = "rust1", since = "1.0.0")] #[must_use] pub const fn new() -> Self { @@ -477,7 +477,7 @@ impl Vec { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[must_use] - #[cfg_attr(not(test), rustc_diagnostic_item = "vec_with_capacity")] + #[rustc_diagnostic_item = "vec_with_capacity"] #[track_caller] pub fn with_capacity(capacity: usize) -> Self { Self::with_capacity_in(capacity, Global) @@ -1267,7 +1267,7 @@ impl Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[track_caller] - #[cfg_attr(not(test), rustc_diagnostic_item = "vec_reserve")] + #[rustc_diagnostic_item = "vec_reserve"] pub fn reserve(&mut self, additional: usize) { self.buf.reserve(self.len, additional); } @@ -1556,7 +1556,7 @@ impl Vec { /// ``` #[inline] #[stable(feature = "vec_as_slice", since = "1.7.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "vec_as_slice")] + #[rustc_diagnostic_item = "vec_as_slice"] #[rustc_const_unstable(feature = "const_vec_string_slice", issue = "129041")] pub const fn as_slice(&self) -> &[T] { // SAFETY: `slice::from_raw_parts` requires pointee is a contiguous, aligned buffer of size @@ -1588,7 +1588,7 @@ impl Vec { /// ``` #[inline] #[stable(feature = "vec_as_slice", since = "1.7.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "vec_as_mut_slice")] + #[rustc_diagnostic_item = "vec_as_mut_slice"] #[rustc_const_unstable(feature = "const_vec_string_slice", issue = "129041")] pub const fn as_mut_slice(&mut self) -> &mut [T] { // SAFETY: `slice::from_raw_parts_mut` requires pointee is a contiguous, aligned buffer of @@ -2499,7 +2499,7 @@ impl Vec { /// Takes *O*(1) time. #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "vec_pop")] + #[rustc_diagnostic_item = "vec_pop"] pub fn pop(&mut self) -> Option { if self.len == 0 { None @@ -2700,7 +2700,7 @@ impl Vec { /// assert!(!v.is_empty()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "vec_is_empty")] + #[rustc_diagnostic_item = "vec_is_empty"] #[rustc_const_unstable(feature = "const_vec_string_slice", issue = "129041")] pub const fn is_empty(&self) -> bool { self.len() == 0 @@ -3181,7 +3181,7 @@ impl Vec { #[doc(hidden)] #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "vec_from_elem")] +#[rustc_diagnostic_item = "vec_from_elem"] #[track_caller] pub fn from_elem(elem: T, n: usize) -> Vec { ::from_elem(elem, n, Global) @@ -3281,23 +3281,12 @@ unsafe impl ops::DerefPure for Vec {} #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl Clone for Vec { - #[cfg(not(test))] #[track_caller] fn clone(&self) -> Self { let alloc = self.allocator().clone(); <[T]>::to_vec_in(&**self, alloc) } - // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is - // required for this method definition, is not available. Instead use the - // `slice::to_vec` function which is only available with cfg(test) - // NB see the slice::hack module in slice.rs for more information - #[cfg(test)] - fn clone(&self) -> Self { - let alloc = self.allocator().clone(); - crate::slice::to_vec(&**self, alloc) - } - /// Overwrites the contents of `self` with a clone of the contents of `source`. /// /// This method is preferred over simply assigning `source.clone()` to `self`, @@ -3844,15 +3833,10 @@ impl From<&[T]> for Vec { /// ``` /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]); /// ``` - #[cfg(not(test))] #[track_caller] fn from(s: &[T]) -> Vec { s.to_vec() } - #[cfg(test)] - fn from(s: &[T]) -> Vec { - crate::slice::to_vec(s, Global) - } } #[cfg(not(no_global_oom_handling))] @@ -3865,15 +3849,10 @@ impl From<&mut [T]> for Vec { /// ``` /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]); /// ``` - #[cfg(not(test))] #[track_caller] fn from(s: &mut [T]) -> Vec { s.to_vec() } - #[cfg(test)] - fn from(s: &mut [T]) -> Vec { - crate::slice::to_vec(s, Global) - } } #[cfg(not(no_global_oom_handling))] @@ -3918,16 +3897,10 @@ impl From<[T; N]> for Vec { /// ``` /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]); /// ``` - #[cfg(not(test))] #[track_caller] fn from(s: [T; N]) -> Vec { <[T]>::into_vec(Box::new(s)) } - - #[cfg(test)] - fn from(s: [T; N]) -> Vec { - crate::slice::into_vec(Box::new(s)) - } } #[stable(feature = "vec_from_cow_slice", since = "1.14.0")] @@ -3956,7 +3929,6 @@ where } // note: test pulls in std, which causes errors here -#[cfg(not(test))] #[stable(feature = "vec_from_box", since = "1.18.0")] impl From> for Vec { /// Converts a boxed slice into a vector by transferring ownership of @@ -3975,7 +3947,6 @@ impl From> for Vec { // note: test pulls in std, which causes errors here #[cfg(not(no_global_oom_handling))] -#[cfg(not(test))] #[stable(feature = "box_from_vec", since = "1.20.0")] impl From> for Box<[T], A> { /// Converts a vector into a boxed slice. diff --git a/library/alloctests/Cargo.toml b/library/alloctests/Cargo.toml index 93c7c786e881b..306375f5f01cc 100644 --- a/library/alloctests/Cargo.toml +++ b/library/alloctests/Cargo.toml @@ -10,12 +10,13 @@ edition = "2021" [lib] path = "lib.rs" -test = false -bench = false +test = true +bench = true +doc = false [dev-dependencies] -rand = { version = "0.8.5", default-features = false, features = ["alloc"] } -rand_xorshift = "0.3.0" +rand = { version = "0.9.0", default-features = false, features = ["alloc"] } +rand_xorshift = "0.4.0" [[test]] name = "alloctests" diff --git a/library/alloctests/lib.rs b/library/alloctests/lib.rs index b49208cd4eb3a..0b5aa2c575d9a 100644 --- a/library/alloctests/lib.rs +++ b/library/alloctests/lib.rs @@ -1 +1,90 @@ -// Intentionally left empty. +#![cfg(test)] +#![allow(unused_attributes)] +#![unstable(feature = "alloctests", issue = "none")] +#![no_std] +// Lints: +#![deny(unsafe_op_in_unsafe_fn)] +#![warn(deprecated_in_future)] +#![warn(missing_debug_implementations)] +#![allow(explicit_outlives_requirements)] +#![allow(internal_features)] +#![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] +#![deny(ffi_unwind_calls)] +// +// Library features: +// tidy-alphabetical-start +#![feature(alloc_layout_extra)] +#![feature(allocator_api)] +#![feature(array_into_iter_constructors)] +#![feature(assert_matches)] +#![feature(core_intrinsics)] +#![feature(exact_size_is_empty)] +#![feature(extend_one)] +#![feature(extend_one_unchecked)] +#![feature(hasher_prefixfree_extras)] +#![feature(inplace_iteration)] +#![feature(iter_advance_by)] +#![feature(iter_next_chunk)] +#![feature(maybe_uninit_slice)] +#![feature(maybe_uninit_uninit_array_transpose)] +#![feature(ptr_internals)] +#![feature(sized_type_properties)] +#![feature(slice_iter_mut_as_mut_slice)] +#![feature(slice_ptr_get)] +#![feature(slice_range)] +#![feature(std_internals)] +#![feature(temporary_niche_types)] +#![feature(trusted_fused)] +#![feature(trusted_len)] +#![feature(trusted_random_access)] +#![feature(try_reserve_kind)] +#![feature(try_trait_v2)] +// tidy-alphabetical-end +// +// Language features: +// tidy-alphabetical-start +#![feature(cfg_sanitize)] +#![feature(dropck_eyepatch)] +#![feature(lang_items)] +#![feature(min_specialization)] +#![feature(negative_impls)] +#![feature(never_type)] +#![feature(optimize_attribute)] +#![feature(rustc_allow_const_fn_unstable)] +#![feature(rustc_attrs)] +#![feature(staged_api)] +#![feature(test)] +#![rustc_preserve_ub_checks] +// tidy-alphabetical-end + +// Allow testing this library +extern crate alloc as realalloc; +#[macro_use] +extern crate std; +#[cfg(test)] +extern crate test; +mod testing; +use realalloc::*; + +#[path = "../alloc/src/collections/mod.rs"] +mod collections; + +#[path = "../alloc/src/raw_vec/mod.rs"] +mod raw_vec; + +#[allow(dead_code)] // Not used in all configurations +pub(crate) mod test_helpers { + /// Copied from `std::test_helpers::test_rng`, since these tests rely on the + /// seed not being the same for every RNG invocation too. + pub(crate) fn test_rng() -> rand_xorshift::XorShiftRng { + use std::hash::{BuildHasher, Hash, Hasher}; + let mut hasher = std::hash::RandomState::new().build_hasher(); + std::panic::Location::caller().hash(&mut hasher); + let hc64 = hasher.finish(); + let seed_vec = + hc64.to_le_bytes().into_iter().chain(0u8..8).collect::>(); + let seed: [u8; 16] = seed_vec.as_slice().try_into().unwrap(); + rand::SeedableRng::from_seed(seed) + } +} diff --git a/library/alloc/src/testing/crash_test.rs b/library/alloctests/testing/crash_test.rs similarity index 100% rename from library/alloc/src/testing/crash_test.rs rename to library/alloctests/testing/crash_test.rs diff --git a/library/alloc/src/testing/mod.rs b/library/alloctests/testing/mod.rs similarity index 100% rename from library/alloc/src/testing/mod.rs rename to library/alloctests/testing/mod.rs diff --git a/library/alloc/src/testing/ord_chaos.rs b/library/alloctests/testing/ord_chaos.rs similarity index 100% rename from library/alloc/src/testing/ord_chaos.rs rename to library/alloctests/testing/ord_chaos.rs diff --git a/library/alloc/src/testing/rng.rs b/library/alloctests/testing/rng.rs similarity index 100% rename from library/alloc/src/testing/rng.rs rename to library/alloctests/testing/rng.rs From 44c07fffc5d44ac8576b5b9da32cacb16414f1c3 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 13 Feb 2025 15:38:07 +0000 Subject: [PATCH 07/20] Add comments --- library/alloc/src/collections/mod.rs | 3 +++ library/alloc/src/raw_vec/mod.rs | 3 +++ library/alloctests/lib.rs | 3 +++ 3 files changed, 9 insertions(+) diff --git a/library/alloc/src/collections/mod.rs b/library/alloc/src/collections/mod.rs index 1414f797e8a45..fac4d1a65abcb 100644 --- a/library/alloc/src/collections/mod.rs +++ b/library/alloc/src/collections/mod.rs @@ -1,5 +1,8 @@ //! Collection types. +// Note: This module is also included in the alloctests crate using #[path] to +// run the tests. See the comment there for an explanation why this is the case. + #![stable(feature = "rust1", since = "1.0.0")] #[cfg(not(no_global_oom_handling))] diff --git a/library/alloc/src/raw_vec/mod.rs b/library/alloc/src/raw_vec/mod.rs index fda4858f9d85d..9128057512b3c 100644 --- a/library/alloc/src/raw_vec/mod.rs +++ b/library/alloc/src/raw_vec/mod.rs @@ -1,6 +1,9 @@ #![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")] #![cfg_attr(test, allow(dead_code))] +// Note: This module is also included in the alloctests crate using #[path] to +// run the tests. See the comment there for an explanation why this is the case. + use core::marker::PhantomData; use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties}; use core::ptr::{self, NonNull, Unique}; diff --git a/library/alloctests/lib.rs b/library/alloctests/lib.rs index 0b5aa2c575d9a..6ce8a6d9ca174 100644 --- a/library/alloctests/lib.rs +++ b/library/alloctests/lib.rs @@ -67,6 +67,9 @@ extern crate test; mod testing; use realalloc::*; +// We are directly including collections and raw_vec here as both use non-public +// methods and fields in tests and as such need to have the types to test in the +// same crate as the tests themself. #[path = "../alloc/src/collections/mod.rs"] mod collections; From 9c88f1007db4620918205ded7808804e220f7191 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 19 Feb 2025 15:58:08 +0000 Subject: [PATCH 08/20] Fix miri by ensuring that core and alloc don't get tested directly cargo test -p core -p alloc overrides the test=false in Cargo.toml so we have to avoid passing -p core and -p alloc to cargo test. --- src/bootstrap/src/core/build_steps/test.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 43e26672fbc33..e581a3708f506 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -2783,10 +2783,28 @@ impl Step for Crate { _ => panic!("can only test libraries"), }; + let crates = self + .crates + .iter() + .cloned() + .map(|crate_| { + // The core and alloc crates can't directly be tested. We could + // silently ignore them, but replacing them with their test crate + // is less confusing for users. + if crate_ == "core" { + "coretests".to_owned() + } else if crate_ == "alloc" { + "alloctests".to_owned() + } else { + crate_ + } + }) + .collect::>(); + run_cargo_test( cargo, &[], - &self.crates, + &crates, &self.crates[0], &*crate_description(&self.crates), target, From 2fc920549be505e419ed4458695fb088c30ba3d7 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 21 Feb 2025 14:59:53 +0000 Subject: [PATCH 09/20] Always allow reusing cratenum in CrateLoader::load The only case where can_reuse_cratenum could have been false in the past are rustc plugins, support for which has been removed over a year ago now. Nowadays the only case where locator.tuple is not target_triple is when loading a proc macro, in which case we also set can_reuse_cratenum to true. As such it is always true and we can remove some dead code. --- compiler/rustc_metadata/src/creader.rs | 30 ++++++++------------------ 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index c2dda21bb72e6..4351d340013c3 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -762,29 +762,17 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // against a hash, we could load a crate which has the same hash // as an already loaded crate. If this is the case prevent // duplicates by just using the first crate. - // - // Note that we only do this for target triple crates, though, as we - // don't want to match a host crate against an equivalent target one - // already loaded. let root = library.metadata.get_root(); - // FIXME: why is this condition necessary? It was adding in #33625 but I - // don't know why and the original author doesn't remember ... - let can_reuse_cratenum = - locator.tuple == self.sess.opts.target_triple || locator.is_proc_macro; - Ok(Some(if can_reuse_cratenum { - let mut result = LoadResult::Loaded(library); - for (cnum, data) in self.cstore.iter_crate_data() { - if data.name() == root.name() && root.hash() == data.hash() { - assert!(locator.hash.is_none()); - info!("load success, going to previous cnum: {}", cnum); - result = LoadResult::Previous(cnum); - break; - } + let mut result = LoadResult::Loaded(library); + for (cnum, data) in self.cstore.iter_crate_data() { + if data.name() == root.name() && root.hash() == data.hash() { + assert!(locator.hash.is_none()); + info!("load success, going to previous cnum: {}", cnum); + result = LoadResult::Previous(cnum); + break; } - result - } else { - LoadResult::Loaded(library) - })) + } + Ok(Some(result)) } /// Go through the crate metadata and load any crates that it references. From 6ed53a624b41d0973ffe4efc1fe4ee642cdc166e Mon Sep 17 00:00:00 2001 From: Paul Mabileau Date: Fri, 21 Feb 2025 16:02:40 +0100 Subject: [PATCH 10/20] Fix(lib/fs/tests): Disable rename POSIX semantics FS tests under Windows 7 Would otherwise fail there. The Windows7-specific parts were left pretty much untouched by the changes introduced by 51df98ddb094b39b2e17d24f887cd66c52560ef6, so it is expected that these tests fail under Windows 7 as they were probably written to run under Windows 10+ only. Signed-off-by: Paul Mabileau --- library/std/src/fs/tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs index 1a266f71965d9..c7833c7dc7133 100644 --- a/library/std/src/fs/tests.rs +++ b/library/std/src/fs/tests.rs @@ -1914,8 +1914,11 @@ fn test_hidden_file_truncation() { assert_eq!(metadata.len(), 0); } +// See https://github.com/rust-lang/rust/pull/131072 for more details about why +// these two tests are disabled under Windows 7 here. #[cfg(windows)] #[test] +#[cfg_attr(target_vendor = "win7", ignore = "Unsupported under Windows 7.")] fn test_rename_file_over_open_file() { // Make sure that std::fs::rename works if the target file is already opened with FILE_SHARE_DELETE. See #123985. let tmpdir = tmpdir(); @@ -1940,6 +1943,7 @@ fn test_rename_file_over_open_file() { #[test] #[cfg(windows)] +#[cfg_attr(target_vendor = "win7", ignore = "Unsupported under Windows 7.")] fn test_rename_directory_to_non_empty_directory() { // Renaming a directory over a non-empty existing directory should fail on Windows. let tmpdir: TempDir = tmpdir(); From ec88bc2e00985e99923ff3de966a947daa63c567 Mon Sep 17 00:00:00 2001 From: Nikita Revenco <154856872+NikitaRevenco@users.noreply.github.com> Date: Fri, 21 Feb 2025 01:00:19 +0000 Subject: [PATCH 11/20] =?UTF-8?q?fix:=20naming=20convention=20"ferris"=20s?= =?UTF-8?q?uggestion=20for=20idents=20named=20=F0=9F=A6=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit test: add tests for correct ferris capitalization fix: add "struct" style: use rustfmt style: remove newline fix: _ _ _ _ _ --- compiler/rustc_interface/src/errors.rs | 3 +- compiler/rustc_interface/src/passes.rs | 35 +++++++++++++++++++++++- tests/ui/parser/ferris-static-mut.rs | 3 ++ tests/ui/parser/ferris-static-mut.stderr | 8 ++++++ tests/ui/parser/ferris-struct.rs | 3 ++ tests/ui/parser/ferris-struct.stderr | 8 ++++++ 6 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 tests/ui/parser/ferris-static-mut.rs create mode 100644 tests/ui/parser/ferris-static-mut.stderr create mode 100644 tests/ui/parser/ferris-struct.rs create mode 100644 tests/ui/parser/ferris-struct.stderr diff --git a/compiler/rustc_interface/src/errors.rs b/compiler/rustc_interface/src/errors.rs index ca4e556dcdb80..eed729a1777fc 100644 --- a/compiler/rustc_interface/src/errors.rs +++ b/compiler/rustc_interface/src/errors.rs @@ -24,8 +24,9 @@ pub(crate) struct CrateNameInvalid<'a> { pub struct FerrisIdentifier { #[primary_span] pub spans: Vec, - #[suggestion(code = "ferris", applicability = "maybe-incorrect")] + #[suggestion(code = "{ferris_fix}", applicability = "maybe-incorrect")] pub first_span: Span, + pub ferris_fix: &'static str, } #[derive(Diagnostic)] diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index d70d9d344b94c..c4b0e244c56b1 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -301,8 +301,41 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { for (ident, mut spans) in identifiers.drain(..) { spans.sort(); if ident == sym::ferris { + enum FerrisFix { + SnakeCase, + ScreamingSnakeCase, + PascalCase, + } + + impl FerrisFix { + const fn as_str(self) -> &'static str { + match self { + FerrisFix::SnakeCase => "ferris", + FerrisFix::ScreamingSnakeCase => "FERRIS", + FerrisFix::PascalCase => "Ferris", + } + } + } + let first_span = spans[0]; - sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span }); + let prev_source = sess.psess.source_map().span_to_prev_source(first_span); + let ferris_fix = prev_source + .map_or(FerrisFix::SnakeCase, |source| { + let mut source_before_ferris = source.trim_end().split_whitespace().rev(); + match source_before_ferris.next() { + Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => { + FerrisFix::PascalCase + } + Some("const" | "static") => FerrisFix::ScreamingSnakeCase, + Some("mut") if source_before_ferris.next() == Some("static") => { + FerrisFix::ScreamingSnakeCase + } + _ => FerrisFix::SnakeCase, + } + }) + .as_str(); + + sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix }); } else { sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident }); } diff --git a/tests/ui/parser/ferris-static-mut.rs b/tests/ui/parser/ferris-static-mut.rs new file mode 100644 index 0000000000000..67186982691e0 --- /dev/null +++ b/tests/ui/parser/ferris-static-mut.rs @@ -0,0 +1,3 @@ +static mut 🦀: &str = "ferris!";//~ ERROR Ferris cannot be used as an identifier + +fn main() {} diff --git a/tests/ui/parser/ferris-static-mut.stderr b/tests/ui/parser/ferris-static-mut.stderr new file mode 100644 index 0000000000000..6af85bbaf7dad --- /dev/null +++ b/tests/ui/parser/ferris-static-mut.stderr @@ -0,0 +1,8 @@ +error: Ferris cannot be used as an identifier + --> $DIR/ferris-static-mut.rs:1:12 + | +LL | static mut 🦀: &str = "ferris!"; + | ^^ help: try using their name instead: `FERRIS` + +error: aborting due to 1 previous error + diff --git a/tests/ui/parser/ferris-struct.rs b/tests/ui/parser/ferris-struct.rs new file mode 100644 index 0000000000000..581957fa7757e --- /dev/null +++ b/tests/ui/parser/ferris-struct.rs @@ -0,0 +1,3 @@ +struct 🦀 {}//~ ERROR Ferris cannot be used as an identifier + +fn main() {} diff --git a/tests/ui/parser/ferris-struct.stderr b/tests/ui/parser/ferris-struct.stderr new file mode 100644 index 0000000000000..34fe28c62975c --- /dev/null +++ b/tests/ui/parser/ferris-struct.stderr @@ -0,0 +1,8 @@ +error: Ferris cannot be used as an identifier + --> $DIR/ferris-struct.rs:1:8 + | +LL | struct 🦀 {} + | ^^ help: try using their name instead: `Ferris` + +error: aborting due to 1 previous error + From 76d341fa09c423e601e2c47f8e4d165fcb7c21aa Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 20 Feb 2025 18:37:58 +0000 Subject: [PATCH 12/20] Upgrade the compiler to edition 2024 --- compiler/rustc/Cargo.toml | 2 +- compiler/rustc_abi/Cargo.toml | 2 +- compiler/rustc_arena/Cargo.toml | 2 +- compiler/rustc_ast/Cargo.toml | 2 +- compiler/rustc_ast_ir/Cargo.toml | 2 +- compiler/rustc_ast_lowering/Cargo.toml | 2 +- compiler/rustc_ast_passes/Cargo.toml | 2 +- compiler/rustc_ast_pretty/Cargo.toml | 2 +- compiler/rustc_attr_data_structures/Cargo.toml | 2 +- compiler/rustc_attr_parsing/Cargo.toml | 2 +- compiler/rustc_baked_icu_data/Cargo.toml | 2 +- compiler/rustc_borrowck/Cargo.toml | 2 +- compiler/rustc_builtin_macros/Cargo.toml | 2 +- compiler/rustc_codegen_llvm/Cargo.toml | 2 +- compiler/rustc_codegen_ssa/Cargo.toml | 2 +- compiler/rustc_const_eval/Cargo.toml | 2 +- compiler/rustc_data_structures/Cargo.toml | 2 +- compiler/rustc_driver/Cargo.toml | 2 +- compiler/rustc_driver_impl/Cargo.toml | 2 +- compiler/rustc_error_codes/Cargo.toml | 2 +- compiler/rustc_error_messages/Cargo.toml | 2 +- compiler/rustc_errors/Cargo.toml | 2 +- compiler/rustc_expand/Cargo.toml | 2 +- compiler/rustc_feature/Cargo.toml | 2 +- compiler/rustc_fluent_macro/Cargo.toml | 2 +- compiler/rustc_fs_util/Cargo.toml | 2 +- compiler/rustc_graphviz/Cargo.toml | 2 +- compiler/rustc_hashes/Cargo.toml | 2 +- compiler/rustc_hir/Cargo.toml | 2 +- compiler/rustc_hir_analysis/Cargo.toml | 2 +- compiler/rustc_hir_pretty/Cargo.toml | 2 +- compiler/rustc_hir_typeck/Cargo.toml | 2 +- compiler/rustc_incremental/Cargo.toml | 2 +- compiler/rustc_index/Cargo.toml | 2 +- compiler/rustc_index_macros/Cargo.toml | 2 +- compiler/rustc_infer/Cargo.toml | 2 +- compiler/rustc_interface/Cargo.toml | 2 +- compiler/rustc_lexer/Cargo.toml | 2 +- compiler/rustc_lint/Cargo.toml | 2 +- compiler/rustc_lint_defs/Cargo.toml | 2 +- compiler/rustc_llvm/Cargo.toml | 2 +- compiler/rustc_log/Cargo.toml | 2 +- compiler/rustc_macros/Cargo.toml | 2 +- compiler/rustc_metadata/Cargo.toml | 2 +- compiler/rustc_middle/Cargo.toml | 2 +- compiler/rustc_mir_build/Cargo.toml | 2 +- compiler/rustc_mir_dataflow/Cargo.toml | 2 +- compiler/rustc_mir_transform/Cargo.toml | 2 +- compiler/rustc_monomorphize/Cargo.toml | 2 +- compiler/rustc_next_trait_solver/Cargo.toml | 2 +- compiler/rustc_parse/Cargo.toml | 2 +- compiler/rustc_parse_format/Cargo.toml | 2 +- compiler/rustc_passes/Cargo.toml | 2 +- compiler/rustc_pattern_analysis/Cargo.toml | 2 +- compiler/rustc_privacy/Cargo.toml | 2 +- compiler/rustc_query_impl/Cargo.toml | 2 +- compiler/rustc_query_system/Cargo.toml | 2 +- compiler/rustc_resolve/Cargo.toml | 2 +- compiler/rustc_sanitizers/Cargo.toml | 2 +- compiler/rustc_serialize/Cargo.toml | 2 +- compiler/rustc_session/Cargo.toml | 2 +- compiler/rustc_smir/Cargo.toml | 2 +- compiler/rustc_span/Cargo.toml | 2 +- compiler/rustc_symbol_mangling/Cargo.toml | 2 +- compiler/rustc_target/Cargo.toml | 2 +- compiler/rustc_trait_selection/Cargo.toml | 2 +- compiler/rustc_traits/Cargo.toml | 2 +- compiler/rustc_transmute/Cargo.toml | 2 +- compiler/rustc_ty_utils/Cargo.toml | 2 +- compiler/rustc_type_ir/Cargo.toml | 2 +- compiler/rustc_type_ir_macros/Cargo.toml | 2 +- compiler/stable_mir/Cargo.toml | 2 +- 72 files changed, 72 insertions(+), 72 deletions(-) diff --git a/compiler/rustc/Cargo.toml b/compiler/rustc/Cargo.toml index d24b630516a7c..f4caa3ef769d5 100644 --- a/compiler/rustc/Cargo.toml +++ b/compiler/rustc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc-main" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_abi/Cargo.toml b/compiler/rustc_abi/Cargo.toml index 3d6f4a6a10923..86dc84e2016d6 100644 --- a/compiler/rustc_abi/Cargo.toml +++ b/compiler/rustc_abi/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_abi" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_arena/Cargo.toml b/compiler/rustc_arena/Cargo.toml index 382ab2b077547..bbcd8ea6d389d 100644 --- a/compiler/rustc_arena/Cargo.toml +++ b/compiler/rustc_arena/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_arena" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_ast/Cargo.toml b/compiler/rustc_ast/Cargo.toml index 34c612dac692b..902287d032802 100644 --- a/compiler/rustc_ast/Cargo.toml +++ b/compiler/rustc_ast/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_ast" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_ast_ir/Cargo.toml b/compiler/rustc_ast_ir/Cargo.toml index 1905574073f13..f54e9687d8c7f 100644 --- a/compiler/rustc_ast_ir/Cargo.toml +++ b/compiler/rustc_ast_ir/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_ast_ir" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_ast_lowering/Cargo.toml b/compiler/rustc_ast_lowering/Cargo.toml index ce95f4dfa1b82..3215ce6b0cb47 100644 --- a/compiler/rustc_ast_lowering/Cargo.toml +++ b/compiler/rustc_ast_lowering/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_ast_lowering" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] doctest = false diff --git a/compiler/rustc_ast_passes/Cargo.toml b/compiler/rustc_ast_passes/Cargo.toml index e4c227532085f..c738cb2aa2fd4 100644 --- a/compiler/rustc_ast_passes/Cargo.toml +++ b/compiler/rustc_ast_passes/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_ast_passes" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_ast_pretty/Cargo.toml b/compiler/rustc_ast_pretty/Cargo.toml index f290fedcd8b9a..2634dd1fdf93e 100644 --- a/compiler/rustc_ast_pretty/Cargo.toml +++ b/compiler/rustc_ast_pretty/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_ast_pretty" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_attr_data_structures/Cargo.toml b/compiler/rustc_attr_data_structures/Cargo.toml index 2ee58f24470e9..19d0d5a306d6e 100644 --- a/compiler/rustc_attr_data_structures/Cargo.toml +++ b/compiler/rustc_attr_data_structures/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_attr_data_structures" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_attr_parsing/Cargo.toml b/compiler/rustc_attr_parsing/Cargo.toml index 7ccedf40c3fa9..f681e9397d9f1 100644 --- a/compiler/rustc_attr_parsing/Cargo.toml +++ b/compiler/rustc_attr_parsing/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_attr_parsing" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_baked_icu_data/Cargo.toml b/compiler/rustc_baked_icu_data/Cargo.toml index c35556dcf5bf2..cb0e145386b83 100644 --- a/compiler/rustc_baked_icu_data/Cargo.toml +++ b/compiler/rustc_baked_icu_data/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_baked_icu_data" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_borrowck/Cargo.toml b/compiler/rustc_borrowck/Cargo.toml index 89154bf2c23c4..9e7d55180a233 100644 --- a/compiler/rustc_borrowck/Cargo.toml +++ b/compiler/rustc_borrowck/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_borrowck" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_builtin_macros/Cargo.toml b/compiler/rustc_builtin_macros/Cargo.toml index b50cb35b8e983..f29be2ee81855 100644 --- a/compiler/rustc_builtin_macros/Cargo.toml +++ b/compiler/rustc_builtin_macros/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_builtin_macros" version = "0.0.0" -edition = "2021" +edition = "2024" [lints.rust] diff --git a/compiler/rustc_codegen_llvm/Cargo.toml b/compiler/rustc_codegen_llvm/Cargo.toml index a817227054885..d3ce7c5a1130f 100644 --- a/compiler/rustc_codegen_llvm/Cargo.toml +++ b/compiler/rustc_codegen_llvm/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_codegen_llvm" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] test = false diff --git a/compiler/rustc_codegen_ssa/Cargo.toml b/compiler/rustc_codegen_ssa/Cargo.toml index 963d9258be67d..83d847f2d155a 100644 --- a/compiler/rustc_codegen_ssa/Cargo.toml +++ b/compiler/rustc_codegen_ssa/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_codegen_ssa" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_const_eval/Cargo.toml b/compiler/rustc_const_eval/Cargo.toml index 7717cd2c69664..a0cc2c65e6e03 100644 --- a/compiler/rustc_const_eval/Cargo.toml +++ b/compiler/rustc_const_eval/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_const_eval" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_data_structures/Cargo.toml b/compiler/rustc_data_structures/Cargo.toml index 1705af1e210a6..bdf5494f2107b 100644 --- a/compiler/rustc_data_structures/Cargo.toml +++ b/compiler/rustc_data_structures/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_data_structures" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_driver/Cargo.toml b/compiler/rustc_driver/Cargo.toml index ae9712ad66d83..e3ee83512952a 100644 --- a/compiler/rustc_driver/Cargo.toml +++ b/compiler/rustc_driver/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_driver" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] crate-type = ["dylib"] diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml index 0b45e5786e83d..8593d1faba264 100644 --- a/compiler/rustc_driver_impl/Cargo.toml +++ b/compiler/rustc_driver_impl/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_driver_impl" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_error_codes/Cargo.toml b/compiler/rustc_error_codes/Cargo.toml index de668b81b7e07..55b4e89905126 100644 --- a/compiler/rustc_error_codes/Cargo.toml +++ b/compiler/rustc_error_codes/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_error_codes" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_error_messages/Cargo.toml b/compiler/rustc_error_messages/Cargo.toml index 6974c12f994b1..578af7fc51d40 100644 --- a/compiler/rustc_error_messages/Cargo.toml +++ b/compiler/rustc_error_messages/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_error_messages" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_errors/Cargo.toml b/compiler/rustc_errors/Cargo.toml index 434f8c1c76751..c1d8cd9bb9ed2 100644 --- a/compiler/rustc_errors/Cargo.toml +++ b/compiler/rustc_errors/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_errors" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_expand/Cargo.toml b/compiler/rustc_expand/Cargo.toml index eb93972387d40..33bada106ca79 100644 --- a/compiler/rustc_expand/Cargo.toml +++ b/compiler/rustc_expand/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_expand" version = "0.0.0" -edition = "2021" +edition = "2024" build = false [lib] diff --git a/compiler/rustc_feature/Cargo.toml b/compiler/rustc_feature/Cargo.toml index 77de7fabd4f92..a5ae06473cbe3 100644 --- a/compiler/rustc_feature/Cargo.toml +++ b/compiler/rustc_feature/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_feature" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_fluent_macro/Cargo.toml b/compiler/rustc_fluent_macro/Cargo.toml index eeceaa4691a2a..ce76b2745eaad 100644 --- a/compiler/rustc_fluent_macro/Cargo.toml +++ b/compiler/rustc_fluent_macro/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_fluent_macro" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] proc-macro = true diff --git a/compiler/rustc_fs_util/Cargo.toml b/compiler/rustc_fs_util/Cargo.toml index 4b76200c06c53..baca3bc7d49eb 100644 --- a/compiler/rustc_fs_util/Cargo.toml +++ b/compiler/rustc_fs_util/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_fs_util" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_graphviz/Cargo.toml b/compiler/rustc_graphviz/Cargo.toml index 780004ae3fbc8..d84943760baeb 100644 --- a/compiler/rustc_graphviz/Cargo.toml +++ b/compiler/rustc_graphviz/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_graphviz" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_hashes/Cargo.toml b/compiler/rustc_hashes/Cargo.toml index c2bae2fe8cb06..c7a273cff88c9 100644 --- a/compiler/rustc_hashes/Cargo.toml +++ b/compiler/rustc_hashes/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_hashes" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_hir/Cargo.toml b/compiler/rustc_hir/Cargo.toml index b1516e53173ba..98300fc40fbeb 100644 --- a/compiler/rustc_hir/Cargo.toml +++ b/compiler/rustc_hir/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_hir" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_hir_analysis/Cargo.toml b/compiler/rustc_hir_analysis/Cargo.toml index 196d7d99e933d..55a816a855af4 100644 --- a/compiler/rustc_hir_analysis/Cargo.toml +++ b/compiler/rustc_hir_analysis/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_hir_analysis" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] test = false diff --git a/compiler/rustc_hir_pretty/Cargo.toml b/compiler/rustc_hir_pretty/Cargo.toml index 9af1fb8279e9f..f5d7dbd3f96e4 100644 --- a/compiler/rustc_hir_pretty/Cargo.toml +++ b/compiler/rustc_hir_pretty/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_hir_pretty" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_hir_typeck/Cargo.toml b/compiler/rustc_hir_typeck/Cargo.toml index 0331a20f95b79..f1afb7b712d59 100644 --- a/compiler/rustc_hir_typeck/Cargo.toml +++ b/compiler/rustc_hir_typeck/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_hir_typeck" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_incremental/Cargo.toml b/compiler/rustc_incremental/Cargo.toml index 46a63b02e8469..a2f88f19f5325 100644 --- a/compiler/rustc_incremental/Cargo.toml +++ b/compiler/rustc_incremental/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_incremental" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_index/Cargo.toml b/compiler/rustc_index/Cargo.toml index f27db7a5400ad..3d83a3c98daf8 100644 --- a/compiler/rustc_index/Cargo.toml +++ b/compiler/rustc_index/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_index" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_index_macros/Cargo.toml b/compiler/rustc_index_macros/Cargo.toml index 98bc1b6a29bba..891e7ded61996 100644 --- a/compiler/rustc_index_macros/Cargo.toml +++ b/compiler/rustc_index_macros/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_index_macros" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] proc-macro = true diff --git a/compiler/rustc_infer/Cargo.toml b/compiler/rustc_infer/Cargo.toml index baf5dbbfd4226..08c0361488493 100644 --- a/compiler/rustc_infer/Cargo.toml +++ b/compiler/rustc_infer/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_infer" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] doctest = false diff --git a/compiler/rustc_interface/Cargo.toml b/compiler/rustc_interface/Cargo.toml index 295a988d2da5d..9c9660cf50469 100644 --- a/compiler/rustc_interface/Cargo.toml +++ b/compiler/rustc_interface/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_interface" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_lexer/Cargo.toml b/compiler/rustc_lexer/Cargo.toml index 4b3492fdeda25..448a50faf458e 100644 --- a/compiler/rustc_lexer/Cargo.toml +++ b/compiler/rustc_lexer/Cargo.toml @@ -2,7 +2,7 @@ name = "rustc_lexer" version = "0.0.0" license = "MIT OR Apache-2.0" -edition = "2021" +edition = "2024" repository = "https://github.com/rust-lang/rust/" description = """ Rust lexer used by rustc. No stability guarantees are provided. diff --git a/compiler/rustc_lint/Cargo.toml b/compiler/rustc_lint/Cargo.toml index cc5a90296332d..24e7b40c8a2d3 100644 --- a/compiler/rustc_lint/Cargo.toml +++ b/compiler/rustc_lint/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_lint" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_lint_defs/Cargo.toml b/compiler/rustc_lint_defs/Cargo.toml index 450885e71647f..9ab350daf69d7 100644 --- a/compiler/rustc_lint_defs/Cargo.toml +++ b/compiler/rustc_lint_defs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_lint_defs" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_llvm/Cargo.toml b/compiler/rustc_llvm/Cargo.toml index 2168a0df9ec87..4f3ce77efc441 100644 --- a/compiler/rustc_llvm/Cargo.toml +++ b/compiler/rustc_llvm/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_llvm" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_log/Cargo.toml b/compiler/rustc_log/Cargo.toml index fe399bc77e32a..30f6e9ba8053f 100644 --- a/compiler/rustc_log/Cargo.toml +++ b/compiler/rustc_log/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_log" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_macros/Cargo.toml b/compiler/rustc_macros/Cargo.toml index d8d2bef496404..f9d3b75835907 100644 --- a/compiler/rustc_macros/Cargo.toml +++ b/compiler/rustc_macros/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_macros" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] proc-macro = true diff --git a/compiler/rustc_metadata/Cargo.toml b/compiler/rustc_metadata/Cargo.toml index 0b9fdbbd3da8d..a8821640f048e 100644 --- a/compiler/rustc_metadata/Cargo.toml +++ b/compiler/rustc_metadata/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_metadata" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_middle/Cargo.toml b/compiler/rustc_middle/Cargo.toml index 389c861c3b524..aebd2181f31e1 100644 --- a/compiler/rustc_middle/Cargo.toml +++ b/compiler/rustc_middle/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_middle" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_mir_build/Cargo.toml b/compiler/rustc_mir_build/Cargo.toml index 1f3689926bcf3..d70d70a31a4a7 100644 --- a/compiler/rustc_mir_build/Cargo.toml +++ b/compiler/rustc_mir_build/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_mir_build" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_mir_dataflow/Cargo.toml b/compiler/rustc_mir_dataflow/Cargo.toml index f84a06638976e..293bcbef21b85 100644 --- a/compiler/rustc_mir_dataflow/Cargo.toml +++ b/compiler/rustc_mir_dataflow/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_mir_dataflow" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_mir_transform/Cargo.toml b/compiler/rustc_mir_transform/Cargo.toml index 2f233f787f0cc..fb8d0ac5e74ac 100644 --- a/compiler/rustc_mir_transform/Cargo.toml +++ b/compiler/rustc_mir_transform/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_mir_transform" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_monomorphize/Cargo.toml b/compiler/rustc_monomorphize/Cargo.toml index 5462105e5e8e4..36b76d261de68 100644 --- a/compiler/rustc_monomorphize/Cargo.toml +++ b/compiler/rustc_monomorphize/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_monomorphize" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_next_trait_solver/Cargo.toml b/compiler/rustc_next_trait_solver/Cargo.toml index eacb6002f5a41..63aa60f2f26b9 100644 --- a/compiler/rustc_next_trait_solver/Cargo.toml +++ b/compiler/rustc_next_trait_solver/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_next_trait_solver" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_parse/Cargo.toml b/compiler/rustc_parse/Cargo.toml index 2360914a0aba1..c9dcab0c871dd 100644 --- a/compiler/rustc_parse/Cargo.toml +++ b/compiler/rustc_parse/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_parse" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_parse_format/Cargo.toml b/compiler/rustc_parse_format/Cargo.toml index 707c4e318474a..a39cca716d23e 100644 --- a/compiler/rustc_parse_format/Cargo.toml +++ b/compiler/rustc_parse_format/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_parse_format" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_passes/Cargo.toml b/compiler/rustc_passes/Cargo.toml index f592a12ab75c1..ba81ef3103bd9 100644 --- a/compiler/rustc_passes/Cargo.toml +++ b/compiler/rustc_passes/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_passes" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_pattern_analysis/Cargo.toml b/compiler/rustc_pattern_analysis/Cargo.toml index 16eea9e4ff90a..40d549630acae 100644 --- a/compiler/rustc_pattern_analysis/Cargo.toml +++ b/compiler/rustc_pattern_analysis/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_pattern_analysis" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_privacy/Cargo.toml b/compiler/rustc_privacy/Cargo.toml index eb48155919fee..242c67d732aff 100644 --- a/compiler/rustc_privacy/Cargo.toml +++ b/compiler/rustc_privacy/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_privacy" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_query_impl/Cargo.toml b/compiler/rustc_query_impl/Cargo.toml index fd1d21b6a8929..d89e1355ca671 100644 --- a/compiler/rustc_query_impl/Cargo.toml +++ b/compiler/rustc_query_impl/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_query_impl" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_query_system/Cargo.toml b/compiler/rustc_query_system/Cargo.toml index d9560f3eb0fad..839465f9273bb 100644 --- a/compiler/rustc_query_system/Cargo.toml +++ b/compiler/rustc_query_system/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_query_system" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_resolve/Cargo.toml b/compiler/rustc_resolve/Cargo.toml index 309227176d4e5..f4771f1af2cfd 100644 --- a/compiler/rustc_resolve/Cargo.toml +++ b/compiler/rustc_resolve/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_resolve" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_sanitizers/Cargo.toml b/compiler/rustc_sanitizers/Cargo.toml index 5623a493cf009..66488bc962594 100644 --- a/compiler/rustc_sanitizers/Cargo.toml +++ b/compiler/rustc_sanitizers/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_sanitizers" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] bitflags = "2.5.0" diff --git a/compiler/rustc_serialize/Cargo.toml b/compiler/rustc_serialize/Cargo.toml index a6815c7a44768..948242352e7a8 100644 --- a/compiler/rustc_serialize/Cargo.toml +++ b/compiler/rustc_serialize/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_serialize" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_session/Cargo.toml b/compiler/rustc_session/Cargo.toml index 31892c1343805..a087725d34dd1 100644 --- a/compiler/rustc_session/Cargo.toml +++ b/compiler/rustc_session/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_session" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_smir/Cargo.toml b/compiler/rustc_smir/Cargo.toml index 29ce24e8b7849..a11df9a9c9bc9 100644 --- a/compiler/rustc_smir/Cargo.toml +++ b/compiler/rustc_smir/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_smir" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_span/Cargo.toml b/compiler/rustc_span/Cargo.toml index 991c75cc98df8..43a2d692577eb 100644 --- a/compiler/rustc_span/Cargo.toml +++ b/compiler/rustc_span/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_span" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_symbol_mangling/Cargo.toml b/compiler/rustc_symbol_mangling/Cargo.toml index 4c51c908f541f..12fe6b719f9b8 100644 --- a/compiler/rustc_symbol_mangling/Cargo.toml +++ b/compiler/rustc_symbol_mangling/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_symbol_mangling" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_target/Cargo.toml b/compiler/rustc_target/Cargo.toml index e33431ba12259..189b19b028617 100644 --- a/compiler/rustc_target/Cargo.toml +++ b/compiler/rustc_target/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_target" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_trait_selection/Cargo.toml b/compiler/rustc_trait_selection/Cargo.toml index 2f2361609a26c..1c61e23362a83 100644 --- a/compiler/rustc_trait_selection/Cargo.toml +++ b/compiler/rustc_trait_selection/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_trait_selection" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_traits/Cargo.toml b/compiler/rustc_traits/Cargo.toml index 9c788116d98c3..04aef4e7b9e03 100644 --- a/compiler/rustc_traits/Cargo.toml +++ b/compiler/rustc_traits/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_traits" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_transmute/Cargo.toml b/compiler/rustc_transmute/Cargo.toml index 94c7695117c63..e9daf6b0c384a 100644 --- a/compiler/rustc_transmute/Cargo.toml +++ b/compiler/rustc_transmute/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_transmute" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_ty_utils/Cargo.toml b/compiler/rustc_ty_utils/Cargo.toml index ab903c6ed73f8..4c7a57f2931bf 100644 --- a/compiler/rustc_ty_utils/Cargo.toml +++ b/compiler/rustc_ty_utils/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_ty_utils" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_type_ir/Cargo.toml b/compiler/rustc_type_ir/Cargo.toml index 8d97ec728304e..d8184da927c3c 100644 --- a/compiler/rustc_type_ir/Cargo.toml +++ b/compiler/rustc_type_ir/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_type_ir" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] # tidy-alphabetical-start diff --git a/compiler/rustc_type_ir_macros/Cargo.toml b/compiler/rustc_type_ir_macros/Cargo.toml index cb95ca6834623..15a5557509929 100644 --- a/compiler/rustc_type_ir_macros/Cargo.toml +++ b/compiler/rustc_type_ir_macros/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustc_type_ir_macros" version = "0.0.0" -edition = "2021" +edition = "2024" [lib] proc-macro = true diff --git a/compiler/stable_mir/Cargo.toml b/compiler/stable_mir/Cargo.toml index 2edb3f140d7ac..d691a0e4f22f5 100644 --- a/compiler/stable_mir/Cargo.toml +++ b/compiler/stable_mir/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "stable_mir" version = "0.1.0-preview" -edition = "2021" +edition = "2024" [dependencies] scoped-tls = "1.0" From 7f6873f64c17cfa53a10a7751c7213f6ed0215c1 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 18 Sep 2024 15:39:23 -0400 Subject: [PATCH 13/20] Fix builtin lints --- compiler/rustc_lint/src/builtin.rs | 6 ++---- compiler/rustc_lint/src/foreign_modules.rs | 4 ++-- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_lint_defs/src/builtin.rs | 8 ++++---- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index b5f09ff346a7a..681a76e26f0f7 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -975,10 +975,8 @@ declare_lint! { /// ### Example /// /// ```rust - /// #[no_mangle] - /// fn foo(t: T) { - /// - /// } + /// #[unsafe(no_mangle)] + /// fn foo(t: T) {} /// ``` /// /// {{produces}} diff --git a/compiler/rustc_lint/src/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index 636779fe9b4cf..49c34d0edcc2a 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -35,12 +35,12 @@ declare_lint! { /// /// ```rust /// mod m { - /// extern "C" { + /// unsafe extern "C" { /// fn foo(); /// } /// } /// - /// extern "C" { + /// unsafe extern "C" { /// fn foo(_: u32); /// } /// ``` diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 68b1f435a4cf7..7e242a9f56711 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -696,7 +696,7 @@ declare_lint! { /// ### Example /// /// ```rust - /// extern "C" { + /// unsafe extern "C" { /// static STATIC: String; /// } /// ``` diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 10bf4ec77ed93..97850a2afc11e 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -2780,7 +2780,7 @@ declare_lint! { /// /// ```rust /// enum Void {} - /// extern { + /// unsafe extern { /// static EXTERN: Void; /// } /// ``` @@ -4011,7 +4011,7 @@ declare_lint! { /// ```rust /// #![warn(ffi_unwind_calls)] /// - /// extern "C-unwind" { + /// unsafe extern "C-unwind" { /// fn foo(); /// } /// @@ -4755,7 +4755,7 @@ declare_lint! { /// /// ### Example /// - /// ```rust + /// ```rust,edition2021 /// #![warn(missing_unsafe_on_extern)] /// #![allow(dead_code)] /// @@ -4792,7 +4792,7 @@ declare_lint! { /// /// ### Example /// - /// ```rust + /// ```rust,edition2021 /// #![warn(unsafe_attr_outside_unsafe)] /// /// #[no_mangle] From e1819a889a2606b79dc9cc790205da1497d617b7 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 20 Feb 2025 18:28:42 +0000 Subject: [PATCH 14/20] Fix overcapturing, unsafe extern blocks, and new unsafe ops --- compiler/rustc/src/main.rs | 2 +- .../rustc_borrowck/src/universal_regions.rs | 2 +- .../rustc_codegen_llvm/src/llvm/enzyme_ffi.rs | 4 ++-- .../src/graph/scc/mod.rs | 2 +- compiler/rustc_expand/src/proc_macro.rs | 2 +- compiler/rustc_interface/src/passes.rs | 20 +++++++++++-------- compiler/rustc_llvm/build.rs | 8 ++++++-- 7 files changed, 24 insertions(+), 16 deletions(-) diff --git a/compiler/rustc/src/main.rs b/compiler/rustc/src/main.rs index a55a63a7bf179..ca1bb59e59d60 100644 --- a/compiler/rustc/src/main.rs +++ b/compiler/rustc/src/main.rs @@ -65,7 +65,7 @@ fn main() { // linking, so we need to explicitly depend on the function. #[cfg(target_os = "macos")] { - extern "C" { + unsafe extern "C" { fn _rjem_je_zone_register(); } diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 9a68eeb3326eb..c578eb4dc458a 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -308,7 +308,7 @@ impl<'tcx> UniversalRegions<'tcx> { /// Returns an iterator over all the RegionVids corresponding to /// universally quantified free regions. - pub(crate) fn universal_regions_iter(&self) -> impl Iterator { + pub(crate) fn universal_regions_iter(&self) -> impl Iterator + use<> { (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize) } diff --git a/compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs index 39bac13a9680c..9c740ab98688c 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs @@ -7,7 +7,7 @@ use super::ffi::{BasicBlock, Metadata, Module, Type, Value}; use crate::llvm::Bool; #[link(name = "llvm-wrapper", kind = "static")] -extern "C" { +unsafe extern "C" { // Enzyme pub(crate) fn LLVMRustHasMetadata(I: &Value, KindID: c_uint) -> bool; pub(crate) fn LLVMRustEraseInstUntilInclusive(BB: &BasicBlock, I: &Value); @@ -18,7 +18,7 @@ extern "C" { pub(crate) fn LLVMRustVerifyFunction(V: &Value, action: LLVMRustVerifierFailureAction) -> Bool; } -extern "C" { +unsafe extern "C" { // Enzyme pub(crate) fn LLVMDumpModule(M: &Module); pub(crate) fn LLVMDumpValue(V: &Value); diff --git a/compiler/rustc_data_structures/src/graph/scc/mod.rs b/compiler/rustc_data_structures/src/graph/scc/mod.rs index 93f6192b10b03..2241b538738cb 100644 --- a/compiler/rustc_data_structures/src/graph/scc/mod.rs +++ b/compiler/rustc_data_structures/src/graph/scc/mod.rs @@ -133,7 +133,7 @@ impl Sccs { /// meaning that if `S1 -> S2`, we will visit `S2` first and `S1` after. /// This is convenient when the edges represent dependencies: when you visit /// `S1`, the value for `S2` will already have been computed. - pub fn all_sccs(&self) -> impl Iterator { + pub fn all_sccs(&self) -> impl Iterator + use { (0..self.scc_data.len()).map(S::new) } diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index dca0516f9f3b3..814d2b04d8d02 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -31,7 +31,7 @@ impl pm::bridge::server::MessagePipe for MessagePipe { } } -fn exec_strategy(ecx: &ExtCtxt<'_>) -> impl pm::bridge::server::ExecutionStrategy { +fn exec_strategy(ecx: &ExtCtxt<'_>) -> impl pm::bridge::server::ExecutionStrategy + use<> { pm::bridge::server::MaybeCrossThread::>::new( ecx.sess.opts.unstable_opts.proc_macro_execution_strategy == ProcMacroExecutionStrategy::CrossThread, diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index d70d9d344b94c..2d3c7f834e985 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -171,13 +171,15 @@ fn configure_and_expand( new_path.push(path); } } - env::set_var( - "PATH", - &env::join_paths( - new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()), - ) - .unwrap(), - ); + unsafe { + env::set_var( + "PATH", + &env::join_paths( + new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()), + ) + .unwrap(), + ); + } } // Create the config for macro expansion @@ -216,7 +218,9 @@ fn configure_and_expand( } if cfg!(windows) { - env::set_var("PATH", &old_path); + unsafe { + env::set_var("PATH", &old_path); + } } krate diff --git a/compiler/rustc_llvm/build.rs b/compiler/rustc_llvm/build.rs index 48806888b43df..3d1f3b2cd4dd4 100644 --- a/compiler/rustc_llvm/build.rs +++ b/compiler/rustc_llvm/build.rs @@ -51,9 +51,13 @@ fn detect_llvm_link() -> (&'static str, &'static str) { fn restore_library_path() { let key = tracked_env_var_os("REAL_LIBRARY_PATH_VAR").expect("REAL_LIBRARY_PATH_VAR"); if let Some(env) = tracked_env_var_os("REAL_LIBRARY_PATH") { - env::set_var(&key, env); + unsafe { + env::set_var(&key, env); + } } else { - env::remove_var(&key); + unsafe { + env::remove_var(&key); + } } } From 681c95c55c449a20c0abe8aadc55b0677cabaa25 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 17 Feb 2025 17:36:35 +0000 Subject: [PATCH 15/20] Remove UnifyReceiver cause code --- .../rustc_hir_typeck/src/method/confirm.rs | 14 +-- compiler/rustc_middle/src/traits/mod.rs | 10 -- .../nice_region_error/static_impl_trait.rs | 112 ++---------------- .../src/error_reporting/traits/suggestions.rs | 1 - 4 files changed, 12 insertions(+), 125 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 8fb425ff0c94c..3b107fbf17394 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -11,7 +11,7 @@ use rustc_hir_analysis::hir_ty_lowering::{ }; use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk}; use rustc_lint::builtin::SUPERTRAIT_ITEM_SHADOWING_USAGE; -use rustc_middle::traits::{ObligationCauseCode, UnifyReceiverContext}; +use rustc_middle::traits::ObligationCauseCode; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCoercion, }; @@ -136,7 +136,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { "confirm: self_ty={:?} method_sig_rcvr={:?} method_sig={:?} method_predicates={:?}", self_ty, method_sig_rcvr, method_sig, method_predicates ); - self.unify_receivers(self_ty, method_sig_rcvr, pick, all_args); + self.unify_receivers(self_ty, method_sig_rcvr, pick); let (method_sig, method_predicates) = self.normalize(self.span, (method_sig, method_predicates)); @@ -525,20 +525,12 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { self_ty: Ty<'tcx>, method_self_ty: Ty<'tcx>, pick: &probe::Pick<'tcx>, - args: GenericArgsRef<'tcx>, ) { debug!( "unify_receivers: self_ty={:?} method_self_ty={:?} span={:?} pick={:?}", self_ty, method_self_ty, self.span, pick ); - let cause = self.cause( - self.self_expr.span, - ObligationCauseCode::UnifyReceiver(Box::new(UnifyReceiverContext { - assoc_item: pick.item, - param_env: self.param_env, - args, - })), - ); + let cause = self.cause(self.self_expr.span, ObligationCauseCode::Misc); match self.at(&cause, self.param_env).sup(DefineOpaqueTypes::Yes, method_self_ty, self_ty) { Ok(InferOk { obligations, value: () }) => { self.register_predicates(obligations); diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 53bc9eb7e466c..a2cc5221d00ec 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -144,14 +144,6 @@ impl<'tcx> ObligationCause<'tcx> { } } -#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)] -#[derive(TypeVisitable, TypeFoldable)] -pub struct UnifyReceiverContext<'tcx> { - pub assoc_item: ty::AssocItem, - pub param_env: ty::ParamEnv<'tcx>, - pub args: GenericArgsRef<'tcx>, -} - /// A compact form of `ObligationCauseCode`. #[derive(Clone, PartialEq, Eq, Default, HashStable)] #[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)] @@ -360,8 +352,6 @@ pub enum ObligationCauseCode<'tcx> { /// Method receiver MethodReceiver, - UnifyReceiver(Box>), - /// `return` with no expression ReturnNoExpression, diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index 3f15a79271d5b..b6ada8dfbf8ef 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -8,20 +8,17 @@ use rustc_hir::{ self as hir, AmbigArg, GenericBound, GenericParam, GenericParamKind, Item, ItemKind, Lifetime, LifetimeName, LifetimeParamKind, MissingLifetimeKind, Node, TyKind, }; -use rustc_middle::ty::{ - self, AssocItemContainer, StaticLifetimeVisitor, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, -}; +use rustc_middle::ty::{self, StaticLifetimeVisitor, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; use rustc_span::def_id::LocalDefId; use rustc_span::{Ident, Span}; use tracing::debug; use crate::error_reporting::infer::nice_region_error::NiceRegionError; use crate::errors::{ - ButCallingIntroduces, ButNeedsToSatisfy, DynTraitConstraintSuggestion, MoreTargeted, - ReqIntroducedLocations, + ButNeedsToSatisfy, DynTraitConstraintSuggestion, MoreTargeted, ReqIntroducedLocations, }; use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace}; -use crate::traits::{ObligationCauseCode, UnifyReceiverContext}; +use crate::traits::ObligationCauseCode; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when the return type is a static `impl Trait`, @@ -39,52 +36,6 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { sup_r, spans, ) if sub_r.is_static() => (var_origin, sub_origin, sub_r, sup_origin, sup_r, spans), - RegionResolutionError::ConcreteFailure( - SubregionOrigin::Subtype(box TypeTrace { cause, .. }), - sub_r, - sup_r, - ) if sub_r.is_static() => { - // This is for an implicit `'static` requirement coming from `impl dyn Trait {}`. - if let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code() { - // This may have a closure and it would cause ICE - // through `find_param_with_region` (#78262). - let anon_reg_sup = tcx.is_suitable_region(self.generic_param_scope, *sup_r)?; - let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.scope); - if fn_returns.is_empty() { - return None; - } - - let param = self.find_param_with_region(*sup_r, *sub_r)?; - let simple_ident = param.param.pat.simple_ident(); - - let (has_impl_path, impl_path) = match ctxt.assoc_item.container { - AssocItemContainer::Trait => { - let id = ctxt.assoc_item.container_id(tcx); - (true, tcx.def_path_str(id)) - } - AssocItemContainer::Impl => (false, String::new()), - }; - - let mut err = self.tcx().dcx().create_err(ButCallingIntroduces { - param_ty_span: param.param_ty_span, - cause_span: cause.span, - has_param_name: simple_ident.is_some(), - param_name: simple_ident.map(|x| x.to_string()).unwrap_or_default(), - has_lifetime: sup_r.has_name(), - lifetime: sup_r.to_string(), - assoc_item: ctxt.assoc_item.name, - has_impl_path, - impl_path, - }); - if self.find_impl_on_dyn_trait(&mut err, param.param_ty, ctxt) { - let reported = err.emit(); - return Some(reported); - } else { - err.cancel() - } - } - return None; - } _ => return None, }; debug!( @@ -198,25 +149,14 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.scope); let mut override_error_code = None; - if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sup_origin - && let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code() - // Handle case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a - // `'static` lifetime when called as a method on a binding: `bar.qux()`. - && self.find_impl_on_dyn_trait(&mut err, param.param_ty, ctxt) - { - override_error_code = Some(ctxt.assoc_item.name); - } if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sub_origin && let code = match cause.code() { ObligationCauseCode::MatchImpl(parent, ..) => parent.code(), _ => cause.code(), } - && let ( - &ObligationCauseCode::WhereClause(item_def_id, _) - | &ObligationCauseCode::WhereClauseInExpr(item_def_id, ..), - None, - ) = (code, override_error_code) + && let &ObligationCauseCode::WhereClause(item_def_id, _) + | &ObligationCauseCode::WhereClauseInExpr(item_def_id, ..) = code { // Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static` // lifetime as above, but called using a fully-qualified path to the method: @@ -230,7 +170,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { override_error_code = Some(ident.name); } } - if let (Some(ident), true) = (override_error_code, fn_returns.is_empty()) { + if let Some(ident) = override_error_code + && fn_returns.is_empty() + { // Provide a more targeted error code and description. let retarget_subdiag = MoreTargeted { ident }; retarget_subdiag.add_to_diag(&mut err); @@ -495,8 +437,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { kind: ItemKind::Impl(hir::Impl { self_ty, .. }), .. }) = tcx.hir_node_by_def_id(impl_did) && trait_objects.iter().all(|did| { - // FIXME: we should check `self_ty` against the receiver - // type in the `UnifyReceiver` context, but for now, use + // FIXME: we should check `self_ty`, but for now, use // this imperfect proxy. This will fail if there are // multiple `impl`s for the same trait like // `impl Foo for Box` and `impl Foo for dyn Bar`. @@ -517,41 +458,6 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { } } - /// When we call a method coming from an `impl Foo for dyn Bar`, `dyn Bar` introduces a default - /// `'static` obligation. Suggest relaxing that implicit bound. - fn find_impl_on_dyn_trait( - &self, - err: &mut Diag<'_>, - ty: Ty<'_>, - ctxt: &UnifyReceiverContext<'tcx>, - ) -> bool { - let tcx = self.tcx(); - - // Find the method being called. - let Ok(Some(instance)) = ty::Instance::try_resolve( - tcx, - self.cx.typing_env(ctxt.param_env), - ctxt.assoc_item.def_id, - self.cx.resolve_vars_if_possible(ctxt.args), - ) else { - return false; - }; - - let mut v = TraitObjectVisitor(FxIndexSet::default()); - v.visit_ty(ty); - - // Get the `Ident` of the method being called and the corresponding `impl` (to point at - // `Bar` in `impl Foo for dyn Bar {}` and the definition of the method being called). - let Some((ident, self_ty)) = - NiceRegionError::get_impl_ident_and_self_ty_from_trait(tcx, instance.def_id(), &v.0) - else { - return false; - }; - - // Find the trait object types in the argument, so we point at *only* the trait object. - self.suggest_constrain_dyn_trait_in_impl(err, &v.0, ident, self_ty) - } - fn suggest_constrain_dyn_trait_in_impl( &self, err: &mut Diag<'_>, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 6eeb47a21f8dd..496a28cd39fd1 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -2680,7 +2680,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { | ObligationCauseCode::IntrinsicType | ObligationCauseCode::MethodReceiver | ObligationCauseCode::ReturnNoExpression - | ObligationCauseCode::UnifyReceiver(..) | ObligationCauseCode::Misc | ObligationCauseCode::WellFormed(..) | ObligationCauseCode::MatchImpl(..) From 9001e5530221de3bb89d59a0ad36c45dcd40077f Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 17 Feb 2025 17:39:55 +0000 Subject: [PATCH 16/20] More dead code --- .../nice_region_error/static_impl_trait.rs | 57 +------------------ compiler/rustc_trait_selection/src/errors.rs | 16 ------ 2 files changed, 2 insertions(+), 71 deletions(-) diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index b6ada8dfbf8ef..9fed03859f862 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -1,7 +1,7 @@ //! Error Reporting for static impl Traits. use rustc_data_structures::fx::FxIndexSet; -use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, Subdiagnostic}; +use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{Visitor, VisitorExt, walk_ty}; use rustc_hir::{ @@ -14,9 +14,7 @@ use rustc_span::{Ident, Span}; use tracing::debug; use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::{ - ButNeedsToSatisfy, DynTraitConstraintSuggestion, MoreTargeted, ReqIntroducedLocations, -}; +use crate::errors::{ButNeedsToSatisfy, ReqIntroducedLocations}; use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace}; use crate::traits::ObligationCauseCode; @@ -148,36 +146,6 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.scope); - let mut override_error_code = None; - - if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sub_origin - && let code = match cause.code() { - ObligationCauseCode::MatchImpl(parent, ..) => parent.code(), - _ => cause.code(), - } - && let &ObligationCauseCode::WhereClause(item_def_id, _) - | &ObligationCauseCode::WhereClauseInExpr(item_def_id, ..) = code - { - // Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static` - // lifetime as above, but called using a fully-qualified path to the method: - // `Foo::qux(bar)`. - let mut v = TraitObjectVisitor(FxIndexSet::default()); - v.visit_ty(param.param_ty); - if let Some((ident, self_ty)) = - NiceRegionError::get_impl_ident_and_self_ty_from_trait(tcx, item_def_id, &v.0) - && self.suggest_constrain_dyn_trait_in_impl(&mut err, &v.0, ident, self_ty) - { - override_error_code = Some(ident.name); - } - } - if let Some(ident) = override_error_code - && fn_returns.is_empty() - { - // Provide a more targeted error code and description. - let retarget_subdiag = MoreTargeted { ident }; - retarget_subdiag.add_to_diag(&mut err); - } - let arg = match param.param.pat.simple_ident() { Some(simple_ident) => format!("argument `{simple_ident}`"), None => "the argument".to_string(), @@ -457,27 +425,6 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { _ => None, } } - - fn suggest_constrain_dyn_trait_in_impl( - &self, - err: &mut Diag<'_>, - found_dids: &FxIndexSet, - ident: Ident, - self_ty: &hir::Ty<'_>, - ) -> bool { - let mut suggested = false; - for found_did in found_dids { - let mut traits = vec![]; - let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did); - hir_v.visit_ty_unambig(self_ty); - for &span in &traits { - let subdiag = DynTraitConstraintSuggestion { span, ident }; - subdiag.add_to_diag(err); - suggested = true; - } - } - suggested - } } /// Collect all the trait objects in a type that could have received an implicit `'static` lifetime. diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index e8d30d3ee7996..d0b944a93528b 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -1119,22 +1119,6 @@ impl Subdiagnostic for ReqIntroducedLocations { } } -pub struct MoreTargeted { - pub ident: Symbol, -} - -impl Subdiagnostic for MoreTargeted { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { - diag.code(E0772); - diag.primary_message(fluent::trait_selection_more_targeted); - diag.arg("ident", self.ident); - } -} - #[derive(Diagnostic)] #[diag(trait_selection_but_needs_to_satisfy, code = E0759)] pub struct ButNeedsToSatisfy { From b2b2e53916cd505e1f7626581a4f0f5be1215201 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 17 Feb 2025 17:41:55 +0000 Subject: [PATCH 17/20] Even more dead code -- we don't HIR regionck anymore --- compiler/rustc_trait_selection/messages.ftl | 8 ---- .../mismatched_static_lifetime.rs | 6 +-- .../nice_region_error/static_impl_trait.rs | 43 ++----------------- compiler/rustc_trait_selection/src/errors.rs | 3 -- 4 files changed, 5 insertions(+), 55 deletions(-) diff --git a/compiler/rustc_trait_selection/messages.ftl b/compiler/rustc_trait_selection/messages.ftl index 055a3edcc3293..4db9d9915b139 100644 --- a/compiler/rustc_trait_selection/messages.ftl +++ b/compiler/rustc_trait_selection/messages.ftl @@ -225,14 +225,6 @@ trait_selection_mismatched_static_lifetime = incompatible lifetime on type trait_selection_missing_options_for_on_unimplemented_attr = missing options for `on_unimplemented` attribute .help = at least one of the `message`, `note` and `label` options are expected -trait_selection_more_targeted = {$has_param_name -> - [true] `{$param_name}` - *[false] `fn` parameter -} has {$has_lifetime -> - [true] lifetime `{$lifetime}` - *[false] an anonymous lifetime `'_` -} but calling `{$ident}` introduces an implicit `'static` lifetime requirement - trait_selection_msl_introduces_static = introduces a `'static` lifetime requirement trait_selection_msl_unmet_req = because this has an unmet lifetime requirement diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs index ad2f7f00fa53d..0904177ea8bb1 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs @@ -33,11 +33,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { }; // If we added a "points at argument expression" obligation, we remove it here, we care // about the original obligation only. - let code = match cause.code() { - ObligationCauseCode::FunctionArg { parent_code, .. } => &*parent_code, - code => code, - }; - let ObligationCauseCode::MatchImpl(parent, impl_def_id) = code else { + let ObligationCauseCode::MatchImpl(parent, impl_def_id) = cause.code() else { return None; }; let (ObligationCauseCode::WhereClause(_, binding_span) diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index 9fed03859f862..083ce022238a0 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -1,22 +1,21 @@ //! Error Reporting for static impl Traits. use rustc_data_structures::fx::FxIndexSet; -use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan}; +use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{Visitor, VisitorExt, walk_ty}; use rustc_hir::{ self as hir, AmbigArg, GenericBound, GenericParam, GenericParamKind, Item, ItemKind, Lifetime, LifetimeName, LifetimeParamKind, MissingLifetimeKind, Node, TyKind, }; -use rustc_middle::ty::{self, StaticLifetimeVisitor, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; use rustc_span::def_id::LocalDefId; use rustc_span::{Ident, Span}; use tracing::debug; use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::{ButNeedsToSatisfy, ReqIntroducedLocations}; -use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace}; -use crate::traits::ObligationCauseCode; +use crate::errors::ButNeedsToSatisfy; +use crate::infer::{RegionResolutionError, SubregionOrigin}; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when the return type is a static `impl Trait`, @@ -89,39 +88,6 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { None }; - let mut subdiag = None; - - if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = sub_origin { - if let ObligationCauseCode::ReturnValue(hir_id) - | ObligationCauseCode::BlockTailExpression(hir_id, ..) = cause.code() - { - let parent_id = tcx.hir_get_parent_item(*hir_id); - if let Some(fn_decl) = tcx.hir_fn_decl_by_hir_id(parent_id.into()) { - let mut span: MultiSpan = fn_decl.output.span().into(); - let mut spans = Vec::new(); - let mut add_label = true; - if let hir::FnRetTy::Return(ty) = fn_decl.output { - let mut v = StaticLifetimeVisitor(vec![], tcx.hir()); - v.visit_ty_unambig(ty); - if !v.0.is_empty() { - span = v.0.clone().into(); - spans = v.0; - add_label = false; - } - } - let fn_decl_span = fn_decl.output.span(); - - subdiag = Some(ReqIntroducedLocations { - span, - spans, - fn_decl_span, - cause_span: cause.span, - add_label, - }); - } - } - } - let diag = ButNeedsToSatisfy { sp, influencer_point, @@ -132,7 +98,6 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { require_span_as_note: require_as_note.then_some(require_span), // We don't need a note, it's already at the end, it can be shown as a `span_label`. require_span_as_label: (!require_as_note).then_some(require_span), - req_introduces_loc: subdiag, has_lifetime: sup_r.has_name(), lifetime: lifetime_name.clone(), diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index d0b944a93528b..01a92091fc3f3 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -1135,9 +1135,6 @@ pub struct ButNeedsToSatisfy { #[note(trait_selection_introduced_by_bound)] pub bound: Option, - #[subdiagnostic] - pub req_introduces_loc: Option, - pub has_param_name: bool, pub param_name: String, pub spans_empty: bool, From 3d5438accdd111b4e507bbfae5e2df6062fb5689 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 20 Feb 2025 18:28:48 +0000 Subject: [PATCH 18/20] Fix binding mode problems --- compiler/rustc_abi/src/lib.rs | 18 ++++++------ compiler/rustc_ast/src/visit.rs | 2 +- .../src/diagnostics/conflict_errors.rs | 2 +- .../src/diagnostics/explain_borrow.rs | 2 +- .../rustc_borrowck/src/diagnostics/mod.rs | 2 +- .../src/diagnostics/region_name.rs | 4 +-- .../src/back/symbol_export.rs | 4 +-- .../rustc_codegen_ssa/src/codegen_attrs.rs | 6 ++-- compiler/rustc_codegen_ssa/src/mir/block.rs | 4 +-- compiler/rustc_codegen_ssa/src/mir/operand.rs | 2 +- .../src/const_eval/machine.rs | 10 +++---- .../src/sorted_map/tests.rs | 2 +- compiler/rustc_expand/src/mbe/transcribe.rs | 4 +-- compiler/rustc_hir/src/hir/tests.rs | 4 +-- compiler/rustc_hir/src/intravisit.rs | 12 ++++---- .../rustc_hir_analysis/src/collect/type_of.rs | 2 +- .../src/hir_ty_lowering/mod.rs | 7 ++--- compiler/rustc_hir_pretty/src/lib.rs | 2 +- compiler/rustc_hir_typeck/src/callee.rs | 4 +-- compiler/rustc_hir_typeck/src/coercion.rs | 2 +- compiler/rustc_hir_typeck/src/demand.rs | 10 +++---- compiler/rustc_hir_typeck/src/fallback.rs | 2 +- compiler/rustc_hir_typeck/src/method/probe.rs | 2 +- .../rustc_hir_typeck/src/method/suggest.rs | 9 ++---- compiler/rustc_hir_typeck/src/pat.rs | 4 +-- compiler/rustc_index/src/bit_set.rs | 20 +++---------- compiler/rustc_lint/src/non_ascii_idents.rs | 6 ++-- compiler/rustc_lint/src/nonstandard_style.rs | 2 +- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_lint_defs/src/lib.rs | 4 +-- .../rustc_macros/src/diagnostics/utils.rs | 4 +-- compiler/rustc_middle/src/middle/mod.rs | 2 +- compiler/rustc_middle/src/mir/mono.rs | 2 +- compiler/rustc_middle/src/mir/pretty.rs | 2 +- compiler/rustc_middle/src/mir/terminator.rs | 2 +- compiler/rustc_middle/src/mir/visit.rs | 6 ++-- compiler/rustc_middle/src/thir.rs | 3 +- compiler/rustc_middle/src/thir/visit.rs | 2 +- compiler/rustc_middle/src/traits/mod.rs | 2 +- .../rustc_middle/src/ty/structural_impls.rs | 16 +++++------ compiler/rustc_middle/src/ty/sty.rs | 2 +- compiler/rustc_mir_build/src/builder/block.rs | 2 +- compiler/rustc_mir_build/src/thir/cx/expr.rs | 4 +-- .../src/thir/pattern/check_match.rs | 4 +-- compiler/rustc_mir_build/src/thir/util.rs | 2 +- compiler/rustc_mir_dataflow/src/un_derefer.rs | 2 +- .../rustc_mir_dataflow/src/value_analysis.rs | 4 +-- .../rustc_mir_transform/src/jump_threading.rs | 2 +- .../src/known_panics_lint.rs | 6 ++-- .../src/mentioned_items.rs | 2 +- compiler/rustc_mir_transform/src/simplify.rs | 6 ++-- .../src/simplify_branches.rs | 2 +- .../src/simplify_comparison_integral.rs | 4 +-- .../rustc_monomorphize/src/partitioning.rs | 2 +- compiler/rustc_passes/src/dead.rs | 2 +- compiler/rustc_passes/src/stability.rs | 6 +--- compiler/rustc_resolve/src/imports.rs | 18 ++++++------ compiler/rustc_resolve/src/late.rs | 28 +++++++++---------- .../rustc_resolve/src/late/diagnostics.rs | 6 ++-- compiler/rustc_session/src/session.rs | 3 +- compiler/rustc_span/src/lib.rs | 4 +-- .../src/error_reporting/infer/suggest.rs | 2 +- .../traits/fulfillment_errors.rs | 2 +- .../src/error_reporting/traits/suggestions.rs | 2 +- compiler/rustc_trait_selection/src/errors.rs | 13 ++++----- .../src/solve/fulfill.rs | 4 ++- .../src/traits/dyn_compatibility.rs | 4 +-- 67 files changed, 154 insertions(+), 181 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 098638b6bcfa7..34228912041d7 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -329,19 +329,19 @@ impl TargetDataLayout { [p] if p.starts_with('P') => { dl.instruction_address_space = parse_address_space(&p[1..], "P")? } - ["a", ref a @ ..] => dl.aggregate_align = parse_align(a, "a")?, - ["f16", ref a @ ..] => dl.f16_align = parse_align(a, "f16")?, - ["f32", ref a @ ..] => dl.f32_align = parse_align(a, "f32")?, - ["f64", ref a @ ..] => dl.f64_align = parse_align(a, "f64")?, - ["f128", ref a @ ..] => dl.f128_align = parse_align(a, "f128")?, + ["a", a @ ..] => dl.aggregate_align = parse_align(a, "a")?, + ["f16", a @ ..] => dl.f16_align = parse_align(a, "f16")?, + ["f32", a @ ..] => dl.f32_align = parse_align(a, "f32")?, + ["f64", a @ ..] => dl.f64_align = parse_align(a, "f64")?, + ["f128", a @ ..] => dl.f128_align = parse_align(a, "f128")?, // FIXME(erikdesjardins): we should be parsing nonzero address spaces // this will require replacing TargetDataLayout::{pointer_size,pointer_align} // with e.g. `fn pointer_size_in(AddressSpace)` - [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => { + [p @ "p", s, a @ ..] | [p @ "p0", s, a @ ..] => { dl.pointer_size = parse_size(s, p)?; dl.pointer_align = parse_align(a, p)?; } - [s, ref a @ ..] if s.starts_with('i') => { + [s, a @ ..] if s.starts_with('i') => { let Ok(bits) = s[1..].parse::() else { parse_size(&s[1..], "i")?; // For the user error. continue; @@ -362,7 +362,7 @@ impl TargetDataLayout { dl.i128_align = a; } } - [s, ref a @ ..] if s.starts_with('v') => { + [s, a @ ..] if s.starts_with('v') => { let v_size = parse_size(&s[1..], "v")?; let a = parse_align(a, s)?; if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) { @@ -1802,7 +1802,7 @@ where variants, max_repr_align, unadjusted_abi_align, - ref randomization_seed, + randomization_seed, } = self; f.debug_struct("Layout") .field("size", size) diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 3242d4145959d..1cb32b56875c3 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -597,7 +597,7 @@ pub fn walk_use_tree<'a, V: Visitor<'a>>( visit_opt!(visitor, visit_ident, rename); } UseTreeKind::Glob => {} - UseTreeKind::Nested { ref items, span: _ } => { + UseTreeKind::Nested { items, span: _ } => { for &(ref nested_tree, nested_id) in items { try_visit!(visitor.visit_use_tree(nested_tree, nested_id, true)); } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 5a526da0087ed..94662070db40a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -2617,7 +2617,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } = local.pat && let Some(init) = local.init - && let hir::Expr { + && let &hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { kind: hir::ClosureKind::Closure, diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index b2b66eabb38b8..f77dda0d386aa 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -262,7 +262,7 @@ impl<'tcx> BorrowExplanation<'tcx> { fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { if let hir::ExprKind::If(cond, _conseq, _alt) | hir::ExprKind::Loop( - hir::Block { + &hir::Block { expr: Some(&hir::Expr { kind: hir::ExprKind::If(cond, _conseq, _alt), diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 7da089c5e8c62..d1f238331d56f 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1126,7 +1126,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let hir_id = self.infcx.tcx.local_def_id_to_hir_id(def_id); let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind; debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr); - if let hir::ExprKind::Closure(&hir::Closure { kind, fn_decl_span, .. }) = expr { + if let &hir::ExprKind::Closure(&hir::Closure { kind, fn_decl_span, .. }) = expr { for (captured_place, place) in self.infcx.tcx.closure_captures(def_id).iter().zip(places) { diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 88804560f28e2..be28f84debd90 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -681,7 +681,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { let mir_hir_id = self.mir_hir_id(); let (return_span, mir_description, hir_ty) = match tcx.hir_node(mir_hir_id) { - hir::Node::Expr(hir::Expr { + hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { fn_decl, kind, fn_decl_span, .. }), .. }) => { @@ -873,7 +873,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { .name; let yield_span = match tcx.hir_node(self.mir_hir_id()) { - hir::Node::Expr(hir::Expr { + hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }), .. }) => tcx.sess.source_map().end_point(fn_decl_span), diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index 12ee872d53141..459f4329d6e92 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -183,11 +183,11 @@ fn exported_symbols_provider_local( }); let mut symbols: Vec<_> = - sorted.iter().map(|(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect(); + sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect(); // Export TLS shims if !tcx.sess.target.dll_tls_export { - symbols.extend(sorted.iter().filter_map(|(&def_id, &info)| { + symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| { tcx.needs_thread_local_shim(def_id).then(|| { ( ExportedSymbol::ThreadLocalShim(def_id), diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 3e9dfcea58b8b..286e5e1790858 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -894,7 +894,7 @@ fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option { let [mode, input_activities @ .., ret_activity] = &list[..] else { span_bug!(attr.span, "rustc_autodiff attribute must contain mode and activities"); }; - let mode = if let MetaItemInner::MetaItem(MetaItem { path: ref p1, .. }) = mode { + let mode = if let MetaItemInner::MetaItem(MetaItem { path: p1, .. }) = mode { p1.segments.first().unwrap().ident } else { span_bug!(attr.span, "rustc_autodiff attribute must contain mode"); @@ -910,7 +910,7 @@ fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option { }; // First read the ret symbol from the attribute - let ret_symbol = if let MetaItemInner::MetaItem(MetaItem { path: ref p1, .. }) = ret_activity { + let ret_symbol = if let MetaItemInner::MetaItem(MetaItem { path: p1, .. }) = ret_activity { p1.segments.first().unwrap().ident } else { span_bug!(attr.span, "rustc_autodiff attribute must contain the return activity"); @@ -924,7 +924,7 @@ fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option { // Now parse all the intermediate (input) activities let mut arg_activities: Vec = vec![]; for arg in input_activities { - let arg_symbol = if let MetaItemInner::MetaItem(MetaItem { path: ref p2, .. }) = arg { + let arg_symbol = if let MetaItemInner::MetaItem(MetaItem { path: p2, .. }) = arg { match p2.segments.first() { Some(x) => x.ident, None => { diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 49074996174a7..676a241c74b47 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -720,14 +720,14 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // Put together the arguments to the panic entry point. let (lang_item, args) = match msg { - AssertKind::BoundsCheck { ref len, ref index } => { + AssertKind::BoundsCheck { len, index } => { let len = self.codegen_operand(bx, len).immediate(); let index = self.codegen_operand(bx, index).immediate(); // It's `fn panic_bounds_check(index: usize, len: usize)`, // and `#[track_caller]` adds an implicit third argument. (LangItem::PanicBoundsCheck, vec![index, len, location]) } - AssertKind::MisalignedPointerDereference { ref required, ref found } => { + AssertKind::MisalignedPointerDereference { required, found } => { let required = self.codegen_operand(bx, required).immediate(); let found = self.codegen_operand(bx, found).immediate(); // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`, diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index e7e4dfa05d0c0..461cf1b8acdaf 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -584,7 +584,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // Moves out of scalar and scalar pair fields are trivial. for elem in place_ref.projection.iter() { match elem { - mir::ProjectionElem::Field(ref f, _) => { + mir::ProjectionElem::Field(f, _) => { assert!( !o.layout.ty.is_any_ptr(), "Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \ diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 82e0a6e6666f3..4db862afd9f6d 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -502,12 +502,10 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { RemainderByZero(op) => RemainderByZero(eval_to_int(op)?), ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind), ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind), - MisalignedPointerDereference { ref required, ref found } => { - MisalignedPointerDereference { - required: eval_to_int(required)?, - found: eval_to_int(found)?, - } - } + MisalignedPointerDereference { required, found } => MisalignedPointerDereference { + required: eval_to_int(required)?, + found: eval_to_int(found)?, + }, NullPointerDereference => NullPointerDereference, }; Err(ConstEvalErrKind::AssertFailure(err)).into() diff --git a/compiler/rustc_data_structures/src/sorted_map/tests.rs b/compiler/rustc_data_structures/src/sorted_map/tests.rs index def7a7112fb3f..ea4d2f1feacc0 100644 --- a/compiler/rustc_data_structures/src/sorted_map/tests.rs +++ b/compiler/rustc_data_structures/src/sorted_map/tests.rs @@ -24,7 +24,7 @@ fn test_sorted_index_multi_map() { // `get_by_key` returns items in insertion order. let twos: Vec<_> = set.get_by_key_enumerated(2).collect(); let idxs: Vec = twos.iter().map(|(i, _)| *i).collect(); - let values: Vec = twos.iter().map(|(_, &v)| v).collect(); + let values: Vec = twos.iter().map(|&(_, &v)| v).collect(); assert_eq!(idxs, vec![0, 2, 4]); assert_eq!(values, vec![0, 1, 2]); diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index 595c8c3279f41..b7c85dd4f2c85 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -255,7 +255,7 @@ pub(super) fn transcribe<'a>( } // Replace the meta-var with the matched token tree from the invocation. - mbe::TokenTree::MetaVar(mut sp, mut original_ident) => { + &mbe::TokenTree::MetaVar(mut sp, mut original_ident) => { // Find the matched nonterminal from the macro invocation, and use it to replace // the meta-var. // @@ -339,7 +339,7 @@ pub(super) fn transcribe<'a>( // We will produce all of the results of the inside of the `Delimited` and then we will // jump back out of the Delimited, pop the result_stack and add the new results back to // the previous results (from outside the Delimited). - mbe::TokenTree::Delimited(mut span, spacing, delimited) => { + &mbe::TokenTree::Delimited(mut span, ref spacing, ref delimited) => { mut_visit::visit_delim_span(&mut marker, &mut span); stack.push(Frame::new_delimited(delimited, span, *spacing)); result_stack.push(mem::take(&mut result)); diff --git a/compiler/rustc_hir/src/hir/tests.rs b/compiler/rustc_hir/src/hir/tests.rs index 300d44355303a..f75b9662132e8 100644 --- a/compiler/rustc_hir/src/hir/tests.rs +++ b/compiler/rustc_hir/src/hir/tests.rs @@ -9,11 +9,11 @@ macro_rules! define_tests { let unambig = $kind::$variant::<'_, ()> { $($init)* }; let unambig_to_ambig = unsafe { std::mem::transmute::<_, $kind<'_, AmbigArg>>(unambig) }; - assert!(matches!(&unambig_to_ambig, $kind::$variant { $($init)* })); + assert!(matches!(&unambig_to_ambig, &$kind::$variant { $($init)* })); let ambig_to_unambig = unsafe { std::mem::transmute::<_, $kind<'_, ()>>(unambig_to_ambig) }; - assert!(matches!(&ambig_to_unambig, $kind::$variant { $($init)* })); + assert!(matches!(&ambig_to_unambig, &$kind::$variant { $($init)* })); } )*}; } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index bd96fe9ee32c7..f62ae5ed0d630 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -593,9 +593,9 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) -> V:: defaultness: _, polarity: _, defaultness_span: _, - ref generics, - ref of_trait, - ref self_ty, + generics, + of_trait, + self_ty, items, }) => { try_visit!(visitor.visit_id(item.hir_id())); @@ -1045,7 +1045,7 @@ pub fn walk_generic_param<'v, V: Visitor<'v>>( } GenericParamKind::Const { ref ty, ref default, synthetic: _ } => { try_visit!(visitor.visit_ty_unambig(ty)); - if let Some(ref default) = default { + if let Some(default) = default { try_visit!(visitor.visit_const_param_default(param.hir_id, default)); } } @@ -1401,8 +1401,8 @@ pub fn walk_assoc_item_constraint<'v, V: Visitor<'v>>( try_visit!(visitor.visit_generic_args(constraint.gen_args)); match constraint.kind { AssocItemConstraintKind::Equality { ref term } => match term { - Term::Ty(ref ty) => try_visit!(visitor.visit_ty_unambig(ty)), - Term::Const(ref c) => try_visit!(visitor.visit_const_arg_unambig(c)), + Term::Ty(ty) => try_visit!(visitor.visit_ty_unambig(ty)), + Term::Const(c) => try_visit!(visitor.visit_const_arg_unambig(c)), }, AssocItemConstraintKind::Bound { bounds } => { walk_list!(visitor, visit_param_bound, bounds) diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 717713d93399d..cd5cf3bc2df19 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -106,7 +106,7 @@ fn anon_const_type_of<'tcx>(icx: &ItemCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx } } } - Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => { + Node::Variant(Variant { disr_expr: Some(e), .. }) if e.hir_id == hir_id => { tcx.adt_def(tcx.hir_get_parent_item(hir_id)).repr().discr_type().to_ty(tcx) } // Sort of affects the type system, but only for the purpose of diagnostics diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index fcd0d4d40fd4c..750770178eef9 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -1226,11 +1226,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { adt_def.variants().iter().find(|s| s.name == variant_name) { let mut suggestion = vec![(assoc_ident.span, variant_name.to_string())]; - if let hir::Node::Stmt(hir::Stmt { - kind: hir::StmtKind::Semi(ref expr), - .. + if let hir::Node::Stmt(&hir::Stmt { + kind: hir::StmtKind::Semi(expr), .. }) - | hir::Node::Expr(ref expr) = tcx.parent_hir_node(hir_ref_id) + | hir::Node::Expr(expr) = tcx.parent_hir_node(hir_ref_id) && let hir::ExprKind::Struct(..) = expr.kind { match variant.ctor { diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 34124a6aa11a3..82c4d37405ae5 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -1856,7 +1856,7 @@ impl<'a> State<'a> { self.word_space("="); match term { Term::Ty(ty) => self.print_type(ty), - Term::Const(ref c) => self.print_const_arg(c), + Term::Const(c) => self.print_const_arg(c), } } hir::AssocItemConstraintKind::Bound { bounds } => { diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 5de3c05c63c58..d18869b6d90c3 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -346,7 +346,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; }; - let fn_decl_span = if let hir::Node::Expr(hir::Expr { + let fn_decl_span = if let hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }), .. }) = self.tcx.parent_hir_node(hir_id) @@ -371,7 +371,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // Actually need to unwrap one more layer of HIR to get to // the _real_ closure... - if let hir::Node::Expr(hir::Expr { + if let hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }), .. }) = self.tcx.parent_hir_node(parent_hir_id) diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 625c7f38fbb40..a5108e7a0326d 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1887,7 +1887,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { let parent_id = fcx.tcx.parent_hir_id(block_or_return_id); let parent = fcx.tcx.hir_node(parent_id); if let Some(expr) = expression - && let hir::Node::Expr(hir::Expr { + && let hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { body, .. }), .. }) = parent diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 38c07e473db3b..85131f6195f83 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -577,9 +577,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut parent; 'outer: loop { // Climb the HIR tree to see if the current `Expr` is part of a `break;` statement. - let (hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Semi(&ref p), .. }) - | hir::Node::Block(hir::Block { expr: Some(&ref p), .. }) - | hir::Node::Expr(&ref p)) = self.tcx.hir_node(parent_id) + let (hir::Node::Stmt(&hir::Stmt { kind: hir::StmtKind::Semi(p), .. }) + | hir::Node::Block(&hir::Block { expr: Some(p), .. }) + | hir::Node::Expr(p)) = self.tcx.hir_node(parent_id) else { break; }; @@ -593,13 +593,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { loop { // Climb the HIR tree to find the (desugared) `loop` this `break` corresponds to. let parent = match self.tcx.hir_node(parent_id) { - hir::Node::Expr(&ref parent) => { + hir::Node::Expr(parent) => { parent_id = self.tcx.parent_hir_id(parent.hir_id); parent } hir::Node::Stmt(hir::Stmt { hir_id, - kind: hir::StmtKind::Semi(&ref parent) | hir::StmtKind::Expr(&ref parent), + kind: hir::StmtKind::Semi(parent) | hir::StmtKind::Expr(parent), .. }) => { parent_id = self.tcx.parent_hir_id(*hir_id); diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index e051fc7ac6ca7..759b5d9550c05 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -503,7 +503,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { let unit_errors = remaining_errors_if_fallback_to(self.tcx.types.unit); if unit_errors.is_empty() && let mut never_errors = remaining_errors_if_fallback_to(self.tcx.types.never) - && let [ref mut never_error, ..] = never_errors.as_mut_slice() + && let [never_error, ..] = never_errors.as_mut_slice() { self.adjust_fulfillment_error_for_expr_obligation(never_error); let sugg = self.try_to_suggest_annotations(diverging_vids, coercions); diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index b3e48fd5bb592..f87e5b5202ab5 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -873,7 +873,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { #[instrument(level = "debug", skip(self))] fn assemble_inherent_candidates_from_object(&mut self, self_ty: Ty<'tcx>) { let principal = match self_ty.kind() { - ty::Dynamic(ref data, ..) => Some(data), + ty::Dynamic(data, ..) => Some(data), _ => None, } .and_then(|data| data.principal()) diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index c757d089478f5..8dd8398ba245f 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -1586,10 +1586,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let SelfSource::QPath(ty) = source && let hir::Node::Expr(ref path_expr) = self.tcx.parent_hir_node(ty.hir_id) && let hir::ExprKind::Path(_) = path_expr.kind - && let hir::Node::Stmt(hir::Stmt { - kind: hir::StmtKind::Semi(ref parent), .. - }) - | hir::Node::Expr(ref parent) = self.tcx.parent_hir_node(path_expr.hir_id) + && let hir::Node::Stmt(&hir::Stmt { kind: hir::StmtKind::Semi(parent), .. }) + | hir::Node::Expr(parent) = self.tcx.parent_hir_node(path_expr.hir_id) { let replacement_span = if let hir::ExprKind::Call(..) | hir::ExprKind::Struct(..) = parent.kind { @@ -3149,8 +3147,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut derives_grouped = Vec::<(String, Span, String)>::new(); for (self_name, self_span, trait_name) in derives.into_iter() { - if let Some((last_self_name, _, ref mut last_trait_names)) = derives_grouped.last_mut() - { + if let Some((last_self_name, _, last_trait_names)) = derives_grouped.last_mut() { if last_self_name == &self_name { last_trait_names.push_str(format!(", {trait_name}").as_str()); continue; diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index c56396c38c956..bd0848b991661 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -324,7 +324,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let PatInfo { binding_mode, max_ref_mutbl, top_info: ti, current_depth, .. } = pat_info; let path_res = match pat.kind { - PatKind::Expr(PatExpr { kind: PatExprKind::Path(ref qpath), hir_id, span }) => { + PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => { Some(self.resolve_ty_and_res_fully_qualified_call(qpath, *hir_id, *span)) } _ => None, @@ -344,7 +344,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { PatKind::Wild | PatKind::Err(_) => expected, // We allow any type here; we ensure that the type is uninhabited during match checking. PatKind::Never => expected, - PatKind::Expr(PatExpr { kind: PatExprKind::Path(ref qpath), hir_id, span }) => { + PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => { let ty = self.check_pat_path( *hir_id, pat.hir_id, diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index f12df831cb503..d7d90ea16e497 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -723,7 +723,7 @@ impl ChunkedBitSet { match self.chunks.get(chunk_index) { Some(Zeros(_chunk_domain_size)) => ChunkIter::Zeros, Some(Ones(chunk_domain_size)) => ChunkIter::Ones(0..*chunk_domain_size as usize), - Some(Mixed(chunk_domain_size, _, ref words)) => { + Some(Mixed(chunk_domain_size, _, words)) => { let num_words = num_words(*chunk_domain_size as usize); ChunkIter::Mixed(BitIter::new(&words[0..num_words])) } @@ -752,11 +752,7 @@ impl BitRelations> for ChunkedBitSet { changed = true; } ( - Mixed( - self_chunk_domain_size, - ref mut self_chunk_count, - ref mut self_chunk_words, - ), + Mixed(self_chunk_domain_size, self_chunk_count, self_chunk_words), Mixed(_other_chunk_domain_size, _other_chunk_count, other_chunk_words), ) => { // First check if the operation would change @@ -836,11 +832,7 @@ impl BitRelations> for ChunkedBitSet { Mixed(*self_chunk_domain_size, self_chunk_count, Rc::new(self_chunk_words)); } ( - Mixed( - self_chunk_domain_size, - ref mut self_chunk_count, - ref mut self_chunk_words, - ), + Mixed(self_chunk_domain_size, self_chunk_count, self_chunk_words), Mixed(_other_chunk_domain_size, _other_chunk_count, other_chunk_words), ) => { // See [`>>::union`] for the explanation @@ -891,11 +883,7 @@ impl BitRelations> for ChunkedBitSet { *self_chunk = other_chunk.clone(); } ( - Mixed( - self_chunk_domain_size, - ref mut self_chunk_count, - ref mut self_chunk_words, - ), + Mixed(self_chunk_domain_size, self_chunk_count, self_chunk_words), Mixed(_other_chunk_domain_size, _other_chunk_count, other_chunk_words), ) => { // See [`>>::union`] for the explanation diff --git a/compiler/rustc_lint/src/non_ascii_idents.rs b/compiler/rustc_lint/src/non_ascii_idents.rs index 2f9cf98848e94..66e207a451ef0 100644 --- a/compiler/rustc_lint/src/non_ascii_idents.rs +++ b/compiler/rustc_lint/src/non_ascii_idents.rs @@ -183,7 +183,7 @@ impl EarlyLintPass for NonAsciiIdents { #[allow(rustc::potential_query_instability)] let mut symbols: Vec<_> = symbols.iter().collect(); symbols.sort_by_key(|k| k.1); - for (symbol, &sp) in symbols.iter() { + for &(ref symbol, &sp) in symbols.iter() { let symbol_str = symbol.as_str(); if symbol_str.is_ascii() { continue; @@ -242,7 +242,7 @@ impl EarlyLintPass for NonAsciiIdents { UnordMap::with_capacity(symbols.len()); let mut skeleton_buf = String::new(); - for (&symbol, &sp) in symbols.iter() { + for &(&symbol, &sp) in symbols.iter() { use unicode_security::confusable_detection::skeleton; let symbol_str = symbol.as_str(); @@ -298,7 +298,7 @@ impl EarlyLintPass for NonAsciiIdents { script_states.insert(latin_augmented_script_set, ScriptSetUsage::Verified); let mut has_suspicious = false; - for (symbol, &sp) in symbols.iter() { + for &(ref symbol, &sp) in symbols.iter() { let symbol_str = symbol.as_str(); for ch in symbol_str.chars() { if ch.is_ascii() { diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index 5636f80d60020..bc35e2f0538d0 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -344,7 +344,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { ast::attr::find_by_name(cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name) .and_then(|attr| { if let AttrKind::Normal(n) = &attr.kind - && let AttrItem { args: AttrArgs::Eq { eq_span: _, expr: ref lit }, .. } = + && let AttrItem { args: AttrArgs::Eq { eq_span: _, expr: lit }, .. } = n.as_ref() && let ast::LitKind::Str(name, ..) = lit.kind { diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 7e242a9f56711..fa019a12469bb 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1791,7 +1791,7 @@ impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences { let t = cx.tcx.type_of(it.owner_id).instantiate_identity(); let ty = cx.tcx.erase_regions(t); let Ok(layout) = cx.layout_of(ty) else { return }; - let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, ref variants, .. } = + let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, variants, .. } = &layout.variants else { return; diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 66fdba28502bd..ff3dae08ffc96 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -134,8 +134,8 @@ impl LintExpectationId { } pub fn set_lint_index(&mut self, new_lint_index: Option) { - let (LintExpectationId::Unstable { ref mut lint_index, .. } - | LintExpectationId::Stable { ref mut lint_index, .. }) = self; + let (LintExpectationId::Unstable { lint_index, .. } + | LintExpectationId::Stable { lint_index, .. }) = self; *lint_index = new_lint_index } diff --git a/compiler/rustc_macros/src/diagnostics/utils.rs b/compiler/rustc_macros/src/diagnostics/utils.rs index 612a36ba9aa57..060799e981d46 100644 --- a/compiler/rustc_macros/src/diagnostics/utils.rs +++ b/compiler/rustc_macros/src/diagnostics/utils.rs @@ -760,8 +760,8 @@ impl SubdiagnosticVariant { } ( "applicability", - SubdiagnosticKind::Suggestion { ref mut applicability, .. } - | SubdiagnosticKind::MultipartSuggestion { ref mut applicability, .. }, + SubdiagnosticKind::Suggestion { applicability, .. } + | SubdiagnosticKind::MultipartSuggestion { applicability, .. }, ) => { let value = get_string!(); let value = Applicability::from_str(&value.value()).unwrap_or_else(|()| { diff --git a/compiler/rustc_middle/src/middle/mod.rs b/compiler/rustc_middle/src/middle/mod.rs index 9f71971ea08b1..4587dcaddc487 100644 --- a/compiler/rustc_middle/src/middle/mod.rs +++ b/compiler/rustc_middle/src/middle/mod.rs @@ -25,7 +25,7 @@ pub mod lib_features { self.stability .to_sorted_stable_ord() .iter() - .map(|(&sym, &(stab, _))| (sym, stab)) + .map(|&(&sym, &(stab, _))| (sym, stab)) .collect() } } diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 4a21b6ad23706..58d5c94d03326 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -243,7 +243,7 @@ impl<'tcx> MonoItem<'tcx> { /// Returns the item's `CrateNum` pub fn krate(&self) -> CrateNum { match self { - MonoItem::Fn(ref instance) => instance.def_id().krate, + MonoItem::Fn(instance) => instance.def_id().krate, MonoItem::Static(def_id) => def_id.krate, MonoItem::GlobalAsm(..) => LOCAL_CRATE, } diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 788306a288558..1d61cf48ad263 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -970,7 +970,7 @@ impl<'tcx> TerminatorKind<'tcx> { } FalseEdge { .. } => write!(fmt, "falseEdge"), FalseUnwind { .. } => write!(fmt, "falseUnwind"), - InlineAsm { template, ref operands, options, .. } => { + InlineAsm { template, operands, options, .. } => { write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?; for op in operands { write!(fmt, ", ")?; diff --git a/compiler/rustc_middle/src/mir/terminator.rs b/compiler/rustc_middle/src/mir/terminator.rs index 49e0f619b1ec6..fdfcb128778a7 100644 --- a/compiler/rustc_middle/src/mir/terminator.rs +++ b/compiler/rustc_middle/src/mir/terminator.rs @@ -226,7 +226,7 @@ impl AssertKind { { use AssertKind::*; match self { - BoundsCheck { ref len, ref index } => write!( + BoundsCheck { len, index } => write!( f, "\"index out of bounds: the length is {{}} but the index is {{}}\", {len:?}, {index:?}" ), diff --git a/compiler/rustc_middle/src/mir/visit.rs b/compiler/rustc_middle/src/mir/visit.rs index 98e8f269c57b7..4198b4a338c08 100644 --- a/compiler/rustc_middle/src/mir/visit.rs +++ b/compiler/rustc_middle/src/mir/visit.rs @@ -443,7 +443,7 @@ macro_rules! make_mir_visitor { location ) } - StatementKind::Intrinsic(box ref $($mutability)? intrinsic) => { + StatementKind::Intrinsic(box intrinsic) => { match intrinsic { NonDivergingIntrinsic::Assume(op) => self.visit_operand(op, location), NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping { @@ -886,8 +886,8 @@ macro_rules! make_mir_visitor { self.visit_source_info(source_info); let location = Location::START; if let Some(box VarDebugInfoFragment { - ref $($mutability)? ty, - ref $($mutability)? projection + ty, + projection }) = composite { self.visit_ty($(& $mutability)? *ty, TyContext::Location(location)); for elem in projection { diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 98cc00c367cfe..c67ed356818a5 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -678,8 +678,7 @@ impl<'tcx> Pat<'tcx> { subpatterns.iter().for_each(|field| field.pattern.walk_(it)) } Or { pats } => pats.iter().for_each(|p| p.walk_(it)), - Array { box ref prefix, ref slice, box ref suffix } - | Slice { box ref prefix, ref slice, box ref suffix } => { + Array { box prefix, slice, box suffix } | Slice { box prefix, slice, box suffix } => { prefix.iter().chain(slice.as_deref()).chain(suffix.iter()).for_each(|p| p.walk_(it)) } } diff --git a/compiler/rustc_middle/src/thir/visit.rs b/compiler/rustc_middle/src/thir/visit.rs index 13b8af55e518e..afe24b55a8372 100644 --- a/compiler/rustc_middle/src/thir/visit.rs +++ b/compiler/rustc_middle/src/thir/visit.rs @@ -194,7 +194,7 @@ pub fn walk_stmt<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( initializer, remainder_scope: _, init_scope: _, - ref pattern, + pattern, lint_level: _, else_block, span: _, diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 53bc9eb7e466c..51420400b102e 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -786,7 +786,7 @@ impl DynCompatibilityViolation { pub fn error_msg(&self) -> Cow<'static, str> { match self { DynCompatibilityViolation::SizedSelf(_) => "it requires `Self: Sized`".into(), - DynCompatibilityViolation::SupertraitSelf(ref spans) => { + DynCompatibilityViolation::SupertraitSelf(spans) => { if spans.iter().any(|sp| *sp != DUMMY_SP) { "it uses `Self` as a type parameter".into() } else { diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index b2286c744020f..db9e9fbc643b2 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -447,23 +447,23 @@ impl<'tcx> TypeSuperVisitable> for Ty<'tcx> { } ty::Slice(typ) => typ.visit_with(visitor), ty::Adt(_, args) => args.visit_with(visitor), - ty::Dynamic(ref trait_ty, ref reg, _) => { + ty::Dynamic(trait_ty, reg, _) => { try_visit!(trait_ty.visit_with(visitor)); reg.visit_with(visitor) } ty::Tuple(ts) => ts.visit_with(visitor), ty::FnDef(_, args) => args.visit_with(visitor), - ty::FnPtr(ref sig_tys, _) => sig_tys.visit_with(visitor), - ty::UnsafeBinder(ref f) => f.visit_with(visitor), + ty::FnPtr(sig_tys, _) => sig_tys.visit_with(visitor), + ty::UnsafeBinder(f) => f.visit_with(visitor), ty::Ref(r, ty, _) => { try_visit!(r.visit_with(visitor)); ty.visit_with(visitor) } - ty::Coroutine(_did, ref args) => args.visit_with(visitor), - ty::CoroutineWitness(_did, ref args) => args.visit_with(visitor), - ty::Closure(_did, ref args) => args.visit_with(visitor), - ty::CoroutineClosure(_did, ref args) => args.visit_with(visitor), - ty::Alias(_, ref data) => data.visit_with(visitor), + ty::Coroutine(_did, args) => args.visit_with(visitor), + ty::CoroutineWitness(_did, args) => args.visit_with(visitor), + ty::Closure(_did, args) => args.visit_with(visitor), + ty::CoroutineClosure(_did, args) => args.visit_with(visitor), + ty::Alias(_, data) => data.visit_with(visitor), ty::Pat(ty, pat) => { try_visit!(ty.visit_with(visitor)); diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 8a31b2960188e..4a97b5d475fae 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1121,7 +1121,7 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn is_param(self, index: u32) -> bool { match self.kind() { - ty::Param(ref data) => data.index == index, + ty::Param(data) => data.index == index, _ => false, } } diff --git a/compiler/rustc_mir_build/src/builder/block.rs b/compiler/rustc_mir_build/src/builder/block.rs index 93ee90011a581..7c76e02fcef6a 100644 --- a/compiler/rustc_mir_build/src/builder/block.rs +++ b/compiler/rustc_mir_build/src/builder/block.rs @@ -244,7 +244,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { StmtKind::Let { remainder_scope, init_scope, - ref pattern, + pattern, initializer, lint_level, else_block: None, diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index d0fca76fcf05d..eb00b95f3c83f 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -429,9 +429,7 @@ impl<'tcx> ThirBuildCx<'tcx> { let user_provided_types = self.typeck_results.user_provided_types(); let user_ty = user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| { - if let ty::UserTypeKind::TypeOf(ref mut did, _) = - &mut u_ty.value.kind - { + if let ty::UserTypeKind::TypeOf(did, _) = &mut u_ty.value.kind { *did = adt_def.did(); } Box::new(u_ty) diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 18305db28c281..d60ae6484afb2 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -1097,7 +1097,7 @@ fn find_fallback_pattern_typo<'tcx>( } } if let Some((i, &const_name)) = - accessible.iter().enumerate().find(|(_, &const_name)| const_name == name) + accessible.iter().enumerate().find(|&(_, &const_name)| const_name == name) { // The pattern name is an exact match, so the pattern needed to be imported. lint.wanted_constant = Some(WantedConstant { @@ -1115,7 +1115,7 @@ fn find_fallback_pattern_typo<'tcx>( const_path: name.to_string(), }); } else if let Some(i) = - imported.iter().enumerate().find(|(_, &const_name)| const_name == name).map(|(i, _)| i) + imported.iter().enumerate().find(|&(_, &const_name)| const_name == name).map(|(i, _)| i) { // The const with the exact name wasn't re-exported from an import in this // crate, we point at the import. diff --git a/compiler/rustc_mir_build/src/thir/util.rs b/compiler/rustc_mir_build/src/thir/util.rs index 4dff093afd0d9..60a47a94e3a1f 100644 --- a/compiler/rustc_mir_build/src/thir/util.rs +++ b/compiler/rustc_mir_build/src/thir/util.rs @@ -16,7 +16,7 @@ pub(crate) fn user_args_applied_to_ty_of_hir_id<'tcx>( let ty = typeck_results.node_type(hir_id); match ty.kind() { ty::Adt(adt_def, ..) => { - if let ty::UserTypeKind::TypeOf(ref mut did, _) = &mut user_ty.value.kind { + if let ty::UserTypeKind::TypeOf(did, _) = &mut user_ty.value.kind { *did = adt_def.did(); } Some(user_ty) diff --git a/compiler/rustc_mir_dataflow/src/un_derefer.rs b/compiler/rustc_mir_dataflow/src/un_derefer.rs index b803ecc575ee0..bb15b8106a1e4 100644 --- a/compiler/rustc_mir_dataflow/src/un_derefer.rs +++ b/compiler/rustc_mir_dataflow/src/un_derefer.rs @@ -91,7 +91,7 @@ impl SlicePlusOne<'_, T> { #[inline] fn advance(&mut self) { match self.slice { - [_, ref remainder @ ..] => { + [_, remainder @ ..] => { self.slice = remainder; } [] => self.last = None, diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 104a2e8c09100..9cba07e15a43b 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -125,7 +125,7 @@ impl State { pub fn all_bottom(&self) -> bool { match self { State::Unreachable => false, - State::Reachable(ref values) => + State::Reachable(values) => { #[allow(rustc::potential_query_instability)] values.map.values().all(V::is_bottom) @@ -349,7 +349,7 @@ impl JoinSemiLattice for State { *self = other.clone(); true } - (State::Reachable(this), State::Reachable(ref other)) => this.join(other), + (State::Reachable(this), State::Reachable(other)) => this.join(other), } } } diff --git a/compiler/rustc_mir_transform/src/jump_threading.rs b/compiler/rustc_mir_transform/src/jump_threading.rs index 17084eca6e388..bd310b0789756 100644 --- a/compiler/rustc_mir_transform/src/jump_threading.rs +++ b/compiler/rustc_mir_transform/src/jump_threading.rs @@ -467,7 +467,7 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { state.insert_place_idx(rhs, lhs, &self.map); } // If we expect `lhs ?= A`, we have an opportunity if we assume `constant == A`. - Rvalue::Aggregate(box ref kind, ref operands) => { + Rvalue::Aggregate(box kind, operands) => { let agg_ty = lhs_place.ty(self.body, self.tcx).ty; let lhs = match kind { // Do not support unions. diff --git a/compiler/rustc_mir_transform/src/known_panics_lint.rs b/compiler/rustc_mir_transform/src/known_panics_lint.rs index 59de6ca84a71b..f8db8de4e82c9 100644 --- a/compiler/rustc_mir_transform/src/known_panics_lint.rs +++ b/compiler/rustc_mir_transform/src/known_panics_lint.rs @@ -509,7 +509,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { // other overflow checks. AssertKind::Overflow(*bin_op, eval_to_int(op1), eval_to_int(op2)) } - AssertKind::BoundsCheck { ref len, ref index } => { + AssertKind::BoundsCheck { len, index } => { let len = eval_to_int(len); let index = eval_to_int(index); AssertKind::BoundsCheck { len, index } @@ -782,10 +782,10 @@ impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> { fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { self.super_terminator(terminator, location); match &terminator.kind { - TerminatorKind::Assert { expected, ref msg, ref cond, .. } => { + TerminatorKind::Assert { expected, msg, cond, .. } => { self.check_assertion(*expected, msg, cond, location); } - TerminatorKind::SwitchInt { ref discr, ref targets } => { + TerminatorKind::SwitchInt { discr, targets } => { if let Some(ref value) = self.eval_operand(discr) && let Some(value_const) = self.use_ecx(|this| this.ecx.read_scalar(value)) && let Some(constant) = value_const.to_bits(value_const.size()).discard_err() diff --git a/compiler/rustc_mir_transform/src/mentioned_items.rs b/compiler/rustc_mir_transform/src/mentioned_items.rs index f5c57418467a1..9fd8d81d64a26 100644 --- a/compiler/rustc_mir_transform/src/mentioned_items.rs +++ b/compiler/rustc_mir_transform/src/mentioned_items.rs @@ -51,7 +51,7 @@ impl<'tcx> Visitor<'tcx> for MentionedItemsVisitor<'_, 'tcx> { let ty = place.ty(self.body, self.tcx).ty; self.mentioned_items.push(Spanned { node: MentionedItem::Drop(ty), span: span() }); } - mir::TerminatorKind::InlineAsm { ref operands, .. } => { + mir::TerminatorKind::InlineAsm { operands, .. } => { for op in operands { match *op { mir::InlineAsmOperand::SymFn { ref value } => { diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index 67070f03dedbd..84905f4a400f3 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -568,9 +568,9 @@ fn remove_unused_definitions_helper(used_locals: &mut UsedLocals, body: &mut Bod } StatementKind::Assign(box (place, _)) => used_locals.is_used(place.local), - StatementKind::SetDiscriminant { ref place, .. } - | StatementKind::BackwardIncompatibleDropHint { ref place, reason: _ } - | StatementKind::Deinit(ref place) => used_locals.is_used(place.local), + StatementKind::SetDiscriminant { place, .. } + | StatementKind::BackwardIncompatibleDropHint { place, reason: _ } + | StatementKind::Deinit(place) => used_locals.is_used(place.local), StatementKind::Nop => false, _ => true, }; diff --git a/compiler/rustc_mir_transform/src/simplify_branches.rs b/compiler/rustc_mir_transform/src/simplify_branches.rs index 12c3503879fb9..886f4d6e50900 100644 --- a/compiler/rustc_mir_transform/src/simplify_branches.rs +++ b/compiler/rustc_mir_transform/src/simplify_branches.rs @@ -24,7 +24,7 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyConstCondition { // Simplify `assume` of a known value: either a NOP or unreachable. if let StatementKind::Intrinsic(box ref intrinsic) = stmt.kind && let NonDivergingIntrinsic::Assume(discr) = intrinsic - && let Operand::Constant(ref c) = discr + && let Operand::Constant(c) = discr && let Some(constant) = c.const_.try_eval_bool(tcx, typing_env) { if constant { diff --git a/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs index 21bc51ecca14e..bd00823073139 100644 --- a/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs +++ b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs @@ -89,10 +89,10 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyComparisonIntegral { use Operand::*; match rhs { - Rvalue::BinaryOp(_, box (ref mut left @ Move(_), Constant(_))) => { + Rvalue::BinaryOp(_, box (left @ Move(_), Constant(_))) => { *left = Copy(opt.to_switch_on); } - Rvalue::BinaryOp(_, box (Constant(_), ref mut right @ Move(_))) => { + Rvalue::BinaryOp(_, box (Constant(_), right @ Move(_))) => { *right = Copy(opt.to_switch_on); } _ => (), diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index d826d03918e08..b1b6f10e0fe2c 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -1269,7 +1269,7 @@ fn dump_mono_items_stats<'tcx>( output_directory: &Option, crate_name: Symbol, ) -> Result<(), Box> { - let output_directory = if let Some(ref directory) = output_directory { + let output_directory = if let Some(directory) = output_directory { fs::create_dir_all(directory)?; directory } else { diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 7b4fecf2ed193..7a14a7a5db299 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -184,7 +184,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { rhs: &'tcx hir::Expr<'tcx>, ) -> bool { match (&lhs.kind, &rhs.kind) { - (hir::ExprKind::Path(ref qpath_l), hir::ExprKind::Path(ref qpath_r)) => { + (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => { if let (Res::Local(id_l), Res::Local(id_r)) = ( typeck_results.qpath_res(qpath_l, lhs.hir_id), typeck_results.qpath_res(qpath_r, rhs.hir_id), diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 4124e8a4dd1f8..d92edf959aff4 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -780,11 +780,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { // individually as it's possible to have a stable trait with unstable // items. hir::ItemKind::Impl(hir::Impl { - of_trait: Some(ref t), - self_ty, - items, - constness, - .. + of_trait: Some(t), self_ty, items, constness, .. }) => { let features = self.tcx.features(); if features.staged_api() { diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 46e52e1f131b0..6b8a7493cd429 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -98,13 +98,13 @@ impl<'ra> std::fmt::Debug for ImportKind<'ra> { use ImportKind::*; match self { Single { - ref source, - ref target, - ref source_bindings, - ref target_bindings, - ref type_ns_only, - ref nested, - ref id, + source, + target, + source_bindings, + target_bindings, + type_ns_only, + nested, + id, } => f .debug_struct("Single") .field("source", source) @@ -122,13 +122,13 @@ impl<'ra> std::fmt::Debug for ImportKind<'ra> { .field("nested", nested) .field("id", id) .finish(), - Glob { ref is_prelude, ref max_vis, ref id } => f + Glob { is_prelude, max_vis, id } => f .debug_struct("Glob") .field("is_prelude", is_prelude) .field("max_vis", max_vis) .field("id", id) .finish(), - ExternCrate { ref source, ref target, ref id } => f + ExternCrate { source, target, id } => f .debug_struct("ExternCrate") .field("source", source) .field("target", target) diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 03aeb8720ca62..ad9c3465f0cc6 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1191,7 +1191,7 @@ impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'r debug!("visit_generic_arg({:?})", arg); let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true); match arg { - GenericArg::Type(ref ty) => { + GenericArg::Type(ty) => { // We parse const arguments as path types as we cannot distinguish them during // parsing. We try to resolve that ambiguity by attempting resolution the type // namespace first, and if that fails we try again in the value namespace. If @@ -1583,7 +1583,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { this.visit_param_bound(bound, BoundKind::Bound); } - if let Some(ref ty) = default { + if let Some(ty) = default { this.ribs[TypeNS].push(forward_ty_ban_rib); this.ribs[ValueNS].push(forward_const_ban_rib); this.visit_ty(ty); @@ -1608,7 +1608,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { this.ribs[TypeNS].pop().unwrap(); this.ribs[ValueNS].pop().unwrap(); - if let Some(ref expr) = default { + if let Some(expr) = default { this.ribs[TypeNS].push(forward_ty_ban_rib); this.ribs[ValueNS].push(forward_const_ban_rib); this.resolve_anon_const( @@ -5044,16 +5044,16 @@ impl ItemInfoCollector<'_, '_, '_> { impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> { fn visit_item(&mut self, item: &'ast Item) { match &item.kind { - ItemKind::TyAlias(box TyAlias { ref generics, .. }) - | ItemKind::Const(box ConstItem { ref generics, .. }) - | ItemKind::Fn(box Fn { ref generics, .. }) - | ItemKind::Enum(_, ref generics) - | ItemKind::Struct(_, ref generics) - | ItemKind::Union(_, ref generics) - | ItemKind::Impl(box Impl { ref generics, .. }) - | ItemKind::Trait(box Trait { ref generics, .. }) - | ItemKind::TraitAlias(ref generics, _) => { - if let ItemKind::Fn(box Fn { ref sig, .. }) = &item.kind { + ItemKind::TyAlias(box TyAlias { generics, .. }) + | ItemKind::Const(box ConstItem { generics, .. }) + | ItemKind::Fn(box Fn { generics, .. }) + | ItemKind::Enum(_, generics) + | ItemKind::Struct(_, generics) + | ItemKind::Union(_, generics) + | ItemKind::Impl(box Impl { generics, .. }) + | ItemKind::Trait(box Trait { generics, .. }) + | ItemKind::TraitAlias(generics, _) => { + if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind { self.collect_fn_info(sig, item.id, &item.attrs); } @@ -5086,7 +5086,7 @@ impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> { } fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) { - if let AssocItemKind::Fn(box Fn { ref sig, .. }) = &item.kind { + if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind { self.collect_fn_info(sig, item.id, &item.attrs); } visit::walk_assoc_item(self, item, ctxt); diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index b37c684a0556a..fa9c42e359333 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -516,7 +516,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let Some(params) = &segment.args else { continue; }; - let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { + let ast::GenericArgs::AngleBracketed(params) = params.deref() else { continue; }; for param in ¶ms.args { @@ -1668,7 +1668,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { ); } if let PathSource::Expr(Some(Expr { - kind: ExprKind::Call(path, ref args), + kind: ExprKind::Call(path, args), span: call_span, .. })) = source @@ -1802,7 +1802,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { } // e.g. `let _ = Enum::TupleVariant(field1, field2);` PathSource::Expr(Some(Expr { - kind: ExprKind::Call(path, ref args), + kind: ExprKind::Call(path, args), span: call_span, .. })) => { diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index c4d45ee02eea1..8e5ff1d3bc48e 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1019,8 +1019,7 @@ pub fn build_session( let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile { - let directory = - if let Some(ref directory) = d { directory } else { std::path::Path::new(".") }; + let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") }; let profiler = SelfProfiler::new( directory, diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 695edc956cdb5..c09669d959c93 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -404,7 +404,7 @@ impl fmt::Display for FileNameDisplay<'_> { impl<'a> FileNameDisplay<'a> { pub fn to_string_lossy(&self) -> Cow<'a, str> { match self.inner { - FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), + FileName::Real(inner) => inner.to_string_lossy(self.display_pref), _ => Cow::from(self.to_string()), } } @@ -1442,7 +1442,7 @@ pub enum ExternalSourceKind { impl ExternalSource { pub fn get_source(&self) -> Option<&str> { match self { - ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), + ExternalSource::Foreign { kind: ExternalSourceKind::Present(src), .. } => Some(src), _ => None, } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs index a87a449daf1c7..a7e68e6419d84 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs @@ -237,7 +237,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { Some(ConsiderAddingAwait::FutureSugg { span: then_span.shrink_to_hi() }) } ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause { - ref prior_non_diverging_arms, + prior_non_diverging_arms, .. }) => Some({ ConsiderAddingAwait::FutureSuggMultiple { diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index a8ee4d61e65ed..a666911dc5d09 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -2357,7 +2357,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { obligated_types: &mut Vec>, cause_code: &ObligationCauseCode<'tcx>, ) -> bool { - if let ObligationCauseCode::BuiltinDerived(ref data) = cause_code { + if let ObligationCauseCode::BuiltinDerived(data) = cause_code { let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred); let self_ty = parent_trait_ref.skip_binder().self_ty(); if obligated_types.iter().any(|ot| ot == &self_ty) { diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 6eeb47a21f8dd..efd2d7cdb6aa2 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -974,7 +974,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { hir::ExprKind::MethodCall( hir::PathSegment { ident, .. }, _receiver, - &[], + [], call_span, ), hir_id, diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index e8d30d3ee7996..96eaf225159d4 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -509,21 +509,18 @@ impl Subdiagnostic for AddLifetimeParamsSuggestion<'_> { let node = self.tcx.hir_node_by_def_id(anon_reg.scope); let is_impl = matches!(&node, hir::Node::ImplItem(_)); let (generics, parent_generics) = match node { - hir::Node::Item(&hir::Item { - kind: hir::ItemKind::Fn { ref generics, .. }, - .. - }) - | hir::Node::TraitItem(&hir::TraitItem { ref generics, .. }) - | hir::Node::ImplItem(&hir::ImplItem { ref generics, .. }) => ( + hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { generics, .. }, .. }) + | hir::Node::TraitItem(hir::TraitItem { generics, .. }) + | hir::Node::ImplItem(hir::ImplItem { generics, .. }) => ( generics, match self.tcx.parent_hir_node(self.tcx.local_def_id_to_hir_id(anon_reg.scope)) { hir::Node::Item(hir::Item { - kind: hir::ItemKind::Trait(_, _, ref generics, ..), + kind: hir::ItemKind::Trait(_, _, generics, ..), .. }) | hir::Node::Item(hir::Item { - kind: hir::ItemKind::Impl(hir::Impl { ref generics, .. }), + kind: hir::ItemKind::Impl(hir::Impl { generics, .. }), .. }) => Some(generics), _ => None, diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index c238e708ab8fa..51d560d4c43d3 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -67,7 +67,9 @@ impl<'tcx> ObligationStorage<'tcx> { obligations } - fn unstalled_for_select(&mut self) -> impl Iterator> { + fn unstalled_for_select( + &mut self, + ) -> impl Iterator> + use<'tcx> { mem::take(&mut self.pending).into_iter() } diff --git a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs index efe2386d014b3..740f44ebcade2 100644 --- a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs +++ b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs @@ -698,11 +698,11 @@ impl<'tcx> TypeVisitor> for IllegalSelfTypeVisitor<'tcx> { ControlFlow::Continue(()) } } - ty::Alias(ty::Projection, ref data) if self.tcx.is_impl_trait_in_trait(data.def_id) => { + ty::Alias(ty::Projection, data) if self.tcx.is_impl_trait_in_trait(data.def_id) => { // We'll deny these later in their own pass ControlFlow::Continue(()) } - ty::Alias(ty::Projection, ref data) => { + ty::Alias(ty::Projection, data) => { match self.allow_self_projections { AllowSelfProjections::Yes => { // This is a projected type `::X`. From fd451dc057d7332e2e40f0625e865ea5e757d000 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Fri, 21 Feb 2025 21:36:58 -0500 Subject: [PATCH 19/20] Use StableHasher + Hash64 for dep_tracking_hash --- Cargo.lock | 1 + compiler/rustc_incremental/Cargo.toml | 1 + .../rustc_incremental/src/persist/load.rs | 3 ++- compiler/rustc_session/src/config.rs | 21 ++++++++++--------- compiler/rustc_session/src/options.rs | 10 ++++----- 5 files changed, 20 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6bc88fb7a6dc8..4401489813a40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3779,6 +3779,7 @@ dependencies = [ "rustc_fluent_macro", "rustc_fs_util", "rustc_graphviz", + "rustc_hashes", "rustc_hir", "rustc_macros", "rustc_middle", diff --git a/compiler/rustc_incremental/Cargo.toml b/compiler/rustc_incremental/Cargo.toml index 46a63b02e8469..83d163da4839d 100644 --- a/compiler/rustc_incremental/Cargo.toml +++ b/compiler/rustc_incremental/Cargo.toml @@ -12,6 +12,7 @@ rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_fs_util = { path = "../rustc_fs_util" } rustc_graphviz = { path = "../rustc_graphviz" } +rustc_hashes = { path = "../rustc_hashes" } rustc_hir = { path = "../rustc_hir" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } diff --git a/compiler/rustc_incremental/src/persist/load.rs b/compiler/rustc_incremental/src/persist/load.rs index 7977bcc68911d..50e47533ab6ca 100644 --- a/compiler/rustc_incremental/src/persist/load.rs +++ b/compiler/rustc_incremental/src/persist/load.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use rustc_data_structures::memmap::Mmap; use rustc_data_structures::unord::UnordMap; +use rustc_hashes::Hash64; use rustc_middle::dep_graph::{DepGraph, DepsType, SerializedDepGraph, WorkProductMap}; use rustc_middle::query::on_disk_cache::OnDiskCache; use rustc_serialize::Decodable; @@ -154,7 +155,7 @@ fn load_dep_graph(sess: &Session) -> LoadResult<(Arc, WorkPr sess.dcx().emit_warn(errors::CorruptFile { path: &path }); return LoadResult::DataOutOfDate; }; - let prev_commandline_args_hash = u64::decode(&mut decoder); + let prev_commandline_args_hash = Hash64::decode(&mut decoder); if prev_commandline_args_hash != expected_hash { if sess.opts.unstable_opts.incremental_info { diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 85ef69ea2b746..6f8da1785f434 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -2928,12 +2928,13 @@ pub enum WasiExecModel { /// how the hash should be calculated when adding a new command-line argument. pub(crate) mod dep_tracking { use std::collections::BTreeMap; - use std::hash::{DefaultHasher, Hash}; + use std::hash::Hash; use std::num::NonZero; use std::path::PathBuf; use rustc_abi::Align; use rustc_data_structures::fx::FxIndexMap; + use rustc_data_structures::stable_hasher::StableHasher; use rustc_errors::LanguageIdentifier; use rustc_feature::UnstableFeatures; use rustc_hashes::Hash64; @@ -2960,7 +2961,7 @@ pub(crate) mod dep_tracking { pub(crate) trait DepTrackingHash { fn hash( &self, - hasher: &mut DefaultHasher, + hasher: &mut StableHasher, error_format: ErrorOutputType, for_crate_hash: bool, ); @@ -2969,7 +2970,7 @@ pub(crate) mod dep_tracking { macro_rules! impl_dep_tracking_hash_via_hash { ($($t:ty),+ $(,)?) => {$( impl DepTrackingHash for $t { - fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType, _for_crate_hash: bool) { + fn hash(&self, hasher: &mut StableHasher, _: ErrorOutputType, _for_crate_hash: bool) { Hash::hash(self, hasher); } } @@ -2979,7 +2980,7 @@ pub(crate) mod dep_tracking { impl DepTrackingHash for Option { fn hash( &self, - hasher: &mut DefaultHasher, + hasher: &mut StableHasher, error_format: ErrorOutputType, for_crate_hash: bool, ) { @@ -3064,7 +3065,7 @@ pub(crate) mod dep_tracking { { fn hash( &self, - hasher: &mut DefaultHasher, + hasher: &mut StableHasher, error_format: ErrorOutputType, for_crate_hash: bool, ) { @@ -3083,7 +3084,7 @@ pub(crate) mod dep_tracking { { fn hash( &self, - hasher: &mut DefaultHasher, + hasher: &mut StableHasher, error_format: ErrorOutputType, for_crate_hash: bool, ) { @@ -3099,7 +3100,7 @@ pub(crate) mod dep_tracking { impl DepTrackingHash for Vec { fn hash( &self, - hasher: &mut DefaultHasher, + hasher: &mut StableHasher, error_format: ErrorOutputType, for_crate_hash: bool, ) { @@ -3114,7 +3115,7 @@ pub(crate) mod dep_tracking { impl DepTrackingHash for FxIndexMap { fn hash( &self, - hasher: &mut DefaultHasher, + hasher: &mut StableHasher, error_format: ErrorOutputType, for_crate_hash: bool, ) { @@ -3129,7 +3130,7 @@ pub(crate) mod dep_tracking { impl DepTrackingHash for OutputTypes { fn hash( &self, - hasher: &mut DefaultHasher, + hasher: &mut StableHasher, error_format: ErrorOutputType, for_crate_hash: bool, ) { @@ -3146,7 +3147,7 @@ pub(crate) mod dep_tracking { // This is a stable hash because BTreeMap is a sorted container pub(crate) fn stable_hash( sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>, - hasher: &mut DefaultHasher, + hasher: &mut StableHasher, error_format: ErrorOutputType, for_crate_hash: bool, ) { diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 351dad3f3e422..ecd6ced622d66 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1,5 +1,4 @@ use std::collections::BTreeMap; -use std::hash::{DefaultHasher, Hasher}; use std::num::{IntErrorKind, NonZero}; use std::path::PathBuf; use std::str; @@ -7,6 +6,7 @@ use std::str; use rustc_abi::Align; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::profiling::TimePassesFormat; +use rustc_data_structures::stable_hasher::StableHasher; use rustc_errors::{ColorConfig, LanguageIdentifier, TerminalUrl}; use rustc_feature::UnstableFeatures; use rustc_hashes::Hash64; @@ -251,7 +251,7 @@ macro_rules! top_level_options { } impl Options { - pub fn dep_tracking_hash(&self, for_crate_hash: bool) -> u64 { + pub fn dep_tracking_hash(&self, for_crate_hash: bool) -> Hash64 { let mut sub_hashes = BTreeMap::new(); $({ hash_opt!($opt, @@ -260,7 +260,7 @@ macro_rules! top_level_options { for_crate_hash, [$dep_tracking_marker]); })* - let mut hasher = DefaultHasher::new(); + let mut hasher = StableHasher::new(); dep_tracking::stable_hash(sub_hashes, &mut hasher, self.error_format, @@ -545,7 +545,7 @@ macro_rules! options { build_options(early_dcx, matches, target_modifiers, $stat, $prefix, $outputname) } - fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> u64 { + fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> Hash64 { let mut sub_hashes = BTreeMap::new(); $({ hash_opt!($opt, @@ -554,7 +554,7 @@ macro_rules! options { for_crate_hash, [$dep_tracking_marker]); })* - let mut hasher = DefaultHasher::new(); + let mut hasher = StableHasher::new(); dep_tracking::stable_hash(sub_hashes, &mut hasher, error_format, From f0ced81439d7ebf1cb6a49ff870a14c2f301af54 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Fri, 21 Feb 2025 21:12:39 -0800 Subject: [PATCH 20/20] jubilee cleared out the review queue --- triagebot.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/triagebot.toml b/triagebot.toml index 31061bd288ef9..f9eb09ff34381 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1081,7 +1081,6 @@ warn_non_default_branch.enable = true contributing_url = "https://rustc-dev-guide.rust-lang.org/getting-started.html" users_on_vacation = [ "jyn514", - "workingjubilee", ] [[assign.warn_non_default_branch.exceptions]]