From 7b7ee8463f0b21e7cf2c6dc57ea8c026bc2f5829 Mon Sep 17 00:00:00 2001 From: Redddy Date: Sun, 21 Dec 2025 00:26:51 +0900 Subject: [PATCH 001/146] Add title field to ICE issue template --- .github/ISSUE_TEMPLATE/ice.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/ISSUE_TEMPLATE/ice.md b/.github/ISSUE_TEMPLATE/ice.md index 2afcd210a6eb..1ab1ddf46016 100644 --- a/.github/ISSUE_TEMPLATE/ice.md +++ b/.github/ISSUE_TEMPLATE/ice.md @@ -2,6 +2,7 @@ name: Internal Compiler Error about: Create a report for an internal compiler error in rustc. labels: C-bug, I-ICE, T-compiler +title: "[ICE]: " --- $DIR/cast-with-type-mismatched.rs:6:30 + | +LL | fn foo(a: [(); N as usize]) {} + | ^^^^^^^^^^ + +error: the constant `C` is not of type `u32` + --> $DIR/cast-with-type-mismatched.rs:12:11 + | +LL | foo::([]); + | ^ expected `u32`, found `f32` + | +note: required by a const generic parameter in `foo` + --> $DIR/cast-with-type-mismatched.rs:6:8 + | +LL | fn foo(a: [(); N as usize]) {} + | ^^^^^^^^^^^^ required by this const generic parameter in `foo` + +error: aborting due to 2 previous errors + diff --git a/tests/ui/const-generics/mgca/const-eval-with-invalid-args.rs b/tests/ui/const-generics/mgca/const-eval-with-invalid-args.rs new file mode 100644 index 000000000000..3bf951e0c212 --- /dev/null +++ b/tests/ui/const-generics/mgca/const-eval-with-invalid-args.rs @@ -0,0 +1,26 @@ +//! regression test for +#![expect(incomplete_features)] +#![feature(generic_const_exprs)] +#![feature(min_generic_const_args)] + +// The previous ICE was an "invalid field access on immediate". +// If we remove `val: i32` from the field, another ICE occurs. +// "assertion `left == right` failed: invalid field type in +// Immediate::offset: scalar value has wrong size" +struct A { + arr: usize, + val: i32, +} + +struct B { + //~^ ERROR: `A` is forbidden as the type of a const generic parameter + arr: [u8; N.arr], + //~^ ERROR: complex const arguments must be placed inside of a `const` block +} + +const C: u32 = 1; +fn main() { + let b = B:: {arr: [1]}; + //~^ ERROR: the constant `C` is not of type `A` + let _ = b.arr.len(); +} diff --git a/tests/ui/const-generics/mgca/const-eval-with-invalid-args.stderr b/tests/ui/const-generics/mgca/const-eval-with-invalid-args.stderr new file mode 100644 index 000000000000..a226718ccf1b --- /dev/null +++ b/tests/ui/const-generics/mgca/const-eval-with-invalid-args.stderr @@ -0,0 +1,32 @@ +error: complex const arguments must be placed inside of a `const` block + --> $DIR/const-eval-with-invalid-args.rs:17:15 + | +LL | arr: [u8; N.arr], + | ^^^^^ + +error: `A` is forbidden as the type of a const generic parameter + --> $DIR/const-eval-with-invalid-args.rs:15:19 + | +LL | struct B { + | ^ + | + = note: the only supported types are integers, `bool`, and `char` +help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types + | +LL + #![feature(adt_const_params)] + | + +error: the constant `C` is not of type `A` + --> $DIR/const-eval-with-invalid-args.rs:23:17 + | +LL | let b = B:: {arr: [1]}; + | ^ expected `A`, found `u32` + | +note: required by a const generic parameter in `B` + --> $DIR/const-eval-with-invalid-args.rs:15:10 + | +LL | struct B { + | ^^^^^^^^^^ required by this const generic parameter in `B` + +error: aborting due to 3 previous errors + diff --git a/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.rs b/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.rs new file mode 100644 index 000000000000..37dcc58ff468 --- /dev/null +++ b/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.rs @@ -0,0 +1,11 @@ +//! regression test for +#![expect(incomplete_features)] +#![feature(generic_const_exprs)] +#![feature(min_generic_const_args)] + +fn identity }>() }>>(); +//~^ ERROR: free function without a body +//~| ERROR: expected type, found function `identity` +//~| ERROR: complex const arguments must be placed inside of a `const` block + +fn main() {} diff --git a/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.stderr b/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.stderr new file mode 100644 index 000000000000..d1899c476ec6 --- /dev/null +++ b/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.stderr @@ -0,0 +1,23 @@ +error: free function without a body + --> $DIR/recursive-self-referencing-const-param.rs:6:1 + | +LL | fn identity }>() }>>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- + | | + | help: provide a definition for the function: `{ }` + +error[E0573]: expected type, found function `identity` + --> $DIR/recursive-self-referencing-const-param.rs:6:22 + | +LL | fn identity }>() }>>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not a type + +error: complex const arguments must be placed inside of a `const` block + --> $DIR/recursive-self-referencing-const-param.rs:6:57 + | +LL | fn identity }>() }>>(); + | ^^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0573`. diff --git a/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.rs b/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.rs new file mode 100644 index 000000000000..2a7c23929845 --- /dev/null +++ b/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.rs @@ -0,0 +1,10 @@ +//! regression test for +#![expect(incomplete_features)] +#![feature(min_generic_const_args)] + +fn foo() { + [0; size_of::<*mut T>()]; + //~^ ERROR: tuple constructor with invalid base path +} + +fn main() {} diff --git a/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.stderr b/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.stderr new file mode 100644 index 000000000000..dcdc56a1cf47 --- /dev/null +++ b/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.stderr @@ -0,0 +1,8 @@ +error: tuple constructor with invalid base path + --> $DIR/size-of-generic-ptr-in-array-len.rs:6:9 + | +LL | [0; size_of::<*mut T>()]; + | ^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + From 112317749850f1c3f09f9ee9b0a7d872c7324d5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Augusto=20C=C3=A9sar=20Perin?= Date: Mon, 12 Jan 2026 23:49:20 -0300 Subject: [PATCH 017/146] Unify and deduplicate From float tests Co-authored-by: ericinB --- library/coretests/tests/floats/f128.rs | 50 ----------------- library/coretests/tests/floats/f16.rs | 35 ------------ library/coretests/tests/floats/mod.rs | 78 +++++++++++++++++++++++++- 3 files changed, 75 insertions(+), 88 deletions(-) delete mode 100644 library/coretests/tests/floats/f128.rs delete mode 100644 library/coretests/tests/floats/f16.rs diff --git a/library/coretests/tests/floats/f128.rs b/library/coretests/tests/floats/f128.rs deleted file mode 100644 index 8e4f0c9899e1..000000000000 --- a/library/coretests/tests/floats/f128.rs +++ /dev/null @@ -1,50 +0,0 @@ -// FIXME(f16_f128): only tested on platforms that have symbols and aren't buggy -#![cfg(target_has_reliable_f128)] - -use super::assert_biteq; - -// Note these tolerances make sense around zero, but not for more extreme exponents. - -/// Default tolerances. Works for values that should be near precise but not exact. Roughly -/// the precision carried by `100 * 100`. -#[allow(unused)] -const TOL: f128 = 1e-12; - -/// For operations that are near exact, usually not involving math of different -/// signs. -#[allow(unused)] -const TOL_PRECISE: f128 = 1e-28; - -// FIXME(f16_f128,miri): many of these have to be disabled since miri does not yet support -// the intrinsics. - -#[test] -fn test_from() { - assert_biteq!(f128::from(false), 0.0); - assert_biteq!(f128::from(true), 1.0); - assert_biteq!(f128::from(u8::MIN), 0.0); - assert_biteq!(f128::from(42_u8), 42.0); - assert_biteq!(f128::from(u8::MAX), 255.0); - assert_biteq!(f128::from(i8::MIN), -128.0); - assert_biteq!(f128::from(42_i8), 42.0); - assert_biteq!(f128::from(i8::MAX), 127.0); - assert_biteq!(f128::from(u16::MIN), 0.0); - assert_biteq!(f128::from(42_u16), 42.0); - assert_biteq!(f128::from(u16::MAX), 65535.0); - assert_biteq!(f128::from(i16::MIN), -32768.0); - assert_biteq!(f128::from(42_i16), 42.0); - assert_biteq!(f128::from(i16::MAX), 32767.0); - assert_biteq!(f128::from(u32::MIN), 0.0); - assert_biteq!(f128::from(42_u32), 42.0); - assert_biteq!(f128::from(u32::MAX), 4294967295.0); - assert_biteq!(f128::from(i32::MIN), -2147483648.0); - assert_biteq!(f128::from(42_i32), 42.0); - assert_biteq!(f128::from(i32::MAX), 2147483647.0); - // FIXME(f16_f128): Uncomment these tests once the From<{u64,i64}> impls are added. - // assert_eq!(f128::from(u64::MIN), 0.0); - // assert_eq!(f128::from(42_u64), 42.0); - // assert_eq!(f128::from(u64::MAX), 18446744073709551615.0); - // assert_eq!(f128::from(i64::MIN), -9223372036854775808.0); - // assert_eq!(f128::from(42_i64), 42.0); - // assert_eq!(f128::from(i64::MAX), 9223372036854775807.0); -} diff --git a/library/coretests/tests/floats/f16.rs b/library/coretests/tests/floats/f16.rs deleted file mode 100644 index 3cff4259de54..000000000000 --- a/library/coretests/tests/floats/f16.rs +++ /dev/null @@ -1,35 +0,0 @@ -// FIXME(f16_f128): only tested on platforms that have symbols and aren't buggy -#![cfg(target_has_reliable_f16)] - -use super::assert_biteq; - -/// Tolerance for results on the order of 10.0e-2 -#[allow(unused)] -const TOL_N2: f16 = 0.0001; - -/// Tolerance for results on the order of 10.0e+0 -#[allow(unused)] -const TOL_0: f16 = 0.01; - -/// Tolerance for results on the order of 10.0e+2 -#[allow(unused)] -const TOL_P2: f16 = 0.5; - -/// Tolerance for results on the order of 10.0e+4 -#[allow(unused)] -const TOL_P4: f16 = 10.0; - -// FIXME(f16_f128,miri): many of these have to be disabled since miri does not yet support -// the intrinsics. - -#[test] -fn test_from() { - assert_biteq!(f16::from(false), 0.0); - assert_biteq!(f16::from(true), 1.0); - assert_biteq!(f16::from(u8::MIN), 0.0); - assert_biteq!(f16::from(42_u8), 42.0); - assert_biteq!(f16::from(u8::MAX), 255.0); - assert_biteq!(f16::from(i8::MIN), -128.0); - assert_biteq!(f16::from(42_i8), 42.0); - assert_biteq!(f16::from(i8::MAX), 127.0); -} diff --git a/library/coretests/tests/floats/mod.rs b/library/coretests/tests/floats/mod.rs index 63d5b8fb2c6e..87e21b21f310 100644 --- a/library/coretests/tests/floats/mod.rs +++ b/library/coretests/tests/floats/mod.rs @@ -375,9 +375,6 @@ macro_rules! float_test { }; } -mod f128; -mod f16; - float_test! { name: num, attrs: { @@ -1582,3 +1579,78 @@ float_test! { assert_biteq!((flt(-3.2)).mul_add(2.4, neg_inf), neg_inf); } } + +float_test! { + name: from, + attrs: { + f16: #[cfg(any(miri, target_has_reliable_f16))], + f128: #[cfg(any(miri, target_has_reliable_f128))], + }, + test { + assert_biteq!(Float::from(false), Float::ZERO); + assert_biteq!(Float::from(true), Float::ONE); + + assert_biteq!(Float::from(u8::MIN), Float::ZERO); + assert_biteq!(Float::from(42_u8), 42.0); + assert_biteq!(Float::from(u8::MAX), 255.0); + + assert_biteq!(Float::from(i8::MIN), -128.0); + assert_biteq!(Float::from(42_i8), 42.0); + assert_biteq!(Float::from(i8::MAX), 127.0); + } +} + +float_test! { + name: from_u16_i16, + attrs: { + f16: #[cfg(false)], + const f16: #[cfg(false)], + f128: #[cfg(any(miri, target_has_reliable_f128))], + }, + test { + assert_biteq!(Float::from(u16::MIN), Float::ZERO); + assert_biteq!(Float::from(42_u16), 42.0); + assert_biteq!(Float::from(u16::MAX), 65535.0); + assert_biteq!(Float::from(i16::MIN), -32768.0); + assert_biteq!(Float::from(42_i16), 42.0); + assert_biteq!(Float::from(i16::MAX), 32767.0); + } +} + +float_test! { + name: from_u32_i32, + attrs: { + f16: #[cfg(false)], + const f16: #[cfg(false)], + f32: #[cfg(false)], + const f32: #[cfg(false)], + f128: #[cfg(any(miri, target_has_reliable_f128))], + }, + test { + assert_biteq!(Float::from(u32::MIN), Float::ZERO); + assert_biteq!(Float::from(42_u32), 42.0); + assert_biteq!(Float::from(u32::MAX), 4294967295.0); + assert_biteq!(Float::from(i32::MIN), -2147483648.0); + assert_biteq!(Float::from(42_i32), 42.0); + assert_biteq!(Float::from(i32::MAX), 2147483647.0); + } +} + +// FIXME(f16_f128): Uncomment and adapt these tests once the From<{u64,i64}> impls are added. +// float_test! { +// name: from_u64_i64, +// attrs: { +// f16: #[cfg(false)], +// f32: #[cfg(false)], +// f64: #[cfg(false)], +// f128: #[cfg(any(miri, target_has_reliable_f128))], +// }, +// test { +// assert_biteq!(Float::from(u64::MIN), Float::ZERO); +// assert_biteq!(Float::from(42_u64), 42.0); +// assert_biteq!(Float::from(u64::MAX), 18446744073709551615.0); +// assert_biteq!(Float::from(i64::MIN), -9223372036854775808.0); +// assert_biteq!(Float::from(42_i64), 42.0); +// assert_biteq!(Float::from(i64::MAX), 9223372036854775807.0); +// } +// } From 02333ad8a2805b333d2d0a944fc04a2ff3b37b90 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Tue, 13 Jan 2026 14:10:53 +1100 Subject: [PATCH 018/146] Simplify some literal-value negations with `u128::wrapping_neg` --- compiler/rustc_mir_build/src/builder/expr/as_constant.rs | 4 +++- compiler/rustc_mir_build/src/thir/constant.rs | 8 ++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs index 1772d66f5285..8a242445f175 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs @@ -157,7 +157,9 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx> } (ast::LitKind::Int(n, _), ty::Uint(_)) if !neg => trunc(n.get()), (ast::LitKind::Int(n, _), ty::Int(_)) => { - trunc(if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() }) + // Unsigned "negation" has the same bitwise effect as signed negation, + // which gets the result we want without additional casts. + trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() }) } (ast::LitKind::Float(n, _), ty::Float(fty)) => { parse_float_into_constval(n, *fty, neg).unwrap() diff --git a/compiler/rustc_mir_build/src/thir/constant.rs b/compiler/rustc_mir_build/src/thir/constant.rs index 7964a58a7ab0..96248499044a 100644 --- a/compiler/rustc_mir_build/src/thir/constant.rs +++ b/compiler/rustc_mir_build/src/thir/constant.rs @@ -72,10 +72,10 @@ pub(crate) fn lit_to_const<'tcx>( ty::ValTree::from_scalar_int(tcx, scalar_int) } (ast::LitKind::Int(n, _), ty::Int(i)) => { - let scalar_int = trunc( - if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() }, - i.to_unsigned(), - ); + // Unsigned "negation" has the same bitwise effect as signed negation, + // which gets the result we want without additional casts. + let scalar_int = + trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() }, i.to_unsigned()); ty::ValTree::from_scalar_int(tcx, scalar_int) } (ast::LitKind::Bool(b), ty::Bool) => ty::ValTree::from_scalar_int(tcx, b.into()), From 959be82effe087543befbd1aeb0920171ae2fc3f Mon Sep 17 00:00:00 2001 From: joboet Date: Mon, 12 Jan 2026 13:58:29 +0100 Subject: [PATCH 019/146] std: implement `sleep_until` on Apple platforms --- library/std/src/lib.rs | 1 + library/std/src/sys/pal/unix/time.rs | 52 ++++++++++++++++++++++------ library/std/src/sys/thread/mod.rs | 2 ++ library/std/src/sys/thread/unix.rs | 41 ++++++++++++++++++++++ library/std/src/thread/functions.rs | 1 + 5 files changed, 87 insertions(+), 10 deletions(-) diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index f5b9f69a5f9f..93f2c519dd1b 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -326,6 +326,7 @@ #![feature(const_convert)] #![feature(core_intrinsics)] #![feature(core_io_borrowed_buf)] +#![feature(cstr_display)] #![feature(drop_guard)] #![feature(duration_constants)] #![feature(error_generic_member_access)] diff --git a/library/std/src/sys/pal/unix/time.rs b/library/std/src/sys/pal/unix/time.rs index 50b690256a20..a56034f3778c 100644 --- a/library/std/src/sys/pal/unix/time.rs +++ b/library/std/src/sys/pal/unix/time.rs @@ -270,22 +270,25 @@ pub struct Instant { } impl Instant { + // CLOCK_UPTIME_RAW clock that increments monotonically, in the same man- + // ner as CLOCK_MONOTONIC_RAW, but that does not incre- + // ment while the system is asleep. The returned value + // is identical to the result of mach_absolute_time() + // after the appropriate mach_timebase conversion is + // applied. + // + // We use `CLOCK_UPTIME_RAW` instead of `CLOCK_MONOTONIC` since + // `CLOCK_UPTIME_RAW` is based on `mach_absolute_time`, which is the + // clock that all timeouts and deadlines are measured against inside + // the kernel. #[cfg(target_vendor = "apple")] pub(crate) const CLOCK_ID: libc::clockid_t = libc::CLOCK_UPTIME_RAW; + #[cfg(not(target_vendor = "apple"))] pub(crate) const CLOCK_ID: libc::clockid_t = libc::CLOCK_MONOTONIC; + pub fn now() -> Instant { // https://pubs.opengroup.org/onlinepubs/9799919799/functions/clock_getres.html - // - // CLOCK_UPTIME_RAW clock that increments monotonically, in the same man- - // ner as CLOCK_MONOTONIC_RAW, but that does not incre- - // ment while the system is asleep. The returned value - // is identical to the result of mach_absolute_time() - // after the appropriate mach_timebase conversion is - // applied. - // - // Instant on macos was historically implemented using mach_absolute_time; - // we preserve this value domain out of an abundance of caution. Instant { t: Timespec::now(Self::CLOCK_ID) } } @@ -308,6 +311,35 @@ impl Instant { pub(crate) fn into_timespec(self) -> Timespec { self.t } + + /// Returns `self` converted into units of `mach_absolute_time`, or `None` + /// if `self` is before the system boot time. + #[cfg(target_vendor = "apple")] + pub fn into_mach_absolute_time(self) -> Option { + #[repr(C)] + struct mach_timebase_info { + numer: u32, + denom: u32, + } + + unsafe extern "C" { + unsafe fn mach_timebase_info(info: *mut mach_timebase_info) -> libc::kern_return_t; + } + + let secs = u64::try_from(self.t.tv_sec).ok()?; + + let mut timebase = mach_timebase_info { numer: 0, denom: 0 }; + assert_eq!(unsafe { mach_timebase_info(&mut timebase) }, libc::KERN_SUCCESS); + + // Since `tv_sec` is 64-bit and `tv_nsec` is smaller than 1 billion, + // this cannot overflow. The resulting number needs at most 94 bits. + let nanos = + u128::from(secs) * u128::from(NSEC_PER_SEC) + u128::from(self.t.tv_nsec.as_inner()); + // This multiplication cannot overflow since multiplying a 94-bit + // number by a 32-bit number yields a number that needs at most + // 126 bits. + Some(nanos * u128::from(timebase.denom) / u128::from(timebase.numer)) + } } impl AsInner for Instant { diff --git a/library/std/src/sys/thread/mod.rs b/library/std/src/sys/thread/mod.rs index cb6bf6518f81..3460270b15fc 100644 --- a/library/std/src/sys/thread/mod.rs +++ b/library/std/src/sys/thread/mod.rs @@ -73,6 +73,7 @@ cfg_select! { target_os = "fuchsia", target_os = "vxworks", target_os = "wasi", + target_vendor = "apple", ))] pub use unix::sleep_until; #[expect(dead_code)] @@ -133,6 +134,7 @@ cfg_select! { target_os = "fuchsia", target_os = "vxworks", target_os = "wasi", + target_vendor = "apple", )))] pub fn sleep_until(deadline: crate::time::Instant) { use crate::time::Instant; diff --git a/library/std/src/sys/thread/unix.rs b/library/std/src/sys/thread/unix.rs index d0396ed71300..e52bc63ea5b1 100644 --- a/library/std/src/sys/thread/unix.rs +++ b/library/std/src/sys/thread/unix.rs @@ -636,6 +636,47 @@ pub fn sleep_until(deadline: crate::time::Instant) { } } +#[cfg(target_vendor = "apple")] +pub fn sleep_until(deadline: crate::time::Instant) { + unsafe extern "C" { + // This is defined in the public header mach/mach_time.h alongside + // `mach_absolute_time`, and like it has been available since the very + // beginning. + // + // There isn't really any documentation on this function, except for a + // short reference in technical note 2169: + // https://developer.apple.com/library/archive/technotes/tn2169/_index.html + safe fn mach_wait_until(deadline: u64) -> libc::kern_return_t; + } + + let Some(deadline) = deadline.into_inner().into_mach_absolute_time() else { + // Since the deadline is before the system boot time, it has already + // passed, so we can return immediately. + return; + }; + + // If the deadline is not representable, then sleep for the maximum duration + // possible and worry about the potential clock issues later (in ca. 600 years). + let deadline = deadline.try_into().unwrap_or(u64::MAX); + loop { + match mach_wait_until(deadline) { + // Success! The deadline has passed. + libc::KERN_SUCCESS => break, + // If the sleep gets interrupted by a signal, `mach_wait_until` + // returns KERN_ABORTED, so we need to restart the syscall. + // Also see Apple's implementation of the POSIX `nanosleep`, which + // converts this error to the POSIX equivalent EINTR: + // https://github.com/apple-oss-distributions/Libc/blob/55b54c0a0c37b3b24393b42b90a4c561d6c606b1/gen/nanosleep.c#L281-L306 + libc::KERN_ABORTED => continue, + // All other errors indicate that something has gone wrong... + error => { + let description = unsafe { CStr::from_ptr(libc::mach_error_string(error)) }; + panic!("mach_wait_until failed: {} (code {error})", description.display()) + } + } + } +} + pub fn yield_now() { let ret = unsafe { libc::sched_yield() }; debug_assert_eq!(ret, 0); diff --git a/library/std/src/thread/functions.rs b/library/std/src/thread/functions.rs index a25bae1aae31..73d727878570 100644 --- a/library/std/src/thread/functions.rs +++ b/library/std/src/thread/functions.rs @@ -318,6 +318,7 @@ pub fn sleep(dur: Duration) { /// | Hurd | [clock_nanosleep] (Monotonic Clock)] | /// | Fuchsia | [clock_nanosleep] (Monotonic Clock)] | /// | Vxworks | [clock_nanosleep] (Monotonic Clock)] | +/// | Apple | `mach_wait_until` | /// | Other | `sleep_until` uses [`sleep`] and does not issue a syscall itself | /// /// [currently]: crate::io#platform-specific-behavior From a1e2cea685fca526ad36667cb9f188127c6438eb Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 13 Jan 2026 16:29:02 +0100 Subject: [PATCH 020/146] Port `do_not_recommend` to new attr parsing --- .../src/attributes/do_not_recommend.rs | 31 +++++++++++++++++ .../rustc_attr_parsing/src/attributes/mod.rs | 1 + compiler/rustc_attr_parsing/src/context.rs | 2 ++ .../rustc_hir/src/attrs/data_structures.rs | 3 ++ .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_lint/messages.ftl | 3 ++ compiler/rustc_lint/src/early/diagnostics.rs | 4 +++ compiler/rustc_lint/src/lints.rs | 4 +++ compiler/rustc_lint_defs/src/lib.rs | 1 + compiler/rustc_middle/src/ty/context.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 33 +------------------ compiler/rustc_passes/messages.ftl | 3 -- compiler/rustc_passes/src/check_attr.rs | 20 +++-------- compiler/rustc_passes/src/errors.rs | 4 --- .../src/solve/fulfill/derive_errors.rs | 2 +- tests/ui/attributes/malformed-attrs.stderr | 15 ++++----- tests/ui/unpretty/diagnostic-attr.stdout | 2 +- 17 files changed, 65 insertions(+), 66 deletions(-) create mode 100644 compiler/rustc_attr_parsing/src/attributes/do_not_recommend.rs diff --git a/compiler/rustc_attr_parsing/src/attributes/do_not_recommend.rs b/compiler/rustc_attr_parsing/src/attributes/do_not_recommend.rs new file mode 100644 index 000000000000..4a89cf6515ce --- /dev/null +++ b/compiler/rustc_attr_parsing/src/attributes/do_not_recommend.rs @@ -0,0 +1,31 @@ +use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::lints::AttributeLintKind; +use rustc_session::lint::builtin::MALFORMED_DIAGNOSTIC_ATTRIBUTES; +use rustc_span::{Symbol, sym}; + +use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser}; +use crate::context::{AcceptContext, Stage}; +use crate::parser::ArgParser; +use crate::target_checking::{ALL_TARGETS, AllowedTargets}; + +pub(crate) struct DoNotRecommendParser; +impl SingleAttributeParser for DoNotRecommendParser { + const PATH: &[Symbol] = &[sym::diagnostic, sym::do_not_recommend]; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); // Checked in check_attr. + const TEMPLATE: AttributeTemplate = template!(Word /*doesn't matter */); + + fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option { + let attr_span = cx.attr_span; + if !matches!(args, ArgParser::NoArgs) { + cx.emit_lint( + MALFORMED_DIAGNOSTIC_ATTRIBUTES, + AttributeLintKind::DoNotRecommendDoesNotExpectArgs, + attr_span, + ); + } + Some(AttributeKind::DoNotRecommend { attr_span }) + } +} diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index e02d71a26158..3da27f077a61 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -39,6 +39,7 @@ pub(crate) mod confusables; pub(crate) mod crate_level; pub(crate) mod debugger; pub(crate) mod deprecation; +pub(crate) mod do_not_recommend; pub(crate) mod doc; pub(crate) mod dummy; pub(crate) mod inline; diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 6b1b1d484283..a207af57ccca 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -34,6 +34,7 @@ use crate::attributes::crate_level::{ }; use crate::attributes::debugger::DebuggerViualizerParser; use crate::attributes::deprecation::DeprecationParser; +use crate::attributes::do_not_recommend::DoNotRecommendParser; use crate::attributes::doc::DocParser; use crate::attributes::dummy::DummyParser; use crate::attributes::inline::{InlineParser, RustcForceInlineParser}; @@ -197,6 +198,7 @@ attribute_parsers!( Single, Single, Single, + Single, Single, Single, Single, diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 8d18d335b355..16bee3d53297 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -731,6 +731,9 @@ pub enum AttributeKind { /// Represents `#[rustc_do_not_implement_via_object]`. DoNotImplementViaObject(Span), + /// Represents `#[diagnostic::do_not_recommend]`. + DoNotRecommend { attr_span: Span }, + /// Represents [`#[doc]`](https://doc.rust-lang.org/stable/rustdoc/write-documentation/the-doc-attribute.html). /// Represents all other uses of the [`#[doc]`](https://doc.rust-lang.org/stable/rustdoc/write-documentation/the-doc-attribute.html) /// attribute. diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 33655f4f0063..7cdcdc3a5e94 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -44,6 +44,7 @@ impl AttributeKind { DenyExplicitImpl(..) => No, Deprecation { .. } => Yes, DoNotImplementViaObject(..) => No, + DoNotRecommend { .. } => Yes, Doc(_) => Yes, DocComment { .. } => Yes, Dummy => No, diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index 9b0b1abc91df..f5b882494863 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -480,6 +480,9 @@ lint_improper_ctypes_unsafe_binder = unsafe binders are incompatible with foreig lint_improper_gpu_kernel_arg = passing type `{$ty}` to a function with "gpu-kernel" ABI may have unexpected behavior .help = use primitive types and raw pointers to get reliable behavior +lint_incorrect_do_not_recommend_args = + `#[diagnostic::do_not_recommend]` does not expect any arguments + lint_int_to_ptr_transmutes = transmuting an integer to a pointer creates a pointer without provenance .note = this is dangerous because dereferencing the resulting pointer is undefined behavior .note_exposed_provenance = exposed provenance semantics can be used to create a pointer based on some previously exposed provenance diff --git a/compiler/rustc_lint/src/early/diagnostics.rs b/compiler/rustc_lint/src/early/diagnostics.rs index 5745f0d4edde..037a31c162d2 100644 --- a/compiler/rustc_lint/src/early/diagnostics.rs +++ b/compiler/rustc_lint/src/early/diagnostics.rs @@ -419,5 +419,9 @@ pub fn decorate_attribute_lint( &AttributeLintKind::DocTestLiteral => lints::DocTestLiteral.decorate_lint(diag), &AttributeLintKind::AttrCrateLevelOnly => lints::AttrCrateLevelOnly.decorate_lint(diag), + + &AttributeLintKind::DoNotRecommendDoesNotExpectArgs => { + lints::DoNotRecommendDoesNotExpectArgs.decorate_lint(diag) + } } } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 33e9375ec71b..c85e4ffe91fc 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -3317,3 +3317,7 @@ pub(crate) struct DocTestLiteral; #[diag(lint_attr_crate_level)] #[note] pub(crate) struct AttrCrateLevelOnly; + +#[derive(LintDiagnostic)] +#[diag(lint_incorrect_do_not_recommend_args)] +pub(crate) struct DoNotRecommendDoesNotExpectArgs; diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index c8713b23633f..4d0c44f16760 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -821,6 +821,7 @@ pub enum AttributeLintKind { }, DocTestLiteral, AttrCrateLevelOnly, + DoNotRecommendDoesNotExpectArgs, } pub type RegisteredTools = FxIndexSet; diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index a3eec72214c0..e9fa3f14358e 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -3540,7 +3540,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Whether this is a trait implementation that has `#[diagnostic::do_not_recommend]` pub fn do_not_recommend_impl(self, def_id: DefId) -> bool { - self.get_diagnostic_attr(def_id, sym::do_not_recommend).is_some() + find_attr!(self.get_all_attrs(def_id), AttributeKind::DoNotRecommend { .. }) } pub fn is_trivial_const

(self, def_id: P) -> bool diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index e2a94b607de1..8eee114ead02 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -51,7 +51,7 @@ use rustc_query_system::ich::StableHashingContext; use rustc_serialize::{Decodable, Encodable}; pub use rustc_session::lint::RegisteredTools; use rustc_span::hygiene::MacroKind; -use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym}; +use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol}; pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet}; pub use rustc_type_ir::fast_reject::DeepRejectCtxt; #[allow( @@ -1819,37 +1819,6 @@ impl<'tcx> TyCtxt<'tcx> { } } - /// Get an attribute from the diagnostic attribute namespace - /// - /// This function requests an attribute with the following structure: - /// - /// `#[diagnostic::$attr]` - /// - /// This function performs feature checking, so if an attribute is returned - /// it can be used by the consumer - pub fn get_diagnostic_attr( - self, - did: impl Into, - attr: Symbol, - ) -> Option<&'tcx hir::Attribute> { - let did: DefId = did.into(); - if did.as_local().is_some() { - // it's a crate local item, we need to check feature flags - if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) { - self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next() - } else { - None - } - } else { - // we filter out unstable diagnostic attributes before - // encoding attributes - debug_assert!(rustc_feature::encode_cross_crate(attr)); - self.attrs_for_def(did) - .iter() - .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr)) - } - } - pub fn get_attrs_by_path( self, did: DefId, diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 11e4b8b20222..51c439b4243c 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -246,9 +246,6 @@ passes_implied_feature_not_exist = passes_incorrect_crate_type = lang items are not allowed in stable dylibs -passes_incorrect_do_not_recommend_args = - `#[diagnostic::do_not_recommend]` does not expect any arguments - passes_incorrect_do_not_recommend_location = `#[diagnostic::do_not_recommend]` can only be placed on trait implementations diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 8f80822a81ab..3402b9744b3c 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -43,8 +43,8 @@ use rustc_middle::{bug, span_bug}; use rustc_session::config::CrateType; use rustc_session::lint; use rustc_session::lint::builtin::{ - CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES, - MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, + CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES, + UNUSED_ATTRIBUTES, }; use rustc_session::parse::feature_err; use rustc_span::edition::Edition; @@ -223,6 +223,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Attribute::Parsed(AttributeKind::RustcMustImplementOneOf { attr_span, fn_names }) => { self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id,target) }, + Attribute::Parsed(AttributeKind::DoNotRecommend{attr_span}) => {self.check_do_not_recommend(*attr_span, hir_id, target, item)}, Attribute::Parsed( AttributeKind::EiiDeclaration { .. } | AttributeKind::EiiForeignItem @@ -313,9 +314,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); match attr.path().as_slice() { - [sym::diagnostic, sym::do_not_recommend, ..] => { - self.check_do_not_recommend(attr.span(), hir_id, target, attr, item) - } [sym::diagnostic, sym::on_unimplemented, ..] => { self.check_diagnostic_on_unimplemented(attr.span(), hir_id, target) } @@ -568,14 +566,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - /// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl and that it has no - /// arguments. + /// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl fn check_do_not_recommend( &self, attr_span: Span, hir_id: HirId, target: Target, - attr: &Attribute, item: Option>, ) { if !matches!(target, Target::Impl { .. }) @@ -592,14 +588,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { errors::IncorrectDoNotRecommendLocation, ); } - if !attr.is_word() { - self.tcx.emit_node_span_lint( - MALFORMED_DIAGNOSTIC_ATTRIBUTES, - hir_id, - attr_span, - errors::DoNotRecommendDoesNotExpectArgs, - ); - } } /// Checks if `#[diagnostic::on_unimplemented]` is applied to a trait definition diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 1f3f0d7f8884..bf9b615546d8 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -20,10 +20,6 @@ use crate::lang_items::Duplicate; #[diag(passes_incorrect_do_not_recommend_location)] pub(crate) struct IncorrectDoNotRecommendLocation; -#[derive(LintDiagnostic)] -#[diag(passes_incorrect_do_not_recommend_args)] -pub(crate) struct DoNotRecommendDoesNotExpectArgs; - #[derive(Diagnostic)] #[diag(passes_autodiff_attr)] pub(crate) struct AutoDiffAttr { diff --git a/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs b/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs index eef8b870a5b8..77834320dbc6 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs @@ -434,7 +434,7 @@ impl<'tcx> ProofTreeVisitor<'tcx> for BestObligation<'tcx> { } = candidate.kind() && tcx.do_not_recommend_impl(impl_def_id) { - trace!("#[do_not_recommend] -> exit"); + trace!("#[diagnostic::do_not_recommend] -> exit"); return ControlFlow::Break(self.obligation.clone()); } diff --git a/tests/ui/attributes/malformed-attrs.stderr b/tests/ui/attributes/malformed-attrs.stderr index fc644668735e..04f51f54b2cd 100644 --- a/tests/ui/attributes/malformed-attrs.stderr +++ b/tests/ui/attributes/malformed-attrs.stderr @@ -729,14 +729,6 @@ help: use `#[rustc_align(...)]` instead LL | #[repr] | ^^^^^^^ -warning: `#[diagnostic::do_not_recommend]` does not expect any arguments - --> $DIR/malformed-attrs.rs:155:1 - | -LL | #[diagnostic::do_not_recommend()] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(malformed_diagnostic_attributes)]` (part of `#[warn(unknown_or_malformed_diagnostic_attributes)]`) on by default - warning: missing options for `on_unimplemented` attribute --> $DIR/malformed-attrs.rs:144:1 | @@ -744,6 +736,7 @@ LL | #[diagnostic::on_unimplemented] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: at least one of the `message`, `note` and `label` options are expected + = note: `#[warn(malformed_diagnostic_attributes)]` (part of `#[warn(unknown_or_malformed_diagnostic_attributes)]`) on by default warning: malformed `on_unimplemented` attribute --> $DIR/malformed-attrs.rs:146:1 @@ -823,6 +816,12 @@ LL | #[no_implicit_prelude = 23] = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = help: `#[no_implicit_prelude]` can be applied to crates and modules +warning: `#[diagnostic::do_not_recommend]` does not expect any arguments + --> $DIR/malformed-attrs.rs:155:1 + | +LL | #[diagnostic::do_not_recommend()] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + warning: `#[automatically_derived]` attribute cannot be used on modules --> $DIR/malformed-attrs.rs:196:1 | diff --git a/tests/ui/unpretty/diagnostic-attr.stdout b/tests/ui/unpretty/diagnostic-attr.stdout index 4822cf4700b9..f74637fa7efe 100644 --- a/tests/ui/unpretty/diagnostic-attr.stdout +++ b/tests/ui/unpretty/diagnostic-attr.stdout @@ -11,5 +11,5 @@ use ::std::prelude::rust_2015::*; "My Label", note = "Note 1", note = "Note 2")] trait ImportantTrait { } -#[diagnostic::do_not_recommend] +#[attr = DoNotRecommend] impl ImportantTrait for T where T: Clone { } From ed6e63092c4f1303b127e10f5d5e300e59e9dbfa Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 13 Jan 2026 16:29:12 +0100 Subject: [PATCH 021/146] Keep allowing invalid metaitem syntax in diagnostic attributes --- compiler/rustc_attr_parsing/src/parser.rs | 5 +++-- .../does_not_acccept_args.current.stderr | 14 ++++++++++---- .../does_not_acccept_args.next.stderr | 14 ++++++++++---- .../do_not_recommend/does_not_acccept_args.rs | 5 +++++ 4 files changed, 28 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/parser.rs b/compiler/rustc_attr_parsing/src/parser.rs index 68265649d182..72b0fc63cc15 100644 --- a/compiler/rustc_attr_parsing/src/parser.rs +++ b/compiler/rustc_attr_parsing/src/parser.rs @@ -113,8 +113,9 @@ impl ArgParser { Some(match value { AttrArgs::Empty => Self::NoArgs, AttrArgs::Delimited(args) => { - // The arguments of rustc_dummy are not validated if the arguments are delimited - if parts == &[sym::rustc_dummy] { + // The arguments of rustc_dummy and diagnostic attributes are not validated + // if the arguments are delimited + if parts == &[sym::rustc_dummy] || parts[0] == sym::diagnostic { return Some(ArgParser::List(MetaItemListParser { sub_parsers: ThinVec::new(), span: args.dspan.entire(), diff --git a/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.current.stderr b/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.current.stderr index 2af24130a1e5..43205bd395fc 100644 --- a/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.current.stderr +++ b/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.current.stderr @@ -1,5 +1,5 @@ warning: `#[diagnostic::do_not_recommend]` does not expect any arguments - --> $DIR/does_not_acccept_args.rs:11:1 + --> $DIR/does_not_acccept_args.rs:12:1 | LL | #[diagnostic::do_not_recommend(not_accepted)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -7,16 +7,22 @@ LL | #[diagnostic::do_not_recommend(not_accepted)] = note: `#[warn(malformed_diagnostic_attributes)]` (part of `#[warn(unknown_or_malformed_diagnostic_attributes)]`) on by default warning: `#[diagnostic::do_not_recommend]` does not expect any arguments - --> $DIR/does_not_acccept_args.rs:15:1 + --> $DIR/does_not_acccept_args.rs:16:1 | LL | #[diagnostic::do_not_recommend(not_accepted = "foo")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: `#[diagnostic::do_not_recommend]` does not expect any arguments - --> $DIR/does_not_acccept_args.rs:19:1 + --> $DIR/does_not_acccept_args.rs:20:1 | LL | #[diagnostic::do_not_recommend(not_accepted(42))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: 3 warnings emitted +warning: `#[diagnostic::do_not_recommend]` does not expect any arguments + --> $DIR/does_not_acccept_args.rs:24:1 + | +LL | #[diagnostic::do_not_recommend(x = y + z)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +warning: 4 warnings emitted diff --git a/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.next.stderr b/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.next.stderr index 2af24130a1e5..43205bd395fc 100644 --- a/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.next.stderr +++ b/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.next.stderr @@ -1,5 +1,5 @@ warning: `#[diagnostic::do_not_recommend]` does not expect any arguments - --> $DIR/does_not_acccept_args.rs:11:1 + --> $DIR/does_not_acccept_args.rs:12:1 | LL | #[diagnostic::do_not_recommend(not_accepted)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -7,16 +7,22 @@ LL | #[diagnostic::do_not_recommend(not_accepted)] = note: `#[warn(malformed_diagnostic_attributes)]` (part of `#[warn(unknown_or_malformed_diagnostic_attributes)]`) on by default warning: `#[diagnostic::do_not_recommend]` does not expect any arguments - --> $DIR/does_not_acccept_args.rs:15:1 + --> $DIR/does_not_acccept_args.rs:16:1 | LL | #[diagnostic::do_not_recommend(not_accepted = "foo")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: `#[diagnostic::do_not_recommend]` does not expect any arguments - --> $DIR/does_not_acccept_args.rs:19:1 + --> $DIR/does_not_acccept_args.rs:20:1 | LL | #[diagnostic::do_not_recommend(not_accepted(42))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: 3 warnings emitted +warning: `#[diagnostic::do_not_recommend]` does not expect any arguments + --> $DIR/does_not_acccept_args.rs:24:1 + | +LL | #[diagnostic::do_not_recommend(x = y + z)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +warning: 4 warnings emitted diff --git a/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.rs b/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.rs index 5c21c045e10a..918bf5a0113e 100644 --- a/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.rs +++ b/tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.rs @@ -7,6 +7,7 @@ trait Foo {} trait Bar {} trait Baz {} +trait Boo {} #[diagnostic::do_not_recommend(not_accepted)] //~^ WARNING `#[diagnostic::do_not_recommend]` does not expect any arguments @@ -20,4 +21,8 @@ impl Bar for T where T: Send {} //~^ WARNING `#[diagnostic::do_not_recommend]` does not expect any arguments impl Baz for T where T: Send {} +#[diagnostic::do_not_recommend(x = y + z)] +//~^ WARNING `#[diagnostic::do_not_recommend]` does not expect any arguments +impl Boo for T where T: Send {} + fn main() {} From 596ea17eae592b68a16a7661bf26c10a5155da89 Mon Sep 17 00:00:00 2001 From: rami3l Date: Tue, 13 Jan 2026 21:05:44 +0100 Subject: [PATCH 022/146] fix(build-manifest): enable docs target fallback for `rustc-docs` --- src/tools/build-manifest/src/main.rs | 12 ++++++------ src/tools/build-manifest/src/versions.rs | 5 +---- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs index 4cec1b1f164b..58f7487a0fda 100644 --- a/src/tools/build-manifest/src/main.rs +++ b/src/tools/build-manifest/src/main.rs @@ -14,11 +14,11 @@ use crate::versions::{PkgType, Versions}; include!(concat!(env!("OUT_DIR"), "/targets.rs")); -/// This allows the manifest to contain rust-docs for hosts that don't build -/// docs. +/// This allows the manifest to contain rust-docs and rustc-docs for hosts +/// that don't build certain docs. /// /// Tuples of `(host_partial, host_instead)`. If the host does not have the -/// rust-docs component available, then if the host name contains +/// corresponding docs component available, then if the host name contains /// `host_partial`, it will use the docs from `host_instead` instead. /// /// The order here matters, more specific entries should be first. @@ -392,9 +392,9 @@ impl Builder { let t = Target::from_compressed_tar(self, &tarball_name!(fallback_target)); // Fallbacks should typically be available on 'production' builds // but may not be available for try builds, which only build one target by - // default. Ideally we'd gate this being a hard error on whether we're in a - // production build or not, but it's not information that's readily available - // here. + // default. It is also possible that `rust-docs` and `rustc-docs` differ in + // availability per target. Thus, we take the first available fallback we can + // find. if !t.available { eprintln!( "{:?} not available for fallback", diff --git a/src/tools/build-manifest/src/versions.rs b/src/tools/build-manifest/src/versions.rs index 6ef8a0e83de3..da887a66d98e 100644 --- a/src/tools/build-manifest/src/versions.rs +++ b/src/tools/build-manifest/src/versions.rs @@ -133,10 +133,7 @@ impl PkgType { /// Whether to package these target-specific docs for another similar target. pub(crate) fn use_docs_fallback(&self) -> bool { - match self { - PkgType::JsonDocs | PkgType::HtmlDocs => true, - _ => false, - } + matches!(self, PkgType::JsonDocs | PkgType::HtmlDocs | PkgType::RustcDocs) } } From 6166b619794ba095919deaad239628ad2ddce3b3 Mon Sep 17 00:00:00 2001 From: reddevilmidzy Date: Mon, 12 Jan 2026 00:45:50 +0900 Subject: [PATCH 023/146] Add crashes mGCA tests --- tests/crashes/138226-2.rs | 13 ++++++++ tests/crashes/138226.rs | 13 ++++++++ tests/crashes/149809.rs | 13 ++++++++ tests/crashes/150960.rs | 11 +++++++ .../mgca/cast-with-type-mismatched.rs | 14 -------- .../mgca/cast-with-type-mismatched.stderr | 20 ------------ .../mgca/const-eval-with-invalid-args.rs | 26 --------------- .../mgca/const-eval-with-invalid-args.stderr | 32 ------------------- .../recursive-self-referencing-const-param.rs | 11 ------- ...ursive-self-referencing-const-param.stderr | 23 ------------- .../mgca/size-of-generic-ptr-in-array-len.rs | 2 ++ .../size-of-generic-ptr-in-array-len.stderr | 8 ++++- 12 files changed, 59 insertions(+), 127 deletions(-) create mode 100644 tests/crashes/138226-2.rs create mode 100644 tests/crashes/138226.rs create mode 100644 tests/crashes/149809.rs create mode 100644 tests/crashes/150960.rs delete mode 100644 tests/ui/const-generics/mgca/cast-with-type-mismatched.rs delete mode 100644 tests/ui/const-generics/mgca/cast-with-type-mismatched.stderr delete mode 100644 tests/ui/const-generics/mgca/const-eval-with-invalid-args.rs delete mode 100644 tests/ui/const-generics/mgca/const-eval-with-invalid-args.stderr delete mode 100644 tests/ui/const-generics/mgca/recursive-self-referencing-const-param.rs delete mode 100644 tests/ui/const-generics/mgca/recursive-self-referencing-const-param.stderr diff --git a/tests/crashes/138226-2.rs b/tests/crashes/138226-2.rs new file mode 100644 index 000000000000..a2ebbdefdf3f --- /dev/null +++ b/tests/crashes/138226-2.rs @@ -0,0 +1,13 @@ +//@ known-bug: #138226 +//@ needs-rustc-debug-assertions +#![feature(min_generic_const_args)] +#![feature(inherent_associated_types)] +struct Bar; +impl Bar { + #[type_const] + const LEN: usize = 4; + + fn bar() { + let _ = [0; Self::LEN]; + } +} diff --git a/tests/crashes/138226.rs b/tests/crashes/138226.rs new file mode 100644 index 000000000000..7d13461a56b3 --- /dev/null +++ b/tests/crashes/138226.rs @@ -0,0 +1,13 @@ +//@ known-bug: #138226 +//@ needs-rustc-debug-assertions +#![feature(min_generic_const_args)] +#![feature(inherent_associated_types)] +struct Foo(A, B); +impl Foo { + #[type_const] + const LEN: usize = 4; + + fn foo() { + let _ = [5; Self::LEN]; + } +} diff --git a/tests/crashes/149809.rs b/tests/crashes/149809.rs new file mode 100644 index 000000000000..2b948e9079c3 --- /dev/null +++ b/tests/crashes/149809.rs @@ -0,0 +1,13 @@ +//@ known-bug: #149809 +#![feature(min_generic_const_args)] +#![feature(inherent_associated_types)] +struct Qux<'a> { + x: &'a (), +} +impl<'a> Qux<'a> { + #[type_const] + const LEN: usize = 4; + fn foo(_: [u8; Qux::LEN]) {} +} + +fn main() {} diff --git a/tests/crashes/150960.rs b/tests/crashes/150960.rs new file mode 100644 index 000000000000..2d46eea67989 --- /dev/null +++ b/tests/crashes/150960.rs @@ -0,0 +1,11 @@ +//@ known-bug: #150960 +#![feature(min_generic_const_args)] +struct Baz; +impl Baz { + #[type_const] + const LEN: usize = 4; + + fn baz() { + let _ = [0; const { Self::LEN }]; + } +} diff --git a/tests/ui/const-generics/mgca/cast-with-type-mismatched.rs b/tests/ui/const-generics/mgca/cast-with-type-mismatched.rs deleted file mode 100644 index 1f499c222e7f..000000000000 --- a/tests/ui/const-generics/mgca/cast-with-type-mismatched.rs +++ /dev/null @@ -1,14 +0,0 @@ -//! regression test for -#![expect(incomplete_features)] -#![feature(generic_const_exprs)] -#![feature(min_generic_const_args)] - -fn foo(a: [(); N as usize]) {} -//~^ ERROR: complex const arguments must be placed inside of a `const` block - -const C: f32 = 1.0; - -fn main() { - foo::([]); - //~^ ERROR: the constant `C` is not of type `u32` -} diff --git a/tests/ui/const-generics/mgca/cast-with-type-mismatched.stderr b/tests/ui/const-generics/mgca/cast-with-type-mismatched.stderr deleted file mode 100644 index 7e1b21138ec8..000000000000 --- a/tests/ui/const-generics/mgca/cast-with-type-mismatched.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error: complex const arguments must be placed inside of a `const` block - --> $DIR/cast-with-type-mismatched.rs:6:30 - | -LL | fn foo(a: [(); N as usize]) {} - | ^^^^^^^^^^ - -error: the constant `C` is not of type `u32` - --> $DIR/cast-with-type-mismatched.rs:12:11 - | -LL | foo::([]); - | ^ expected `u32`, found `f32` - | -note: required by a const generic parameter in `foo` - --> $DIR/cast-with-type-mismatched.rs:6:8 - | -LL | fn foo(a: [(); N as usize]) {} - | ^^^^^^^^^^^^ required by this const generic parameter in `foo` - -error: aborting due to 2 previous errors - diff --git a/tests/ui/const-generics/mgca/const-eval-with-invalid-args.rs b/tests/ui/const-generics/mgca/const-eval-with-invalid-args.rs deleted file mode 100644 index 3bf951e0c212..000000000000 --- a/tests/ui/const-generics/mgca/const-eval-with-invalid-args.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! regression test for -#![expect(incomplete_features)] -#![feature(generic_const_exprs)] -#![feature(min_generic_const_args)] - -// The previous ICE was an "invalid field access on immediate". -// If we remove `val: i32` from the field, another ICE occurs. -// "assertion `left == right` failed: invalid field type in -// Immediate::offset: scalar value has wrong size" -struct A { - arr: usize, - val: i32, -} - -struct B { - //~^ ERROR: `A` is forbidden as the type of a const generic parameter - arr: [u8; N.arr], - //~^ ERROR: complex const arguments must be placed inside of a `const` block -} - -const C: u32 = 1; -fn main() { - let b = B:: {arr: [1]}; - //~^ ERROR: the constant `C` is not of type `A` - let _ = b.arr.len(); -} diff --git a/tests/ui/const-generics/mgca/const-eval-with-invalid-args.stderr b/tests/ui/const-generics/mgca/const-eval-with-invalid-args.stderr deleted file mode 100644 index a226718ccf1b..000000000000 --- a/tests/ui/const-generics/mgca/const-eval-with-invalid-args.stderr +++ /dev/null @@ -1,32 +0,0 @@ -error: complex const arguments must be placed inside of a `const` block - --> $DIR/const-eval-with-invalid-args.rs:17:15 - | -LL | arr: [u8; N.arr], - | ^^^^^ - -error: `A` is forbidden as the type of a const generic parameter - --> $DIR/const-eval-with-invalid-args.rs:15:19 - | -LL | struct B { - | ^ - | - = note: the only supported types are integers, `bool`, and `char` -help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types - | -LL + #![feature(adt_const_params)] - | - -error: the constant `C` is not of type `A` - --> $DIR/const-eval-with-invalid-args.rs:23:17 - | -LL | let b = B:: {arr: [1]}; - | ^ expected `A`, found `u32` - | -note: required by a const generic parameter in `B` - --> $DIR/const-eval-with-invalid-args.rs:15:10 - | -LL | struct B { - | ^^^^^^^^^^ required by this const generic parameter in `B` - -error: aborting due to 3 previous errors - diff --git a/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.rs b/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.rs deleted file mode 100644 index 37dcc58ff468..000000000000 --- a/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! regression test for -#![expect(incomplete_features)] -#![feature(generic_const_exprs)] -#![feature(min_generic_const_args)] - -fn identity }>() }>>(); -//~^ ERROR: free function without a body -//~| ERROR: expected type, found function `identity` -//~| ERROR: complex const arguments must be placed inside of a `const` block - -fn main() {} diff --git a/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.stderr b/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.stderr deleted file mode 100644 index d1899c476ec6..000000000000 --- a/tests/ui/const-generics/mgca/recursive-self-referencing-const-param.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error: free function without a body - --> $DIR/recursive-self-referencing-const-param.rs:6:1 - | -LL | fn identity }>() }>>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- - | | - | help: provide a definition for the function: `{ }` - -error[E0573]: expected type, found function `identity` - --> $DIR/recursive-self-referencing-const-param.rs:6:22 - | -LL | fn identity }>() }>>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not a type - -error: complex const arguments must be placed inside of a `const` block - --> $DIR/recursive-self-referencing-const-param.rs:6:57 - | -LL | fn identity }>() }>>(); - | ^^ - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0573`. diff --git a/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.rs b/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.rs index 2a7c23929845..22963b6438c0 100644 --- a/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.rs +++ b/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.rs @@ -5,6 +5,8 @@ fn foo() { [0; size_of::<*mut T>()]; //~^ ERROR: tuple constructor with invalid base path + [0; const { size_of::<*mut T>() }]; + //~^ ERROR: generic parameters may not be used in const operations } fn main() {} diff --git a/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.stderr b/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.stderr index dcdc56a1cf47..913d8195fe21 100644 --- a/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.stderr +++ b/tests/ui/const-generics/mgca/size-of-generic-ptr-in-array-len.stderr @@ -4,5 +4,11 @@ error: tuple constructor with invalid base path LL | [0; size_of::<*mut T>()]; | ^^^^^^^^^^^^^^^^^^^ -error: aborting due to 1 previous error +error: generic parameters may not be used in const operations + --> $DIR/size-of-generic-ptr-in-array-len.rs:8:32 + | +LL | [0; const { size_of::<*mut T>() }]; + | ^ + +error: aborting due to 2 previous errors From 0ee43b16b6aa77096246e42c294de72affa60f40 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 13 Jan 2026 23:57:34 +0100 Subject: [PATCH 024/146] Do not validate `diagnostic::do_not_recommend` args --- compiler/rustc_attr_parsing/src/parser.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/parser.rs b/compiler/rustc_attr_parsing/src/parser.rs index 72b0fc63cc15..63c82ccbc7df 100644 --- a/compiler/rustc_attr_parsing/src/parser.rs +++ b/compiler/rustc_attr_parsing/src/parser.rs @@ -113,9 +113,12 @@ impl ArgParser { Some(match value { AttrArgs::Empty => Self::NoArgs, AttrArgs::Delimited(args) => { - // The arguments of rustc_dummy and diagnostic attributes are not validated - // if the arguments are delimited - if parts == &[sym::rustc_dummy] || parts[0] == sym::diagnostic { + // The arguments of rustc_dummy and diagnostic::do_not_recommend are not validated + // if the arguments are delimited. + // See https://doc.rust-lang.org/reference/attributes/diagnostics.html#r-attributes.diagnostic.namespace.unknown-invalid-syntax + if parts == &[sym::rustc_dummy] + || parts == &[sym::diagnostic, sym::do_not_recommend] + { return Some(ArgParser::List(MetaItemListParser { sub_parsers: ThinVec::new(), span: args.dspan.entire(), From c8c7b5b449d243a4ee5474e49e9bb112d56264aa Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 14 Jan 2026 00:58:35 +0100 Subject: [PATCH 025/146] Generate macro expansion for rust compiler crates docs --- src/bootstrap/src/core/build_steps/doc.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bootstrap/src/core/build_steps/doc.rs b/src/bootstrap/src/core/build_steps/doc.rs index b86582807f72..fa36a6471cae 100644 --- a/src/bootstrap/src/core/build_steps/doc.rs +++ b/src/bootstrap/src/core/build_steps/doc.rs @@ -932,6 +932,7 @@ impl Step for Rustc { // see https://github.com/rust-lang/rust/pull/122066#issuecomment-1983049222 // If there is any bug, please comment out the next line. cargo.rustdocflag("--generate-link-to-definition"); + cargo.rustdocflag("--generate-macro-expansion"); compile::rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates); cargo.arg("-Zskip-rustdoc-fingerprint"); From 0c57e8c83266603eb2ef4e899fe76c783073ce7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 7 Jan 2026 16:57:33 +0100 Subject: [PATCH 026/146] Change `bors build finished` job to `publish toolstate` --- .github/workflows/ci.yml | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0fe906cb8622..e6a00bb42785 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -305,30 +305,22 @@ jobs: DD_GITHUB_JOB_NAME: ${{ matrix.full_name }} run: ./build/citool/debug/citool upload-build-metrics build/cpu-usage.csv - # This job isused to tell bors the final status of the build, as there is no practical way to detect - # when a workflow is successful listening to webhooks only in our current bors implementation (homu). + # This job is used to publish toolstate for successful auto builds. outcome: - name: bors build finished + name: publish toolstate runs-on: ubuntu-24.04 needs: [ calculate_matrix, job ] - # !cancelled() executes the job regardless of whether the previous jobs passed or failed - if: ${{ !cancelled() && contains(fromJSON('["auto", "try"]'), needs.calculate_matrix.outputs.run_type) }} - environment: ${{ ((github.repository == 'rust-lang/rust' && (github.ref == 'refs/heads/try-perf' || github.ref == 'refs/heads/automation/bors/try' || github.ref == 'refs/heads/automation/bors/auto')) && 'bors') || '' }} + if: ${{ needs.calculate_matrix.outputs.run_type == 'auto' }} + environment: ${{ (github.repository == 'rust-lang/rust' && 'bors') || '' }} steps: - name: checkout the source code uses: actions/checkout@v5 with: fetch-depth: 2 - # Calculate the exit status of the whole CI workflow. - # If all dependent jobs were successful, this exits with 0 (and the outcome job continues successfully). - # If a some dependent job has failed, this exits with 1. - - name: calculate the correct exit status - run: jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< '${{ toJson(needs) }}' # Publish the toolstate if an auto build succeeds (just before push to the default branch) - name: publish toolstate run: src/ci/publish_toolstate.sh shell: bash - if: needs.calculate_matrix.outputs.run_type == 'auto' env: TOOLSTATE_ISSUES_API_URL: https://api.github.com/repos/rust-lang/rust/issues TOOLSTATE_PUBLISH: 1 From 414e00d3509a4cfedaab0d9c712a5f41861ea0c6 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 14 Jan 2026 15:55:49 +1100 Subject: [PATCH 027/146] Clarify the docs/examples for `ProjectionElem::ConstantIndex` --- compiler/rustc_middle/src/mir/syntax.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 83e9a1f1784b..6ec874fb15f7 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -1221,25 +1221,32 @@ pub enum ProjectionElem { /// thing is true of the `ConstantIndex` and `Subslice` projections below. Index(V), - /// These indices are generated by slice patterns. Easiest to explain - /// by example: + /// These endpoint-relative indices are generated by slice/array patterns. + /// + /// For array types, `offset` is always relative to the start of the array. + /// For slice types, `from_end` determines whether `offset` is relative to + /// the start or the end of the slice being inspected. + /// + /// Slice-pattern indices are easiest to explain by the position of `X` in + /// these examples: /// /// ```ignore (illustrative) - /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false }, - /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false }, - /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true }, - /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true }, + /// [X, _, .., _, _] => { offset: 0, min_length: 4, from_end: false }, + /// [_, X, .., _, _] => { offset: 1, min_length: 4, from_end: false }, + /// [_, _, .., X, _] => { offset: 2, min_length: 4, from_end: true }, + /// [_, _, .., _, X] => { offset: 1, min_length: 4, from_end: true }, /// ``` ConstantIndex { - /// index or -index (in Python terms), depending on from_end + /// - If `from_end == false`, this is a 0-based offset from the start of the array/slice. + /// - If `from_end == true`, this is a 1-based offset from the end of the slice. offset: u64, /// The thing being indexed must be at least this long -- otherwise, the /// projection is UB. /// /// For arrays this is always the exact length. min_length: u64, - /// Counting backwards from end? This is always false when indexing an - /// array. + /// If `true`, `offset` is a 1-based offset from the end of the slice. + /// Always false when indexing an array. from_end: bool, }, From a9ce7503d51b2be5a71a25315b4b4cb63eebf8b6 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 14 Jan 2026 14:53:57 +1100 Subject: [PATCH 028/146] Pull array length determination out of `prefix_slice_suffix` --- .../src/builder/matches/match_pair.rs | 85 +++++++++++-------- 1 file changed, 48 insertions(+), 37 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs index 8cee3ff27e8f..19b4cd70c0b9 100644 --- a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -40,33 +40,22 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { match_pairs: &mut Vec>, extra_data: &mut PatternExtraData<'tcx>, place: &PlaceBuilder<'tcx>, + array_len: Option, prefix: &[Pat<'tcx>], opt_slice: &Option>>, suffix: &[Pat<'tcx>], ) { - let tcx = self.tcx; - let (min_length, exact_size) = if let Some(place_resolved) = place.try_to_place(self) { - let place_ty = place_resolved.ty(&self.local_decls, tcx).ty; - match place_ty.kind() { - ty::Array(_, length) => { - if let Some(length) = length.try_to_target_usize(tcx) { - (length, true) - } else { - // This can happen when the array length is a generic const - // expression that couldn't be evaluated (e.g., due to an error). - // Since there's already a compilation error, we use a fallback - // to avoid an ICE. - tcx.dcx().span_delayed_bug( - tcx.def_span(self.def_id), - "array length in pattern couldn't be evaluated", - ); - ((prefix.len() + suffix.len()).try_into().unwrap(), false) - } - } - _ => ((prefix.len() + suffix.len()).try_into().unwrap(), false), - } - } else { - ((prefix.len() + suffix.len()).try_into().unwrap(), false) + let prefix_len = u64::try_from(prefix.len()).unwrap(); + let suffix_len = u64::try_from(suffix.len()).unwrap(); + + // For slice patterns with a `..` followed by 0 or more suffix subpatterns, + // the actual slice index of those subpatterns isn't statically known, so + // we have to index them relative to the end of the slice. + // + // For array patterns, all subpatterns are indexed relative to the start. + let (min_length, is_array) = match array_len { + Some(len) => (len, true), + None => (prefix_len + suffix_len, false), }; for (idx, subpattern) in prefix.iter().enumerate() { @@ -77,11 +66,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } if let Some(subslice_pat) = opt_slice { - let suffix_len = suffix.len() as u64; let subslice = place.clone_project(PlaceElem::Subslice { - from: prefix.len() as u64, - to: if exact_size { min_length - suffix_len } else { suffix_len }, - from_end: !exact_size, + from: prefix_len, + to: if is_array { min_length - suffix_len } else { suffix_len }, + from_end: !is_array, }); MatchPairTree::for_pattern(subslice, subslice_pat, self, match_pairs, extra_data); } @@ -89,9 +77,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { for (idx, subpattern) in suffix.iter().rev().enumerate() { let end_offset = (idx + 1) as u64; let elem = ProjectionElem::ConstantIndex { - offset: if exact_size { min_length - end_offset } else { end_offset }, + offset: if is_array { min_length - end_offset } else { end_offset }, min_length, - from_end: !exact_size, + from_end: !is_array, }; let place = place.clone_project(elem); MatchPairTree::for_pattern(place, subpattern, self, match_pairs, extra_data) @@ -256,14 +244,36 @@ impl<'tcx> MatchPairTree<'tcx> { } PatKind::Array { ref prefix, ref slice, ref suffix } => { - cx.prefix_slice_suffix( - &mut subpairs, - extra_data, - &place_builder, - prefix, - slice, - suffix, - ); + // Determine the statically-known length of the array type being matched. + // This should always succeed for legal programs, but could fail for + // erroneous programs (e.g. the type is `[u8; const { panic!() }]`), + // so take care not to ICE if this fails. + let array_len = match pattern.ty.kind() { + ty::Array(_, len) => len.try_to_target_usize(cx.tcx), + _ => None, + }; + if let Some(array_len) = array_len { + cx.prefix_slice_suffix( + &mut subpairs, + extra_data, + &place_builder, + Some(array_len), + prefix, + slice, + suffix, + ); + } else { + // If the array length couldn't be determined, ignore the + // subpatterns and delayed-assert that compilation will fail. + cx.tcx.dcx().span_delayed_bug( + pattern.span, + format!( + "array length in pattern couldn't be determined for ty={:?}", + pattern.ty + ), + ); + } + None } PatKind::Slice { ref prefix, ref slice, ref suffix } => { @@ -271,6 +281,7 @@ impl<'tcx> MatchPairTree<'tcx> { &mut subpairs, extra_data, &place_builder, + None, prefix, slice, suffix, From a72083f739c369cd1ce675a1d278505656674af6 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 14 Jan 2026 16:13:49 +1100 Subject: [PATCH 029/146] Avoid some more usize-to-u64 casts in `prefix_slice_suffix` --- .../rustc_mir_build/src/builder/matches/match_pair.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs index 19b4cd70c0b9..3edd0234b0ad 100644 --- a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -58,9 +58,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { None => (prefix_len + suffix_len, false), }; - for (idx, subpattern) in prefix.iter().enumerate() { - let elem = - ProjectionElem::ConstantIndex { offset: idx as u64, min_length, from_end: false }; + for (offset, subpattern) in (0u64..).zip(prefix) { + let elem = ProjectionElem::ConstantIndex { offset, min_length, from_end: false }; let place = place.clone_project(elem); MatchPairTree::for_pattern(place, subpattern, self, match_pairs, extra_data) } @@ -74,8 +73,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { MatchPairTree::for_pattern(subslice, subslice_pat, self, match_pairs, extra_data); } - for (idx, subpattern) in suffix.iter().rev().enumerate() { - let end_offset = (idx + 1) as u64; + for (end_offset, subpattern) in (1u64..).zip(suffix.iter().rev()) { let elem = ProjectionElem::ConstantIndex { offset: if is_array { min_length - end_offset } else { end_offset }, min_length, From 5769006794df86e3a27fedbc5317f695c0f153e6 Mon Sep 17 00:00:00 2001 From: dianqk Date: Wed, 14 Jan 2026 18:57:17 +0800 Subject: [PATCH 030/146] Run dummy_span.rs test with SimplifyComparisonIntegral --- tests/debuginfo/dummy_span.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/debuginfo/dummy_span.rs b/tests/debuginfo/dummy_span.rs index fec4f33e3d56..6cf79c46d9a9 100644 --- a/tests/debuginfo/dummy_span.rs +++ b/tests/debuginfo/dummy_span.rs @@ -1,6 +1,8 @@ //@ min-lldb-version: 310 //@ compile-flags:-g +// FIXME: Investigate why test fails without SimplifyComparisonIntegral pass. +//@ compile-flags: -Zmir-enable-passes=+SimplifyComparisonIntegral //@ ignore-backends: gcc // === GDB TESTS =================================================================================== From 0361bd004a5074e7fddc8479bca9414e03178e04 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Mon, 12 Jan 2026 02:10:41 +0300 Subject: [PATCH 031/146] resolve: In `visit_scopes` do not extract ctxt out of span unless necessary --- compiler/rustc_resolve/src/diagnostics.rs | 5 ++++- compiler/rustc_resolve/src/ident.rs | 19 +++++++++++-------- compiler/rustc_resolve/src/late.rs | 8 +++----- compiler/rustc_resolve/src/lib.rs | 2 +- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 7bc08f1de546..899f81525529 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -32,7 +32,9 @@ use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::edition::Edition; use rustc_span::hygiene::MacroKind; use rustc_span::source_map::{SourceMap, Spanned}; -use rustc_span::{BytePos, Ident, Macros20NormalizedIdent, Span, Symbol, SyntaxContext, kw, sym}; +use rustc_span::{ + BytePos, DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, SyntaxContext, kw, sym, +}; use thin_vec::{ThinVec, thin_vec}; use tracing::{debug, instrument}; @@ -1179,6 +1181,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { ctxt: SyntaxContext, filter_fn: &impl Fn(Res) -> bool, ) { + let ctxt = DUMMY_SP.with_ctxt(ctxt); self.cm().visit_scopes(scope_set, ps, ctxt, None, |this, scope, use_prelude, _| { match scope { Scope::DeriveHelpers(expn_id) => { diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index 7f04216c5553..f7e628048ccd 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -53,13 +53,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { mut self: CmResolver<'r, 'ra, 'tcx>, scope_set: ScopeSet<'ra>, parent_scope: &ParentScope<'ra>, - orig_ctxt: SyntaxContext, + // Location of the span is not significant, but pass a `Span` instead of `SyntaxContext` + // to avoid extracting and re-packaging the syntax context unnecessarily. + orig_ctxt: Span, derive_fallback_lint_id: Option, mut visitor: impl FnMut( &mut CmResolver<'r, 'ra, 'tcx>, Scope<'ra>, UsePrelude, - SyntaxContext, + Span, ) -> ControlFlow, ) -> Option { // General principles: @@ -238,11 +240,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { fn hygienic_lexical_parent( &self, module: Module<'ra>, - ctxt: &mut SyntaxContext, + span: &mut Span, derive_fallback_lint_id: Option, ) -> Option<(Module<'ra>, Option)> { - if !module.expansion.outer_expn_is_descendant_of(*ctxt) { - return Some((self.expn_def_scope(ctxt.remove_mark()), None)); + let ctxt = span.ctxt(); + if !module.expansion.outer_expn_is_descendant_of(ctxt) { + return Some((self.expn_def_scope(span.remove_mark()), None)); } if let ModuleKind::Block = module.kind { @@ -272,7 +275,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let ext = &self.get_macro_by_def_id(def_id).ext; if ext.builtin_name.is_none() && ext.macro_kinds() == MacroKinds::DERIVE - && parent.expansion.outer_expn_is_descendant_of(*ctxt) + && parent.expansion.outer_expn_is_descendant_of(ctxt) { return Some((parent, derive_fallback_lint_id)); } @@ -433,10 +436,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let break_result = self.visit_scopes( scope_set, parent_scope, - orig_ident.span.ctxt(), + orig_ident.span, derive_fallback_lint_id, |this, scope, use_prelude, ctxt| { - let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt)); + let ident = Ident::new(orig_ident.name, ctxt); // The passed `ctxt` is already normalized, so avoid expensive double normalization. let ident = Macros20NormalizedIdent(ident); let res = match this.reborrow().resolve_ident_in_scope( diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 6d0097631772..6557e1dea1a1 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -37,9 +37,7 @@ use rustc_session::config::{CrateType, ResolveDocLinks}; use rustc_session::lint; use rustc_session::parse::feature_err; use rustc_span::source_map::{Spanned, respan}; -use rustc_span::{ - BytePos, DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, SyntaxContext, kw, sym, -}; +use rustc_span::{BytePos, DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, kw, sym}; use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; use tracing::{debug, instrument, trace}; @@ -5224,7 +5222,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { self.r.traits_in_scope( self.current_trait_ref.as_ref().map(|(module, _)| *module), &self.parent_scope, - ident.span.ctxt(), + ident.span, Some((ident.name, ns)), ) } @@ -5323,7 +5321,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { .entry(self.parent_scope.module.nearest_parent_mod().expect_local()) .or_insert_with(|| { self.r - .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None) + .traits_in_scope(None, &self.parent_scope, DUMMY_SP, None) .into_iter() .filter_map(|tr| { if self.is_invalid_proc_macro_item_for_doc(tr.def_id) { diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index c4c1e06f94ae..0939f8cddbe5 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1918,7 +1918,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { &mut self, current_trait: Option>, parent_scope: &ParentScope<'ra>, - ctxt: SyntaxContext, + ctxt: Span, assoc_item: Option<(Symbol, Namespace)>, ) -> Vec { let mut found_traits = Vec::new(); From 79ec275e2d513d5f1b8a685a20476b9b700674fe Mon Sep 17 00:00:00 2001 From: Asuna Date: Wed, 14 Jan 2026 17:00:22 +0100 Subject: [PATCH 032/146] Support primitives in type info reflection Support {bool,char,int,uint,float,str} primitive types for feature `type_info` reflection. --- .../src/const_eval/type_info.rs | 84 +++++++- compiler/rustc_span/src/symbol.rs | 8 +- library/core/src/mem/type_info.rs | 75 ++++++- library/coretests/tests/mem/type_info.rs | 39 +++- .../const_prop/invalid_constant.main.GVN.diff | 2 +- .../invalid_constant.main.RemoveZsts.diff | 2 +- tests/ui/lint/recommend-literal.rs | 2 + tests/ui/lint/recommend-literal.stderr | 22 ++- tests/ui/reflection/dump.bit32.run.stdout | 186 ++++++++++++++++++ tests/ui/reflection/dump.bit64.run.stdout | 186 ++++++++++++++++++ tests/ui/reflection/dump.rs | 33 ++-- tests/ui/reflection/dump.run.stdout | 31 --- ...stion-when-stmt-and-expr-span-equal.stderr | 4 +- tests/ui/traits/issue-77982.stderr | 2 +- tests/ui/try-trait/bad-interconversion.stderr | 2 +- 15 files changed, 612 insertions(+), 66 deletions(-) create mode 100644 tests/ui/reflection/dump.bit32.run.stdout create mode 100644 tests/ui/reflection/dump.bit64.run.stdout delete mode 100644 tests/ui/reflection/dump.run.stdout diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index 814c81278a10..fc3378275be2 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -35,6 +35,7 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { interp_ok((variant_id, self.project_downcast(&field_dest, variant_id)?)) }; + let ptr_bit_width = || self.tcx.data_layout.pointer_size().bits(); match field.name { sym::kind => { let variant_index = match ty.kind() { @@ -64,13 +65,60 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { variant } - // For now just merge all primitives into one `Leaf` variant with no data - ty::Uint(_) | ty::Int(_) | ty::Float(_) | ty::Char | ty::Bool => { - downcast(sym::Leaf)?.0 + ty::Bool => { + let (variant, variant_place) = downcast(sym::Bool)?; + let place = self.project_field(&variant_place, FieldIdx::ZERO)?; + self.write_primitive_type_info(place, ty, None)?; + variant + } + ty::Char => { + let (variant, variant_place) = downcast(sym::Char)?; + let place = self.project_field(&variant_place, FieldIdx::ZERO)?; + self.write_primitive_type_info(place, ty, None)?; + variant + } + ty::Int(int_ty) => { + let (variant, variant_place) = downcast(sym::Int)?; + let place = self.project_field(&variant_place, FieldIdx::ZERO)?; + self.write_primitive_type_info( + place, + ty, + Some( + int_ty + .bit_width() + .unwrap_or_else(/* isize */ ptr_bit_width), + ), + )?; + variant + } + ty::Uint(uint_ty) => { + let (variant, variant_place) = downcast(sym::Uint)?; + let place = self.project_field(&variant_place, FieldIdx::ZERO)?; + self.write_primitive_type_info( + place, + ty, + Some( + uint_ty + .bit_width() + .unwrap_or_else(/* usize */ ptr_bit_width), + ), + )?; + variant + } + ty::Float(float_ty) => { + let (variant, variant_place) = downcast(sym::Float)?; + let place = self.project_field(&variant_place, FieldIdx::ZERO)?; + self.write_primitive_type_info(place, ty, Some(float_ty.bit_width()))?; + variant + } + ty::Str => { + let (variant, variant_place) = downcast(sym::Str)?; + let place = self.project_field(&variant_place, FieldIdx::ZERO)?; + self.write_primitive_type_info(place, ty, None)?; + variant } ty::Adt(_, _) | ty::Foreign(_) - | ty::Str | ty::Pat(_, _) | ty::Slice(_) | ty::RawPtr(..) @@ -203,4 +251,32 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { interp_ok(()) } + + // This method always writes to field `ty`. + // If field `bit_width` is present, it also writes to it (in which case parameter `write_bit_width` must be `Some`). + fn write_primitive_type_info( + &mut self, + place: impl Writeable<'tcx, CtfeProvenance>, + ty: Ty<'tcx>, + write_bit_width: Option, + ) -> InterpResult<'tcx> { + for (field_idx, field) in + place.layout().ty.ty_adt_def().unwrap().non_enum_variant().fields.iter_enumerated() + { + let field_place = self.project_field(&place, field_idx)?; + match field.name { + sym::ty => self.write_type_id(ty, &field_place)?, + sym::bit_width => { + let bit_width = write_bit_width + .expect("type info struct needs a `bit_width` but none was provided"); + self.write_scalar( + ScalarInt::try_from_target_usize(bit_width, self.tcx.tcx).unwrap(), + &field_place, + )? + } + other => span_bug!(self.tcx.def_span(field.did), "unimplemented field {other}"), + } + } + interp_ok(()) + } } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 34804160ed39..4c19fa83fd3a 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -190,6 +190,7 @@ symbols! { BTreeMap, BTreeSet, BinaryHeap, + Bool, Borrow, BorrowMut, Break, @@ -202,6 +203,7 @@ symbols! { Capture, Cell, Center, + Char, Child, Cleanup, Clone, @@ -238,6 +240,7 @@ symbols! { Error, File, FileType, + Float, FmtArgumentsNew, FmtWrite, Fn, @@ -263,6 +266,7 @@ symbols! { IndexOutput, Input, Instant, + Int, Into, IntoFuture, IntoIterator, @@ -285,7 +289,6 @@ symbols! { IteratorItem, IteratorMap, Layout, - Leaf, Left, LinkedList, LintDiagnostic, @@ -363,6 +366,7 @@ symbols! { Some, SpanCtxt, Stdin, + Str, String, StructuralPartialEq, SubdiagMessage, @@ -387,6 +391,7 @@ symbols! { Ty, TyCtxt, TyKind, + Uint, Unknown, Unsize, UnsizedConstParamTy, @@ -584,6 +589,7 @@ symbols! { binaryheap_iter, bind_by_move_pattern_guards, bindings_after_at, + bit_width, bitand, bitand_assign, bitor, diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index e4ccc408f1c6..7db4f3b00123 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -45,9 +45,18 @@ pub enum TypeKind { Tuple(Tuple), /// Arrays. Array(Array), - /// Primitives - /// FIXME(#146922): disambiguate further - Leaf, + /// Primitive boolean type. + Bool(Bool), + /// Primitive character type. + Char(Char), + /// Primitive signed integer type. + Int(Int), + /// Primitive unsigned integer type. + Uint(Uint), + /// Primitive floating-point type. + Float(Float), + /// String slice type. + Str(Str), /// FIXME(#146922): add all the common types Other, } @@ -82,3 +91,63 @@ pub struct Array { /// The length of the array. pub len: usize, } + +/// Compile-time type information about `bool`. +#[derive(Debug)] +#[non_exhaustive] +#[unstable(feature = "type_info", issue = "146922")] +pub struct Bool { + /// The type id of `bool`. + pub ty: TypeId, +} + +/// Compile-time type information about `char`. +#[derive(Debug)] +#[non_exhaustive] +#[unstable(feature = "type_info", issue = "146922")] +pub struct Char { + /// The type id of `char`. + pub ty: TypeId, +} + +/// Compile-time type information about signed integer types. +#[derive(Debug)] +#[non_exhaustive] +#[unstable(feature = "type_info", issue = "146922")] +pub struct Int { + /// The type id of signed integer type. + pub ty: TypeId, + /// The bit width of the signed integer type. + pub bit_width: usize, +} + +/// Compile-time type information about unsigned integer types. +#[derive(Debug)] +#[non_exhaustive] +#[unstable(feature = "type_info", issue = "146922")] +pub struct Uint { + /// The type id of unsigned integer type. + pub ty: TypeId, + /// The bit width of the unsigned integer type. + pub bit_width: usize, +} + +/// Compile-time type information about floating-point types. +#[derive(Debug)] +#[non_exhaustive] +#[unstable(feature = "type_info", issue = "146922")] +pub struct Float { + /// The type id of floating-point type. + pub ty: TypeId, + /// The bit width of the floating-point type. + pub bit_width: usize, +} + +/// Compile-time type information about string slice types. +#[derive(Debug)] +#[non_exhaustive] +#[unstable(feature = "type_info", issue = "146922")] +pub struct Str { + /// The type id of `str`. + pub ty: TypeId, +} diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index b3b8d96d49b0..5dd8f4034d11 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -46,7 +46,10 @@ fn test_tuples() { assert!(b.offset == 1); match (a.ty.info().kind, b.ty.info().kind) { - (TypeKind::Leaf, TypeKind::Leaf) => {} + (TypeKind::Uint(a), TypeKind::Uint(b)) => { + assert!(a.bit_width == 8); + assert!(b.bit_width == 8); + } _ => unreachable!(), } } @@ -54,3 +57,37 @@ fn test_tuples() { } } } + +#[test] +fn test_primitives() { + use TypeKind::*; + + let Type { kind: Bool(_ty), size, .. } = (const { Type::of::() }) else { panic!() }; + assert_eq!(size, Some(1)); + + let Type { kind: Char(_ty), size, .. } = (const { Type::of::() }) else { panic!() }; + assert_eq!(size, Some(4)); + + let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; + assert_eq!(size, Some(4)); + assert_eq!(ty.bit_width, 32); + + let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; + assert_eq!(size, Some(size_of::())); + assert_eq!(ty.bit_width, size_of::() * 8); + + let Type { kind: Uint(ty), size, .. } = (const { Type::of::() }) else { panic!() }; + assert_eq!(size, Some(4)); + assert_eq!(ty.bit_width, 32); + + let Type { kind: Uint(ty), size, .. } = (const { Type::of::() }) else { panic!() }; + assert_eq!(size, Some(size_of::())); + assert_eq!(ty.bit_width, size_of::() * 8); + + let Type { kind: Float(ty), size, .. } = (const { Type::of::() }) else { panic!() }; + assert_eq!(size, Some(4)); + assert_eq!(ty.bit_width, 32); + + let Type { kind: Str(_ty), size, .. } = (const { Type::of::() }) else { panic!() }; + assert_eq!(size, None); +} diff --git a/tests/mir-opt/const_prop/invalid_constant.main.GVN.diff b/tests/mir-opt/const_prop/invalid_constant.main.GVN.diff index 20923d0352cd..3dc6fc9e3f65 100644 --- a/tests/mir-opt/const_prop/invalid_constant.main.GVN.diff +++ b/tests/mir-opt/const_prop/invalid_constant.main.GVN.diff @@ -19,7 +19,7 @@ debug _enum_without_variants => const [ZeroSized: Empty]; let _9: main::Str<"���">; scope 4 { - debug _non_utf8_str => const Str::<"���">; + debug _non_utf8_str => const main::Str::<"���">; } } } diff --git a/tests/mir-opt/const_prop/invalid_constant.main.RemoveZsts.diff b/tests/mir-opt/const_prop/invalid_constant.main.RemoveZsts.diff index 6593b329756c..c16cbaf4c0f2 100644 --- a/tests/mir-opt/const_prop/invalid_constant.main.RemoveZsts.diff +++ b/tests/mir-opt/const_prop/invalid_constant.main.RemoveZsts.diff @@ -21,7 +21,7 @@ let _9: main::Str<"���">; scope 4 { - debug _non_utf8_str => _9; -+ debug _non_utf8_str => const Str::<"���">; ++ debug _non_utf8_str => const main::Str::<"���">; } } } diff --git a/tests/ui/lint/recommend-literal.rs b/tests/ui/lint/recommend-literal.rs index 45f9ae0a7bdf..be074c111453 100644 --- a/tests/ui/lint/recommend-literal.rs +++ b/tests/ui/lint/recommend-literal.rs @@ -1,3 +1,5 @@ +//~vv HELP consider importing this struct + type Real = double; //~^ ERROR cannot find type `double` in this scope //~| HELP perhaps you intended to use this type diff --git a/tests/ui/lint/recommend-literal.stderr b/tests/ui/lint/recommend-literal.stderr index 6b6dd134e1d2..01e993df17a9 100644 --- a/tests/ui/lint/recommend-literal.stderr +++ b/tests/ui/lint/recommend-literal.stderr @@ -1,5 +1,5 @@ error[E0425]: cannot find type `double` in this scope - --> $DIR/recommend-literal.rs:1:13 + --> $DIR/recommend-literal.rs:3:13 | LL | type Real = double; | ^^^^^^ @@ -8,7 +8,7 @@ LL | type Real = double; | help: perhaps you intended to use this type: `f64` error[E0425]: cannot find type `long` in this scope - --> $DIR/recommend-literal.rs:7:12 + --> $DIR/recommend-literal.rs:9:12 | LL | let y: long = 74802374902374923; | ^^^^ @@ -17,7 +17,7 @@ LL | let y: long = 74802374902374923; | help: perhaps you intended to use this type: `i64` error[E0425]: cannot find type `Boolean` in this scope - --> $DIR/recommend-literal.rs:10:13 + --> $DIR/recommend-literal.rs:12:13 | LL | let v1: Boolean = true; | ^^^^^^^ @@ -26,7 +26,7 @@ LL | let v1: Boolean = true; | help: perhaps you intended to use this type: `bool` error[E0425]: cannot find type `Bool` in this scope - --> $DIR/recommend-literal.rs:13:13 + --> $DIR/recommend-literal.rs:15:13 | LL | let v2: Bool = true; | ^^^^ @@ -41,9 +41,13 @@ help: perhaps you intended to use this type LL - let v2: Bool = true; LL + let v2: bool = true; | +help: consider importing this struct + | +LL + use std::mem::type_info::Bool; + | error[E0425]: cannot find type `boolean` in this scope - --> $DIR/recommend-literal.rs:19:9 + --> $DIR/recommend-literal.rs:21:9 | LL | fn z(a: boolean) { | ^^^^^^^ @@ -52,7 +56,7 @@ LL | fn z(a: boolean) { | help: perhaps you intended to use this type: `bool` error[E0425]: cannot find type `byte` in this scope - --> $DIR/recommend-literal.rs:24:11 + --> $DIR/recommend-literal.rs:26:11 | LL | fn a() -> byte { | ^^^^ @@ -61,7 +65,7 @@ LL | fn a() -> byte { | help: perhaps you intended to use this type: `u8` error[E0425]: cannot find type `float` in this scope - --> $DIR/recommend-literal.rs:31:12 + --> $DIR/recommend-literal.rs:33:12 | LL | width: float, | ^^^^^ @@ -70,7 +74,7 @@ LL | width: float, | help: perhaps you intended to use this type: `f32` error[E0425]: cannot find type `int` in this scope - --> $DIR/recommend-literal.rs:34:19 + --> $DIR/recommend-literal.rs:36:19 | LL | depth: Option, | ^^^ not found in this scope @@ -86,7 +90,7 @@ LL | struct Data { | +++++ error[E0425]: cannot find type `short` in this scope - --> $DIR/recommend-literal.rs:40:16 + --> $DIR/recommend-literal.rs:42:16 | LL | impl Stuff for short {} | ^^^^^ diff --git a/tests/ui/reflection/dump.bit32.run.stdout b/tests/ui/reflection/dump.bit32.run.stdout new file mode 100644 index 000000000000..d747ee210204 --- /dev/null +++ b/tests/ui/reflection/dump.bit32.run.stdout @@ -0,0 +1,186 @@ +Type { + kind: Tuple( + Tuple { + fields: [ + Field { + ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + offset: 0, + }, + Field { + ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + offset: 1, + }, + Field { + ty: TypeId(0x41223169ff28813ba79b7268a2a968d9), + offset: 2, + }, + ], + }, + ), + size: Some( + 2, + ), +} +Type { + kind: Array( + Array { + element_ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + len: 2, + }, + ), + size: Some( + 2, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0x12427c993eca190c841e0d92c5b7a45d), + bit_width: 8, + }, + ), + size: Some( + 1, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0x56ced5e4a15bd89050bb9674fa2df013), + bit_width: 32, + }, + ), + size: Some( + 4, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0xae6c4318bb07632e00428affbea41961), + bit_width: 64, + }, + ), + size: Some( + 8, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0xc7164498f3902dde0d8194a7b9733e79), + bit_width: 128, + }, + ), + size: Some( + 16, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0x1e5f92831c560aac8658b980a22e60b0), + bit_width: 32, + }, + ), + size: Some( + 4, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + bit_width: 8, + }, + ), + size: Some( + 1, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x1378bb1c0a0202683eb65e7c11f2e4d7), + bit_width: 32, + }, + ), + size: Some( + 4, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x9ed91be891e304132cb86891e578f4a5), + bit_width: 64, + }, + ), + size: Some( + 8, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x7bf7411d57d603e9fb393892a9c3f362), + bit_width: 128, + }, + ), + size: Some( + 16, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x763d199bccd319899208909ed1a860c6), + bit_width: 32, + }, + ), + size: Some( + 4, + ), +} +Type { + kind: Other, + size: Some( + 4, + ), +} +Type { + kind: Other, + size: Some( + 12, + ), +} +Type { + kind: Other, + size: Some( + 8, + ), +} +Type { + kind: Other, + size: Some( + 8, + ), +} +Type { + kind: Other, + size: Some( + 8, + ), +} +Type { + kind: Str( + Str { + ty: TypeId(0x474ccf3b5db264ef53916706f7d7bb2c), + }, + ), + size: None, +} +Type { + kind: Other, + size: None, +} diff --git a/tests/ui/reflection/dump.bit64.run.stdout b/tests/ui/reflection/dump.bit64.run.stdout new file mode 100644 index 000000000000..180a6e2882d7 --- /dev/null +++ b/tests/ui/reflection/dump.bit64.run.stdout @@ -0,0 +1,186 @@ +Type { + kind: Tuple( + Tuple { + fields: [ + Field { + ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + offset: 0, + }, + Field { + ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + offset: 1, + }, + Field { + ty: TypeId(0x41223169ff28813ba79b7268a2a968d9), + offset: 2, + }, + ], + }, + ), + size: Some( + 2, + ), +} +Type { + kind: Array( + Array { + element_ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + len: 2, + }, + ), + size: Some( + 2, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0x12427c993eca190c841e0d92c5b7a45d), + bit_width: 8, + }, + ), + size: Some( + 1, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0x56ced5e4a15bd89050bb9674fa2df013), + bit_width: 32, + }, + ), + size: Some( + 4, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0xae6c4318bb07632e00428affbea41961), + bit_width: 64, + }, + ), + size: Some( + 8, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0xc7164498f3902dde0d8194a7b9733e79), + bit_width: 128, + }, + ), + size: Some( + 16, + ), +} +Type { + kind: Int( + Int { + ty: TypeId(0x1e5f92831c560aac8658b980a22e60b0), + bit_width: 64, + }, + ), + size: Some( + 8, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + bit_width: 8, + }, + ), + size: Some( + 1, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x1378bb1c0a0202683eb65e7c11f2e4d7), + bit_width: 32, + }, + ), + size: Some( + 4, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x9ed91be891e304132cb86891e578f4a5), + bit_width: 64, + }, + ), + size: Some( + 8, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x7bf7411d57d603e9fb393892a9c3f362), + bit_width: 128, + }, + ), + size: Some( + 16, + ), +} +Type { + kind: Uint( + Uint { + ty: TypeId(0x763d199bccd319899208909ed1a860c6), + bit_width: 64, + }, + ), + size: Some( + 8, + ), +} +Type { + kind: Other, + size: Some( + 4, + ), +} +Type { + kind: Other, + size: Some( + 24, + ), +} +Type { + kind: Other, + size: Some( + 16, + ), +} +Type { + kind: Other, + size: Some( + 16, + ), +} +Type { + kind: Other, + size: Some( + 16, + ), +} +Type { + kind: Str( + Str { + ty: TypeId(0x474ccf3b5db264ef53916706f7d7bb2c), + }, + ), + size: None, +} +Type { + kind: Other, + size: None, +} diff --git a/tests/ui/reflection/dump.rs b/tests/ui/reflection/dump.rs index 0adcda481b5a..584b7c8ed4ae 100644 --- a/tests/ui/reflection/dump.rs +++ b/tests/ui/reflection/dump.rs @@ -1,6 +1,11 @@ -#![feature(type_info)] +// Some types whose length depends on the target pointer length will be dumped. +//@ revisions: bit32 bit64 +//@[bit32] only-32bit +//@[bit64] only-64bit //@ run-pass //@ check-run-results + +#![feature(type_info)] #![allow(dead_code)] use std::mem::type_info::Type; @@ -20,14 +25,20 @@ struct Unsized { s: str, } -fn main() { - println!("{:#?}", const { Type::of::<(u8, u8, ())>() }.kind); - println!("{:#?}", const { Type::of::<[u8; 2]>() }.kind); - println!("{:#?}", const { Type::of::() }.kind); - println!("{:#?}", const { Type::of::() }.kind); - println!("{:#?}", const { Type::of::<&Unsized>() }.kind); - println!("{:#?}", const { Type::of::<&str>() }.kind); - println!("{:#?}", const { Type::of::<&[u8]>() }.kind); - println!("{:#?}", const { Type::of::() }.kind); - println!("{:#?}", const { Type::of::<[u8]>() }.kind); +macro_rules! dump_types { + ($($ty:ty),+ $(,)?) => { + $(println!("{:#?}", const { Type::of::<$ty>() });)+ + }; +} + +fn main() { + dump_types! { + (u8, u8, ()), + [u8; 2], + i8, i32, i64, i128, isize, + u8, u32, u64, u128, usize, + Foo, Bar, + &Unsized, &str, &[u8], + str, [u8], + } } diff --git a/tests/ui/reflection/dump.run.stdout b/tests/ui/reflection/dump.run.stdout deleted file mode 100644 index dfd128664e2d..000000000000 --- a/tests/ui/reflection/dump.run.stdout +++ /dev/null @@ -1,31 +0,0 @@ -Tuple( - Tuple { - fields: [ - Field { - ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), - offset: 0, - }, - Field { - ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), - offset: 1, - }, - Field { - ty: TypeId(0x41223169ff28813ba79b7268a2a968d9), - offset: 2, - }, - ], - }, -) -Array( - Array { - element_ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), - len: 2, - }, -) -Other -Other -Other -Other -Other -Other -Other diff --git a/tests/ui/suggestions/semi-suggestion-when-stmt-and-expr-span-equal.stderr b/tests/ui/suggestions/semi-suggestion-when-stmt-and-expr-span-equal.stderr index aa96159aacf5..9f34d2747881 100644 --- a/tests/ui/suggestions/semi-suggestion-when-stmt-and-expr-span-equal.stderr +++ b/tests/ui/suggestions/semi-suggestion-when-stmt-and-expr-span-equal.stderr @@ -21,14 +21,14 @@ LL | .collect::(); | = help: the trait `FromIterator<()>` is not implemented for `String` = help: the following other types implement trait `FromIterator`: - `String` implements `FromIterator<&Char>` `String` implements `FromIterator<&char>` + `String` implements `FromIterator<&std::ascii::Char>` `String` implements `FromIterator<&str>` `String` implements `FromIterator>` - `String` implements `FromIterator` `String` implements `FromIterator>` `String` implements `FromIterator` `String` implements `FromIterator` + `String` implements `FromIterator` note: the method call chain might not have had the expected associated types --> $DIR/semi-suggestion-when-stmt-and-expr-span-equal.rs:20:10 | diff --git a/tests/ui/traits/issue-77982.stderr b/tests/ui/traits/issue-77982.stderr index 4bc24e81215a..b1baabc4394b 100644 --- a/tests/ui/traits/issue-77982.stderr +++ b/tests/ui/traits/issue-77982.stderr @@ -44,10 +44,10 @@ LL | let ips: Vec<_> = (0..100_000).map(|_| u32::from(0u32.into())).collect( | type must be known at this point | = note: multiple `impl`s satisfying `u32: From<_>` found in the `core` crate: - - impl From for u32; - impl From for u32; - impl From for u32; - impl From for u32; + - impl From for u32; - impl From for u32; - impl From for u32; help: try using a fully qualified path to specify the expected types diff --git a/tests/ui/try-trait/bad-interconversion.stderr b/tests/ui/try-trait/bad-interconversion.stderr index 61fecaf89917..f8c0deba99ba 100644 --- a/tests/ui/try-trait/bad-interconversion.stderr +++ b/tests/ui/try-trait/bad-interconversion.stderr @@ -18,7 +18,7 @@ help: the following other types implement trait `From` = note: in this macro invocation --> $SRC_DIR/core/src/ascii/ascii_char.rs:LL:COL | - = note: `u8` implements `From` + = note: `u8` implements `From` ::: $SRC_DIR/core/src/ascii/ascii_char.rs:LL:COL | = note: in this macro invocation From 1028c7a66a718a6421241b3a46268681f79fd597 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maja=20K=C4=85dzio=C5=82ka?= Date: Sun, 11 Jan 2026 20:10:22 +0100 Subject: [PATCH 033/146] Avoid ICEs after bad patterns, for the other syntactic variants --- compiler/rustc_hir_typeck/src/pat.rs | 13 +++--- tests/ui/pattern/type_mismatch.rs | 63 ++++++++++++++++++++++++++- tests/ui/pattern/type_mismatch.stderr | 61 +++++++++++++++++++++++++- 3 files changed, 128 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 90e22b2cd381..b56ab6dcb4ab 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -1512,11 +1512,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pat_info: PatInfo<'tcx>, ) -> Ty<'tcx> { // Type-check the path. - let _ = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info); + let had_err = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info); // Type-check subpatterns. match self.check_struct_pat_fields(pat_ty, pat, variant, fields, has_rest_pat, pat_info) { - Ok(()) => pat_ty, + Ok(()) => match had_err { + Ok(()) => pat_ty, + Err(guar) => Ty::new_error(self.tcx, guar), + }, Err(guar) => Ty::new_error(self.tcx, guar), } } @@ -1764,8 +1767,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Type-check the tuple struct pattern against the expected type. - let diag = self.demand_eqtype_pat_diag(pat.span, expected, pat_ty, &pat_info.top_info); - let had_err = diag.map_err(|diag| diag.emit()); + let had_err = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info); // Type-check subpatterns. if subpats.len() == variant.fields.len() @@ -1989,11 +1991,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Err(reported) = self.demand_eqtype_pat(span, expected, pat_ty, &pat_info.top_info) { // Walk subpatterns with an expected type of `err` in this case to silence // further errors being emitted when using the bindings. #50333 - let element_tys_iter = (0..max_len).map(|_| Ty::new_error(tcx, reported)); for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) { self.check_pat(elem, Ty::new_error(tcx, reported), pat_info); } - Ty::new_tup_from_iter(tcx, element_tys_iter) + Ty::new_error(tcx, reported) } else { for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) { self.check_pat(elem, element_tys[i], pat_info); diff --git a/tests/ui/pattern/type_mismatch.rs b/tests/ui/pattern/type_mismatch.rs index 408ff7588471..39d57301e98f 100644 --- a/tests/ui/pattern/type_mismatch.rs +++ b/tests/ui/pattern/type_mismatch.rs @@ -1,4 +1,4 @@ -//! This test used to ICE: rust-lang/rust#109812 +//! These tests used to ICE: rust-lang/rust#109812, rust-lang/rust#150507 //! Instead of actually analyzing the erroneous patterns, //! we instead stop after typeck where errors are already //! reported. @@ -8,12 +8,21 @@ enum Either { One(X), Two(X), + Three { a: X }, } struct X(Y); struct Y; +struct Z(*const i32); +unsafe impl Send for Z {} + +enum Meow { + A { a: Z }, + B(Z), +} + fn consume_fnmut(_: impl FnMut()) {} fn move_into_fnmut() { @@ -25,6 +34,58 @@ fn move_into_fnmut() { let X(mut _t) = x; }); + + consume_fnmut(|| { + let Either::Three { a: ref mut _t } = x; + //~^ ERROR: mismatched types + + let X(mut _t) = x; + }); +} + +fn tuple_against_array() { + let variant: [();1] = [()]; + + || match variant { + (2,) => (), + //~^ ERROR: mismatched types + _ => {} + }; + + || { + let ((2,) | _) = variant; + //~^ ERROR: mismatched types + }; +} + +// Reproducer that triggers the compatibility lint more reliably, instead of relying on the fact +// that at the time of writing, an unresolved integer type variable does not implement any +// auto-traits. +// +// The @_ makes this example also reproduce ICE #150507 before PR #138961 +fn arcane() { + let variant: [();1] = [()]; + + || { + match variant { + (Z(y@_),) => {} + //~^ ERROR: mismatched types + } + }; + + || { + match variant { + Meow::A { a: Z(y@_) } => {} + //~^ ERROR: mismatched types + } + }; + + || { + match variant { + Meow::B(Z(y@_)) => {} + //~^ ERROR: mismatched types + } + }; } fn main() {} diff --git a/tests/ui/pattern/type_mismatch.stderr b/tests/ui/pattern/type_mismatch.stderr index b0441b1fadcf..3f24b2e70694 100644 --- a/tests/ui/pattern/type_mismatch.stderr +++ b/tests/ui/pattern/type_mismatch.stderr @@ -1,11 +1,68 @@ error[E0308]: mismatched types - --> $DIR/type_mismatch.rs:23:13 + --> $DIR/type_mismatch.rs:32:13 | LL | let Either::Two(ref mut _t) = x; | ^^^^^^^^^^^^^^^^^^^^^^^ - this expression has type `X` | | | expected `X`, found `Either` -error: aborting due to 1 previous error +error[E0308]: mismatched types + --> $DIR/type_mismatch.rs:39:13 + | +LL | let Either::Three { a: ref mut _t } = x; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - this expression has type `X` + | | + | expected `X`, found `Either` + +error[E0308]: mismatched types + --> $DIR/type_mismatch.rs:50:9 + | +LL | || match variant { + | ------- this expression has type `[(); 1]` +LL | (2,) => (), + | ^^^^ expected `[(); 1]`, found `(_,)` + | + = note: expected array `[(); 1]` + found tuple `(_,)` + +error[E0308]: mismatched types + --> $DIR/type_mismatch.rs:56:14 + | +LL | let ((2,) | _) = variant; + | ^^^^ ------- this expression has type `[(); 1]` + | | + | expected `[(); 1]`, found `(_,)` + | + = note: expected array `[(); 1]` + found tuple `(_,)` + +error[E0308]: mismatched types + --> $DIR/type_mismatch.rs:71:13 + | +LL | match variant { + | ------- this expression has type `[(); 1]` +LL | (Z(y@_),) => {} + | ^^^^^^^^^ expected `[(); 1]`, found `(_,)` + | + = note: expected array `[(); 1]` + found tuple `(_,)` + +error[E0308]: mismatched types + --> $DIR/type_mismatch.rs:78:13 + | +LL | match variant { + | ------- this expression has type `[(); 1]` +LL | Meow::A { a: Z(y@_) } => {} + | ^^^^^^^^^^^^^^^^^^^^^ expected `[(); 1]`, found `Meow` + +error[E0308]: mismatched types + --> $DIR/type_mismatch.rs:85:13 + | +LL | match variant { + | ------- this expression has type `[(); 1]` +LL | Meow::B(Z(y@_)) => {} + | ^^^^^^^^^^^^^^^ expected `[(); 1]`, found `Meow` + +error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0308`. From e4e2e8bd6f607e16c35c966f16a616daced632e7 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 14 Jan 2026 16:37:01 +0100 Subject: [PATCH 034/146] Fix `deprecated` attribute intra-doc link not resolved in the right location on reexported item --- .../passes/collect_intra_doc_links.rs | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 07d6efaa97e1..8a37f46b9a96 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -7,7 +7,6 @@ use std::fmt::Display; use std::mem; use std::ops::Range; -use rustc_ast::attr::AttributeExt; use rustc_ast::util::comments::may_have_doc_links; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; @@ -1038,10 +1037,11 @@ fn preprocessed_markdown_links(s: &str) -> Vec { impl LinkCollector<'_, '_> { #[instrument(level = "debug", skip_all)] fn resolve_links(&mut self, item: &Item) { + let tcx = self.cx.tcx; if !self.cx.document_private() && let Some(def_id) = item.item_id.as_def_id() && let Some(def_id) = def_id.as_local() - && !self.cx.tcx.effective_visibilities(()).is_exported(def_id) + && !tcx.effective_visibilities(()).is_exported(def_id) && !has_primitive_or_keyword_or_attribute_docs(&item.attrs.other_attrs) { // Skip link resolution for non-exported items. @@ -1049,9 +1049,9 @@ impl LinkCollector<'_, '_> { } let mut insert_links = |item_id, doc: &str| { - let module_id = match self.cx.tcx.def_kind(item_id) { - DefKind::Mod if item.inner_docs(self.cx.tcx) => item_id, - _ => find_nearest_parent_module(self.cx.tcx, item_id).unwrap(), + let module_id = match tcx.def_kind(item_id) { + DefKind::Mod if item.inner_docs(tcx) => item_id, + _ => find_nearest_parent_module(tcx, item_id).unwrap(), }; for md_link in preprocessed_markdown_links(&doc) { let link = self.resolve_link(&doc, item, item_id, module_id, &md_link); @@ -1084,7 +1084,14 @@ impl LinkCollector<'_, '_> { // Also resolve links in the note text of `#[deprecated]`. for attr in &item.attrs.other_attrs { - let Some(note_sym) = attr.deprecation_note() else { continue }; + let rustc_hir::Attribute::Parsed(rustc_hir::attrs::AttributeKind::Deprecation { + span, + deprecation, + }) = attr + else { + continue; + }; + let Some(note_sym) = deprecation.note else { continue }; let note = note_sym.as_str(); if !may_have_doc_links(note) { @@ -1092,7 +1099,18 @@ impl LinkCollector<'_, '_> { } debug!("deprecated_note={note}"); - insert_links(item.item_id.expect_def_id(), note) + // When resolving an intra-doc link inside a deprecation note that is on an inlined + // `use` statement, we need to use the `def_id` of the `use` statement, not the + // inlined item. + // + let item_id = if let Some(inline_stmt_id) = item.inline_stmt_id + && item.span(tcx).is_none_or(|item_span| !item_span.inner().contains(*span)) + { + inline_stmt_id.to_def_id() + } else { + item.item_id.expect_def_id() + }; + insert_links(item_id, note) } } From c341745970fa9f18e5f87166bba95574231edebf Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 14 Jan 2026 16:37:24 +0100 Subject: [PATCH 035/146] Add regression test for #151028 --- .../intra-doc/ice-deprecated-note-on-reexport.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 tests/rustdoc-html/intra-doc/ice-deprecated-note-on-reexport.rs diff --git a/tests/rustdoc-html/intra-doc/ice-deprecated-note-on-reexport.rs b/tests/rustdoc-html/intra-doc/ice-deprecated-note-on-reexport.rs new file mode 100644 index 000000000000..99415a9a2fd4 --- /dev/null +++ b/tests/rustdoc-html/intra-doc/ice-deprecated-note-on-reexport.rs @@ -0,0 +1,11 @@ +// This test ensures that the intra-doc link in `deprecated` note is resolved at the correct +// location (ie in the current crate and not in the reexported item's location/crate) and +// therefore doesn't crash. +// +// This is a regression test for . + +#![crate_name = "foo"] + +#[deprecated(note = "use [`std::mem::forget`]")] +#[doc(inline)] +pub use std::mem::drop; From 4bacdf7b8b9046507ef5ae3bcb349d54fb827b0d Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 14 Jan 2026 22:47:53 +0100 Subject: [PATCH 036/146] Reduce rustdoc GUI flakyness, take 2 --- tests/rustdoc-gui/utils.goml | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/tests/rustdoc-gui/utils.goml b/tests/rustdoc-gui/utils.goml index c0625ead2f1a..c5c8ab3b1af8 100644 --- a/tests/rustdoc-gui/utils.goml +++ b/tests/rustdoc-gui/utils.goml @@ -29,9 +29,18 @@ define-function: ( "open-settings-menu", [], block { - call-function: ("click-settings-button", {}) - // Wait for the popover to appear... - wait-for-css: ("#settings", {"display": "block"}) + store-count: ("#settings", nb_settings_menu) + if: (|nb_settings_menu| != 0, block { + store-css: ("#settings", {"display": settings_display}) + }) + else: block { + store-value: (settings_display, "none") + } + if: (|settings_display| != "block", block { + call-function: ("click-settings-button", {}) + // Wait for the popover to appear... + wait-for-css: ("#settings", {"display": "block"}) + }) } ) @@ -39,9 +48,18 @@ define-function: ( "close-settings-menu", [], block { - call-function: ("click-settings-button", {}) - // Wait for the popover to disappear... - wait-for-css-false: ("#settings", {"display": "block"}) + store-count: ("#settings", nb_settings_menu) + if: (|nb_settings_menu| != 0, block { + store-css: ("#settings", {"display": settings_display}) + }) + else: block { + store-value: (settings_display, "block") + } + if: (|settings_display| == "block", block { + call-function: ("click-settings-button", {}) + // Wait for the popover to disappear... + wait-for-css-false: ("#settings", {"display": "block"}) + }) } ) From 36d37fd11b43e4cce1a2d993497937c40db9a7a2 Mon Sep 17 00:00:00 2001 From: dianne Date: Thu, 8 Jan 2026 15:44:41 -0800 Subject: [PATCH 037/146] THIR: directly contain `HirId`s, not `LintLevel`s --- compiler/rustc_middle/src/thir.rs | 8 +- compiler/rustc_middle/src/thir/visit.rs | 8 +- compiler/rustc_mir_build/src/builder/block.rs | 12 +-- .../src/builder/expr/as_constant.rs | 2 +- .../src/builder/expr/as_operand.rs | 8 +- .../src/builder/expr/as_place.rs | 4 +- .../src/builder/expr/as_rvalue.rs | 8 +- .../src/builder/expr/as_temp.rs | 10 ++- .../rustc_mir_build/src/builder/expr/into.rs | 4 +- .../rustc_mir_build/src/builder/expr/stmt.rs | 8 +- .../src/builder/matches/mod.rs | 6 +- .../rustc_mir_build/src/check_unsafety.rs | 2 +- compiler/rustc_mir_build/src/thir/cx/block.rs | 2 +- compiler/rustc_mir_build/src/thir/cx/expr.rs | 4 +- .../src/thir/pattern/check_match.rs | 66 +++++++--------- compiler/rustc_mir_build/src/thir/print.rs | 12 +-- tests/ui/thir-print/c-variadic.stdout | 2 +- tests/ui/thir-print/offset_of.stdout | 76 +++++++++---------- .../thir-print/thir-flat-const-variant.stdout | 36 +++------ tests/ui/thir-print/thir-flat.stdout | 4 +- .../ui/thir-print/thir-tree-loop-match.stdout | 24 +++--- tests/ui/thir-print/thir-tree-match.stdout | 20 ++--- tests/ui/thir-print/thir-tree.stdout | 2 +- tests/ui/unpretty/box.stdout | 8 +- 24 files changed, 155 insertions(+), 181 deletions(-) diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 3683c1cfb7dd..86bd6fb803b7 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -236,8 +236,8 @@ pub enum StmtKind<'tcx> { /// `let pat: ty = else { }` else_block: Option, - /// The lint level for this `let` statement. - lint_level: LintLevel, + /// The [`HirId`] for this `let` statement. + hir_id: HirId, /// Span of the `let = ` part. span: Span, @@ -271,7 +271,7 @@ pub enum ExprKind<'tcx> { /// and to track the `HirId` of the expressions within the scope. Scope { region_scope: region::Scope, - lint_level: LintLevel, + hir_id: HirId, value: ExprId, }, /// A `box ` expression. @@ -579,7 +579,7 @@ pub struct Arm<'tcx> { pub pattern: Box>, pub guard: Option, pub body: ExprId, - pub lint_level: LintLevel, + pub hir_id: HirId, pub scope: region::Scope, pub span: Span, } diff --git a/compiler/rustc_middle/src/thir/visit.rs b/compiler/rustc_middle/src/thir/visit.rs index d792bbe60c88..4e30c450c89b 100644 --- a/compiler/rustc_middle/src/thir/visit.rs +++ b/compiler/rustc_middle/src/thir/visit.rs @@ -47,9 +47,7 @@ pub fn walk_expr<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( use ExprKind::*; let Expr { kind, ty: _, temp_scope_id: _, span: _ } = expr; match *kind { - Scope { value, region_scope: _, lint_level: _ } => { - visitor.visit_expr(&visitor.thir()[value]) - } + Scope { value, region_scope: _, hir_id: _ } => visitor.visit_expr(&visitor.thir()[value]), Box { value } => visitor.visit_expr(&visitor.thir()[value]), If { cond, then, else_opt, if_then_scope: _ } => { visitor.visit_expr(&visitor.thir()[cond]); @@ -205,7 +203,7 @@ pub fn walk_stmt<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( remainder_scope: _, init_scope: _, pattern, - lint_level: _, + hir_id: _, else_block, span: _, } => { @@ -238,7 +236,7 @@ pub fn walk_arm<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( visitor: &mut V, arm: &'thir Arm<'tcx>, ) { - let Arm { guard, pattern, body, lint_level: _, span: _, scope: _ } = arm; + let Arm { guard, pattern, body, hir_id: _, span: _, scope: _ } = arm; if let Some(expr) = guard { visitor.visit_expr(&visitor.thir()[*expr]) } diff --git a/compiler/rustc_mir_build/src/builder/block.rs b/compiler/rustc_mir_build/src/builder/block.rs index 88533ad22648..d8837d2b195a 100644 --- a/compiler/rustc_mir_build/src/builder/block.rs +++ b/compiler/rustc_mir_build/src/builder/block.rs @@ -83,7 +83,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { init_scope, pattern, initializer: Some(initializer), - lint_level, + hir_id, else_block: Some(else_block), span: _, } => { @@ -191,7 +191,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let initializer_span = this.thir[*initializer].span; let scope = (*init_scope, source_info); - let failure_and_block = this.in_scope(scope, *lint_level, |this| { + let lint_level = LintLevel::Explicit(*hir_id); + let failure_and_block = this.in_scope(scope, lint_level, |this| { this.declare_bindings( visibility_scope, remainder_span, @@ -232,7 +233,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { init_scope, pattern, initializer, - lint_level, + hir_id, else_block: None, span: _, } => { @@ -250,12 +251,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { Some(this.new_source_scope(remainder_span, LintLevel::Inherited)); // Evaluate the initializer, if present. + let lint_level = LintLevel::Explicit(*hir_id); if let Some(init) = *initializer { let initializer_span = this.thir[init].span; let scope = (*init_scope, source_info); block = this - .in_scope(scope, *lint_level, |this| { + .in_scope(scope, lint_level, |this| { this.declare_bindings( visibility_scope, remainder_span, @@ -269,7 +271,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { .into_block(); } else { let scope = (*init_scope, source_info); - let _: BlockAnd<()> = this.in_scope(scope, *lint_level, |this| { + let _: BlockAnd<()> = this.in_scope(scope, lint_level, |this| { this.declare_bindings( visibility_scope, remainder_span, diff --git a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs index 186fde4883df..39b4390f7749 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs @@ -23,7 +23,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let tcx = this.tcx; let Expr { ty, temp_scope_id: _, span, ref kind } = *expr; match kind { - ExprKind::Scope { region_scope: _, lint_level: _, value } => { + ExprKind::Scope { region_scope: _, hir_id: _, value } => { this.as_constant(&this.thir[*value]) } _ => as_constant_inner( diff --git a/compiler/rustc_mir_build/src/builder/expr/as_operand.rs b/compiler/rustc_mir_build/src/builder/expr/as_operand.rs index 5989a15b9346..c9c166b7f018 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_operand.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_operand.rs @@ -122,10 +122,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let this = self; // See "LET_THIS_SELF". let expr = &this.thir[expr_id]; - if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { + if let ExprKind::Scope { region_scope, hir_id, value } = expr.kind { let source_info = this.source_info(expr.span); let region_scope = (region_scope, source_info); - return this.in_scope(region_scope, lint_level, |this| { + return this.in_scope(region_scope, LintLevel::Explicit(hir_id), |this| { this.as_operand(block, scope, value, local_info, needs_temporary) }); } @@ -165,10 +165,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let expr = &this.thir[expr_id]; debug!("as_call_operand(block={:?}, expr={:?})", block, expr); - if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { + if let ExprKind::Scope { region_scope, hir_id, value } = expr.kind { let source_info = this.source_info(expr.span); let region_scope = (region_scope, source_info); - return this.in_scope(region_scope, lint_level, |this| { + return this.in_scope(region_scope, LintLevel::Explicit(hir_id), |this| { this.as_call_operand(block, scope, value) }); } diff --git a/compiler/rustc_mir_build/src/builder/expr/as_place.rs b/compiler/rustc_mir_build/src/builder/expr/as_place.rs index cb81b42128a8..db9aa3cd8704 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_place.rs @@ -427,8 +427,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let expr_span = expr.span; let source_info = this.source_info(expr_span); match expr.kind { - ExprKind::Scope { region_scope, lint_level, value } => { - this.in_scope((region_scope, source_info), lint_level, |this| { + ExprKind::Scope { region_scope, hir_id, value } => { + this.in_scope((region_scope, source_info), LintLevel::Explicit(hir_id), |this| { this.expr_as_place(block, value, mutability, fake_borrow_temps) }) } diff --git a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs index bb1095ced47a..3d1774bd1d68 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs @@ -56,9 +56,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { match expr.kind { ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)), - ExprKind::Scope { region_scope, lint_level, value } => { + ExprKind::Scope { region_scope, hir_id, value } => { let region_scope = (region_scope, source_info); - this.in_scope(region_scope, lint_level, |this| this.as_rvalue(block, scope, value)) + this.in_scope(region_scope, LintLevel::Explicit(hir_id), |this| { + this.as_rvalue(block, scope, value) + }) } ExprKind::Repeat { value, count } => { if Some(0) == count.try_to_target_usize(this.tcx) { @@ -657,7 +659,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { source: eid, is_from_as_cast: _, } - | &ExprKind::Scope { region_scope: _, lint_level: _, value: eid } => { + | &ExprKind::Scope { region_scope: _, hir_id: _, value: eid } => { kind = &self.thir[eid].kind } _ => return matches!(Category::of(&kind), Some(Category::Constant)), diff --git a/compiler/rustc_mir_build/src/builder/expr/as_temp.rs b/compiler/rustc_mir_build/src/builder/expr/as_temp.rs index d8ac19e34aae..2aace64062cd 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_temp.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_temp.rs @@ -39,10 +39,12 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let expr = &this.thir[expr_id]; let expr_span = expr.span; let source_info = this.source_info(expr_span); - if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { - return this.in_scope((region_scope, source_info), lint_level, |this| { - this.as_temp(block, temp_lifetime, value, mutability) - }); + if let ExprKind::Scope { region_scope, hir_id, value } = expr.kind { + return this.in_scope( + (region_scope, source_info), + LintLevel::Explicit(hir_id), + |this| this.as_temp(block, temp_lifetime, value, mutability), + ); } let expr_ty = expr.ty; diff --git a/compiler/rustc_mir_build/src/builder/expr/into.rs b/compiler/rustc_mir_build/src/builder/expr/into.rs index f595cfc77e9d..9731f0de135f 100644 --- a/compiler/rustc_mir_build/src/builder/expr/into.rs +++ b/compiler/rustc_mir_build/src/builder/expr/into.rs @@ -45,10 +45,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } let block_and = match expr.kind { - ExprKind::Scope { region_scope, lint_level, value } => { + ExprKind::Scope { region_scope, hir_id, value } => { let region_scope = (region_scope, source_info); ensure_sufficient_stack(|| { - this.in_scope(region_scope, lint_level, |this| { + this.in_scope(region_scope, LintLevel::Explicit(hir_id), |this| { this.expr_into_dest(destination, block, value) }) }) diff --git a/compiler/rustc_mir_build/src/builder/expr/stmt.rs b/compiler/rustc_mir_build/src/builder/expr/stmt.rs index 66ee13939849..f28e483b6a5d 100644 --- a/compiler/rustc_mir_build/src/builder/expr/stmt.rs +++ b/compiler/rustc_mir_build/src/builder/expr/stmt.rs @@ -25,8 +25,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Handle a number of expressions that don't need a destination at all. This // avoids needing a mountain of temporary `()` variables. match expr.kind { - ExprKind::Scope { region_scope, lint_level, value } => { - this.in_scope((region_scope, source_info), lint_level, |this| { + ExprKind::Scope { region_scope, hir_id, value } => { + this.in_scope((region_scope, source_info), LintLevel::Explicit(hir_id), |this| { this.stmt_expr(block, value, statement_scope) }) } @@ -106,7 +106,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } ExprKind::Become { value } => { let v = &this.thir[value]; - let ExprKind::Scope { value, lint_level, region_scope } = v.kind else { + let ExprKind::Scope { value, hir_id, region_scope } = v.kind else { span_bug!(v.span, "`thir_check_tail_calls` should have disallowed this {v:?}") }; @@ -115,7 +115,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { span_bug!(v.span, "`thir_check_tail_calls` should have disallowed this {v:?}") }; - this.in_scope((region_scope, source_info), lint_level, |this| { + this.in_scope((region_scope, source_info), LintLevel::Explicit(hir_id), |this| { let fun = unpack!(block = this.as_local_operand(block, fun)); let args: Box<[_]> = args .into_iter() diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 9080e2ba801b..49caee4a1896 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -182,9 +182,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.break_for_else(success_block, args.variable_source_info); failure_block.unit() } - ExprKind::Scope { region_scope, lint_level, value } => { + ExprKind::Scope { region_scope, hir_id, value } => { let region_scope = (region_scope, this.source_info(expr_span)); - this.in_scope(region_scope, lint_level, |this| { + this.in_scope(region_scope, LintLevel::Explicit(hir_id), |this| { this.then_else_break_inner(block, value, args) }) } @@ -434,7 +434,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let guard_scope = arm .guard .map(|_| region::Scope { data: region::ScopeData::MatchGuard, ..arm.scope }); - self.in_scope(arm_scope, arm.lint_level, |this| { + self.in_scope(arm_scope, LintLevel::Explicit(arm.hir_id), |this| { this.opt_in_scope(guard_scope.map(|scope| (scope, arm_source_info)), |this| { // `if let` guard temps needing deduplicating will be in the guard scope. let old_dedup_scope = diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 4f03e3d965c6..e330242c8a1f 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -478,7 +478,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { } }; match expr.kind { - ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => { + ExprKind::Scope { value, hir_id, region_scope: _ } => { let prev_id = self.hir_context; self.hir_context = hir_id; ensure_sufficient_stack(|| { diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index 7cdd70a7fc27..fad73a7115b0 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -88,7 +88,7 @@ impl<'tcx> ThirBuildCx<'tcx> { pattern, initializer: local.init.map(|init| self.mirror_expr(init)), else_block, - lint_level: LintLevel::Explicit(local.hir_id), + hir_id: local.hir_id, span, }, }; diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 50ccbd50d971..8e02424706ee 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -77,7 +77,7 @@ impl<'tcx> ThirBuildCx<'tcx> { kind: ExprKind::Scope { region_scope: expr_scope, value: self.thir.exprs.push(expr), - lint_level: LintLevel::Explicit(hir_expr.hir_id), + hir_id: hir_expr.hir_id, }, }; @@ -1192,7 +1192,7 @@ impl<'tcx> ThirBuildCx<'tcx> { pattern: self.pattern_from_hir(&arm.pat), guard: arm.guard.as_ref().map(|g| self.mirror_expr(g)), body: self.mirror_expr(arm.body), - lint_level: LintLevel::Explicit(arm.hir_id), + hir_id: arm.hir_id, scope: region::Scope { local_id: arm.hir_id.local_id, data: region::ScopeData::Node }, span: arm.span, }; 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 bf480cf601ee..b8c64d98881b 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -43,7 +43,7 @@ pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), Err typeck_results, // FIXME(#132279): We're in a body, should handle opaques. typing_env: ty::TypingEnv::non_body_analysis(tcx, def_id), - lint_level: tcx.local_def_id_to_hir_id(def_id), + hir_source: tcx.local_def_id_to_hir_id(def_id), let_source: LetSource::None, pattern_arena: &pattern_arena, dropless_arena: &dropless_arena, @@ -92,7 +92,7 @@ struct MatchVisitor<'p, 'tcx> { typing_env: ty::TypingEnv<'tcx>, typeck_results: &'tcx ty::TypeckResults<'tcx>, thir: &'p Thir<'tcx>, - lint_level: HirId, + hir_source: HirId, let_source: LetSource, pattern_arena: &'p TypedArena>, dropless_arena: &'p DroplessArena, @@ -111,7 +111,7 @@ impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> { #[instrument(level = "trace", skip(self))] fn visit_arm(&mut self, arm: &'p Arm<'tcx>) { - self.with_lint_level(arm.lint_level, |this| { + self.with_hir_source(arm.hir_id, |this| { if let Some(expr) = arm.guard { this.with_let_source(LetSource::IfLetGuard, |this| { this.visit_expr(&this.thir[expr]) @@ -125,8 +125,8 @@ impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> { #[instrument(level = "trace", skip(self))] fn visit_expr(&mut self, ex: &'p Expr<'tcx>) { match ex.kind { - ExprKind::Scope { value, lint_level, .. } => { - self.with_lint_level(lint_level, |this| { + ExprKind::Scope { value, hir_id, .. } => { + self.with_hir_source(hir_id, |this| { this.visit_expr(&this.thir[value]); }); return; @@ -181,10 +181,8 @@ impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> { fn visit_stmt(&mut self, stmt: &'p Stmt<'tcx>) { match stmt.kind { - StmtKind::Let { - box ref pattern, initializer, else_block, lint_level, span, .. - } => { - self.with_lint_level(lint_level, |this| { + StmtKind::Let { box ref pattern, initializer, else_block, hir_id, span, .. } => { + self.with_hir_source(hir_id, |this| { let let_source = if else_block.is_some() { LetSource::LetElse } else { LetSource::PlainLet }; this.with_let_source(let_source, |this| { @@ -209,20 +207,12 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { self.let_source = old_let_source; } - fn with_lint_level( - &mut self, - new_lint_level: LintLevel, - f: impl FnOnce(&mut Self) -> T, - ) -> T { - if let LintLevel::Explicit(hir_id) = new_lint_level { - let old_lint_level = self.lint_level; - self.lint_level = hir_id; - let ret = f(self); - self.lint_level = old_lint_level; - ret - } else { - f(self) - } + fn with_hir_source(&mut self, new_hir_source: HirId, f: impl FnOnce(&mut Self) -> T) -> T { + let old_hir_source = self.hir_source; + self.hir_source = new_hir_source; + let ret = f(self); + self.hir_source = old_hir_source; + ret } /// Visit a nested chain of `&&`. Used for if-let chains. This must call `visit_expr` on the @@ -233,9 +223,9 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { accumulator: &mut Vec>, ) -> Result<(), ErrorGuaranteed> { match ex.kind { - ExprKind::Scope { value, lint_level, .. } => self.with_lint_level(lint_level, |this| { - this.visit_land(&this.thir[value], accumulator) - }), + ExprKind::Scope { value, hir_id, .. } => { + self.with_hir_source(hir_id, |this| this.visit_land(&this.thir[value], accumulator)) + } ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => { // We recurse into the lhs only, because `&&` chains associate to the left. let res_lhs = self.visit_land(&self.thir[lhs], accumulator); @@ -259,8 +249,8 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { ex: &'p Expr<'tcx>, ) -> Result, ErrorGuaranteed> { match ex.kind { - ExprKind::Scope { value, lint_level, .. } => { - self.with_lint_level(lint_level, |this| this.visit_land_rhs(&this.thir[value])) + ExprKind::Scope { value, hir_id, .. } => { + self.with_hir_source(hir_id, |this| this.visit_land_rhs(&this.thir[value])) } ExprKind::Let { box ref pat, expr } => { let expr = &self.thir()[expr]; @@ -398,9 +388,9 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { tcx: self.tcx, typeck_results: self.typeck_results, typing_env: self.typing_env, - module: self.tcx.parent_module(self.lint_level).to_def_id(), + module: self.tcx.parent_module(self.hir_source).to_def_id(), dropless_arena: self.dropless_arena, - match_lint_level: self.lint_level, + match_lint_level: self.hir_source, whole_match_span, scrut_span, refutable, @@ -448,7 +438,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { if matches!(refutability, Irrefutable) { report_irrefutable_let_patterns( self.tcx, - self.lint_level, + self.hir_source, self.let_source, 1, span, @@ -470,10 +460,10 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { let mut tarms = Vec::with_capacity(arms.len()); for &arm in arms { let arm = &self.thir.arms[arm]; - let got_error = self.with_lint_level(arm.lint_level, |this| { + let got_error = self.with_hir_source(arm.hir_id, |this| { let Ok(pat) = this.lower_pattern(&cx, &arm.pattern) else { return true }; let arm = - MatchArm { pat, arm_data: this.lint_level, has_guard: arm.guard.is_some() }; + MatchArm { pat, arm_data: this.hir_source, has_guard: arm.guard.is_some() }; tarms.push(arm); false }); @@ -572,7 +562,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { // The entire chain is made up of irrefutable `let` statements report_irrefutable_let_patterns( self.tcx, - self.lint_level, + self.hir_source, self.let_source, chain_refutabilities.len(), whole_chain_span, @@ -605,7 +595,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { let count = prefix.len(); self.tcx.emit_node_span_lint( IRREFUTABLE_LET_PATTERNS, - self.lint_level, + self.hir_source, span, LeadingIrrefutableLetPatterns { count }, ); @@ -624,7 +614,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { let count = suffix.len(); self.tcx.emit_node_span_lint( IRREFUTABLE_LET_PATTERNS, - self.lint_level, + self.hir_source, span, TrailingIrrefutableLetPatterns { count }, ); @@ -639,7 +629,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { ) -> Result<(PatCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> { let cx = self.new_cx(refutability, None, scrut, pat.span); let pat = self.lower_pattern(&cx, pat)?; - let arms = [MatchArm { pat, arm_data: self.lint_level, has_guard: false }]; + let arms = [MatchArm { pat, arm_data: self.hir_source, has_guard: false }]; let report = self.analyze_patterns(&cx, &arms, pat.ty().inner())?; Ok((cx, report)) } @@ -893,7 +883,7 @@ fn check_for_bindings_named_same_as_variants( let ty_path = with_no_trimmed_paths!(cx.tcx.def_path_str(edef.did())); cx.tcx.emit_node_span_lint( BINDINGS_WITH_VARIANT_NAME, - cx.lint_level, + cx.hir_source, pat.span, BindingsWithVariantName { // If this is an irrefutable pattern, and there's > 1 variant, diff --git a/compiler/rustc_mir_build/src/thir/print.rs b/compiler/rustc_mir_build/src/thir/print.rs index 5a2d6cfef1cc..d837aa3d70ca 100644 --- a/compiler/rustc_mir_build/src/thir/print.rs +++ b/compiler/rustc_mir_build/src/thir/print.rs @@ -142,7 +142,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { pattern, initializer, else_block, - lint_level, + hir_id, span, } => { print_indented!(self, "kind: Let {", depth_lvl + 1); @@ -173,7 +173,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { print_indented!(self, "else_block: None", depth_lvl + 2); } - print_indented!(self, format!("lint_level: {:?}", lint_level), depth_lvl + 2); + print_indented!(self, format!("hir_id: {:?}", hir_id), depth_lvl + 2); print_indented!(self, format!("span: {:?}", span), depth_lvl + 2); print_indented!(self, "}", depth_lvl + 1); } @@ -197,10 +197,10 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { use rustc_middle::thir::ExprKind::*; match expr_kind { - Scope { region_scope, value, lint_level } => { + Scope { region_scope, value, hir_id } => { print_indented!(self, "Scope {", depth_lvl); print_indented!(self, format!("region_scope: {:?}", region_scope), depth_lvl + 1); - print_indented!(self, format!("lint_level: {:?}", lint_level), depth_lvl + 1); + print_indented!(self, format!("hir_id: {:?}", hir_id), depth_lvl + 1); print_indented!(self, "value:", depth_lvl + 1); self.print_expr(*value, depth_lvl + 2); print_indented!(self, "}", depth_lvl); @@ -642,7 +642,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { print_indented!(self, "Arm {", depth_lvl); let arm = &self.thir.arms[arm_id]; - let Arm { pattern, guard, body, lint_level, scope, span } = arm; + let Arm { pattern, guard, body, hir_id, scope, span } = arm; print_indented!(self, "pattern: ", depth_lvl + 1); self.print_pat(pattern, depth_lvl + 2); @@ -656,7 +656,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { print_indented!(self, "body: ", depth_lvl + 1); self.print_expr(*body, depth_lvl + 2); - print_indented!(self, format!("lint_level: {:?}", lint_level), depth_lvl + 1); + print_indented!(self, format!("hir_id: {:?}", hir_id), depth_lvl + 1); print_indented!(self, format!("scope: {:?}", scope), depth_lvl + 1); print_indented!(self, format!("span: {:?}", span), depth_lvl + 1); print_indented!(self, "}", depth_lvl); diff --git a/tests/ui/thir-print/c-variadic.stdout b/tests/ui/thir-print/c-variadic.stdout index f1905e04f72b..a3e3fa5e0008 100644 --- a/tests/ui/thir-print/c-variadic.stdout +++ b/tests/ui/thir-print/c-variadic.stdout @@ -39,7 +39,7 @@ body: kind: Scope { region_scope: Node(6) - lint_level: Explicit(HirId(DefId(0:3 ~ c_variadic[a5de]::foo).6)) + hir_id: HirId(DefId(0:3 ~ c_variadic[a5de]::foo).6) value: Expr { ty: () diff --git a/tests/ui/thir-print/offset_of.stdout b/tests/ui/thir-print/offset_of.stdout index dcf60a86af9b..29399bb98e32 100644 --- a/tests/ui/thir-print/offset_of.stdout +++ b/tests/ui/thir-print/offset_of.stdout @@ -9,7 +9,7 @@ body: kind: Scope { region_scope: Node(52) - lint_level: Explicit(HirId(DefId(offset_of::concrete).52)) + hir_id: HirId(DefId(offset_of::concrete).52) value: Expr { ty: () @@ -51,7 +51,7 @@ body: kind: Scope { region_scope: Node(3) - lint_level: Explicit(HirId(DefId(offset_of::concrete).3)) + hir_id: HirId(DefId(offset_of::concrete).3) value: Expr { ty: usize @@ -67,7 +67,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::concrete).10)) + hir_id: HirId(DefId(offset_of::concrete).10) span: $DIR/offset_of.rs:37:5: 1440:57 (#0) } } @@ -100,7 +100,7 @@ body: kind: Scope { region_scope: Node(13) - lint_level: Explicit(HirId(DefId(offset_of::concrete).13)) + hir_id: HirId(DefId(offset_of::concrete).13) value: Expr { ty: usize @@ -116,7 +116,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::concrete).20)) + hir_id: HirId(DefId(offset_of::concrete).20) span: $DIR/offset_of.rs:38:5: 1440:57 (#0) } } @@ -149,7 +149,7 @@ body: kind: Scope { region_scope: Node(23) - lint_level: Explicit(HirId(DefId(offset_of::concrete).23)) + hir_id: HirId(DefId(offset_of::concrete).23) value: Expr { ty: usize @@ -165,7 +165,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::concrete).30)) + hir_id: HirId(DefId(offset_of::concrete).30) span: $DIR/offset_of.rs:39:5: 1440:57 (#0) } } @@ -198,7 +198,7 @@ body: kind: Scope { region_scope: Node(33) - lint_level: Explicit(HirId(DefId(offset_of::concrete).33)) + hir_id: HirId(DefId(offset_of::concrete).33) value: Expr { ty: usize @@ -214,7 +214,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::concrete).40)) + hir_id: HirId(DefId(offset_of::concrete).40) span: $DIR/offset_of.rs:40:5: 1440:57 (#0) } } @@ -247,7 +247,7 @@ body: kind: Scope { region_scope: Node(43) - lint_level: Explicit(HirId(DefId(offset_of::concrete).43)) + hir_id: HirId(DefId(offset_of::concrete).43) value: Expr { ty: usize @@ -263,7 +263,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::concrete).50)) + hir_id: HirId(DefId(offset_of::concrete).50) span: $DIR/offset_of.rs:41:5: 1440:57 (#0) } } @@ -286,7 +286,7 @@ body: kind: Scope { region_scope: Node(5) - lint_level: Explicit(HirId(DefId(offset_of::concrete).5)) + hir_id: HirId(DefId(offset_of::concrete).5) value: Expr { ty: usize @@ -307,7 +307,7 @@ body: kind: Scope { region_scope: Node(7) - lint_level: Explicit(HirId(DefId(offset_of::concrete).7)) + hir_id: HirId(DefId(offset_of::concrete).7) value: Expr { ty: usize @@ -369,7 +369,7 @@ body: kind: Scope { region_scope: Node(15) - lint_level: Explicit(HirId(DefId(offset_of::concrete).15)) + hir_id: HirId(DefId(offset_of::concrete).15) value: Expr { ty: usize @@ -390,7 +390,7 @@ body: kind: Scope { region_scope: Node(17) - lint_level: Explicit(HirId(DefId(offset_of::concrete).17)) + hir_id: HirId(DefId(offset_of::concrete).17) value: Expr { ty: usize @@ -452,7 +452,7 @@ body: kind: Scope { region_scope: Node(25) - lint_level: Explicit(HirId(DefId(offset_of::concrete).25)) + hir_id: HirId(DefId(offset_of::concrete).25) value: Expr { ty: usize @@ -473,7 +473,7 @@ body: kind: Scope { region_scope: Node(27) - lint_level: Explicit(HirId(DefId(offset_of::concrete).27)) + hir_id: HirId(DefId(offset_of::concrete).27) value: Expr { ty: usize @@ -535,7 +535,7 @@ body: kind: Scope { region_scope: Node(35) - lint_level: Explicit(HirId(DefId(offset_of::concrete).35)) + hir_id: HirId(DefId(offset_of::concrete).35) value: Expr { ty: usize @@ -556,7 +556,7 @@ body: kind: Scope { region_scope: Node(37) - lint_level: Explicit(HirId(DefId(offset_of::concrete).37)) + hir_id: HirId(DefId(offset_of::concrete).37) value: Expr { ty: usize @@ -670,7 +670,7 @@ body: kind: Scope { region_scope: Node(45) - lint_level: Explicit(HirId(DefId(offset_of::concrete).45)) + hir_id: HirId(DefId(offset_of::concrete).45) value: Expr { ty: usize @@ -691,7 +691,7 @@ body: kind: Scope { region_scope: Node(47) - lint_level: Explicit(HirId(DefId(offset_of::concrete).47)) + hir_id: HirId(DefId(offset_of::concrete).47) value: Expr { ty: usize @@ -805,7 +805,7 @@ body: kind: Scope { region_scope: Node(50) - lint_level: Explicit(HirId(DefId(offset_of::generic).50)) + hir_id: HirId(DefId(offset_of::generic).50) value: Expr { ty: () @@ -847,7 +847,7 @@ body: kind: Scope { region_scope: Node(3) - lint_level: Explicit(HirId(DefId(offset_of::generic).3)) + hir_id: HirId(DefId(offset_of::generic).3) value: Expr { ty: usize @@ -863,7 +863,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::generic).12)) + hir_id: HirId(DefId(offset_of::generic).12) span: $DIR/offset_of.rs:45:5: 1440:57 (#0) } } @@ -896,7 +896,7 @@ body: kind: Scope { region_scope: Node(15) - lint_level: Explicit(HirId(DefId(offset_of::generic).15)) + hir_id: HirId(DefId(offset_of::generic).15) value: Expr { ty: usize @@ -912,7 +912,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::generic).24)) + hir_id: HirId(DefId(offset_of::generic).24) span: $DIR/offset_of.rs:46:5: 1440:57 (#0) } } @@ -945,7 +945,7 @@ body: kind: Scope { region_scope: Node(27) - lint_level: Explicit(HirId(DefId(offset_of::generic).27)) + hir_id: HirId(DefId(offset_of::generic).27) value: Expr { ty: usize @@ -961,7 +961,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::generic).36)) + hir_id: HirId(DefId(offset_of::generic).36) span: $DIR/offset_of.rs:47:5: 1440:57 (#0) } } @@ -994,7 +994,7 @@ body: kind: Scope { region_scope: Node(39) - lint_level: Explicit(HirId(DefId(offset_of::generic).39)) + hir_id: HirId(DefId(offset_of::generic).39) value: Expr { ty: usize @@ -1010,7 +1010,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(offset_of::generic).48)) + hir_id: HirId(DefId(offset_of::generic).48) span: $DIR/offset_of.rs:48:5: 1440:57 (#0) } } @@ -1033,7 +1033,7 @@ body: kind: Scope { region_scope: Node(5) - lint_level: Explicit(HirId(DefId(offset_of::generic).5)) + hir_id: HirId(DefId(offset_of::generic).5) value: Expr { ty: usize @@ -1054,7 +1054,7 @@ body: kind: Scope { region_scope: Node(7) - lint_level: Explicit(HirId(DefId(offset_of::generic).7)) + hir_id: HirId(DefId(offset_of::generic).7) value: Expr { ty: usize @@ -1116,7 +1116,7 @@ body: kind: Scope { region_scope: Node(17) - lint_level: Explicit(HirId(DefId(offset_of::generic).17)) + hir_id: HirId(DefId(offset_of::generic).17) value: Expr { ty: usize @@ -1137,7 +1137,7 @@ body: kind: Scope { region_scope: Node(19) - lint_level: Explicit(HirId(DefId(offset_of::generic).19)) + hir_id: HirId(DefId(offset_of::generic).19) value: Expr { ty: usize @@ -1199,7 +1199,7 @@ body: kind: Scope { region_scope: Node(29) - lint_level: Explicit(HirId(DefId(offset_of::generic).29)) + hir_id: HirId(DefId(offset_of::generic).29) value: Expr { ty: usize @@ -1220,7 +1220,7 @@ body: kind: Scope { region_scope: Node(31) - lint_level: Explicit(HirId(DefId(offset_of::generic).31)) + hir_id: HirId(DefId(offset_of::generic).31) value: Expr { ty: usize @@ -1282,7 +1282,7 @@ body: kind: Scope { region_scope: Node(41) - lint_level: Explicit(HirId(DefId(offset_of::generic).41)) + hir_id: HirId(DefId(offset_of::generic).41) value: Expr { ty: usize @@ -1303,7 +1303,7 @@ body: kind: Scope { region_scope: Node(43) - lint_level: Explicit(HirId(DefId(offset_of::generic).43)) + hir_id: HirId(DefId(offset_of::generic).43) value: Expr { ty: usize diff --git a/tests/ui/thir-print/thir-flat-const-variant.stdout b/tests/ui/thir-print/thir-flat-const-variant.stdout index 750a47a7141c..908684094ec3 100644 --- a/tests/ui/thir-print/thir-flat-const-variant.stdout +++ b/tests/ui/thir-print/thir-flat-const-variant.stdout @@ -17,9 +17,7 @@ Thir { Expr { kind: Scope { region_scope: Node(7), - lint_level: Explicit( - HirId(DefId(0:8 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR1).7), - ), + hir_id: HirId(DefId(0:8 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR1).7), value: e0, }, ty: (), @@ -49,9 +47,7 @@ Thir { Expr { kind: Scope { region_scope: Node(3), - lint_level: Explicit( - HirId(DefId(0:8 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR1).3), - ), + hir_id: HirId(DefId(0:8 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR1).3), value: e2, }, ty: Foo, @@ -82,9 +78,7 @@ Thir { Expr { kind: Scope { region_scope: Node(8), - lint_level: Explicit( - HirId(DefId(0:9 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR2).8), - ), + hir_id: HirId(DefId(0:9 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR2).8), value: e0, }, ty: (), @@ -114,9 +108,7 @@ Thir { Expr { kind: Scope { region_scope: Node(3), - lint_level: Explicit( - HirId(DefId(0:9 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR2).3), - ), + hir_id: HirId(DefId(0:9 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR2).3), value: e2, }, ty: Foo, @@ -147,9 +139,7 @@ Thir { Expr { kind: Scope { region_scope: Node(7), - lint_level: Explicit( - HirId(DefId(0:10 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR3).7), - ), + hir_id: HirId(DefId(0:10 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR3).7), value: e0, }, ty: (), @@ -179,9 +169,7 @@ Thir { Expr { kind: Scope { region_scope: Node(3), - lint_level: Explicit( - HirId(DefId(0:10 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR3).3), - ), + hir_id: HirId(DefId(0:10 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR3).3), value: e2, }, ty: Foo, @@ -212,9 +200,7 @@ Thir { Expr { kind: Scope { region_scope: Node(8), - lint_level: Explicit( - HirId(DefId(0:11 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR4).8), - ), + hir_id: HirId(DefId(0:11 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR4).8), value: e0, }, ty: (), @@ -244,9 +230,7 @@ Thir { Expr { kind: Scope { region_scope: Node(3), - lint_level: Explicit( - HirId(DefId(0:11 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR4).3), - ), + hir_id: HirId(DefId(0:11 ~ thir_flat_const_variant[1f54]::{impl#0}::BAR4).3), value: e2, }, ty: Foo, @@ -286,9 +270,7 @@ Thir { Expr { kind: Scope { region_scope: Node(2), - lint_level: Explicit( - HirId(DefId(0:12 ~ thir_flat_const_variant[1f54]::main).2), - ), + hir_id: HirId(DefId(0:12 ~ thir_flat_const_variant[1f54]::main).2), value: e0, }, ty: (), diff --git a/tests/ui/thir-print/thir-flat.stdout b/tests/ui/thir-print/thir-flat.stdout index f01d64e60b3d..37106427745e 100644 --- a/tests/ui/thir-print/thir-flat.stdout +++ b/tests/ui/thir-print/thir-flat.stdout @@ -26,9 +26,7 @@ Thir { Expr { kind: Scope { region_scope: Node(2), - lint_level: Explicit( - HirId(DefId(0:3 ~ thir_flat[7b97]::main).2), - ), + hir_id: HirId(DefId(0:3 ~ thir_flat[7b97]::main).2), value: e0, }, ty: (), diff --git a/tests/ui/thir-print/thir-tree-loop-match.stdout b/tests/ui/thir-print/thir-tree-loop-match.stdout index 5f6b130c3905..4a1b2aaf67f5 100644 --- a/tests/ui/thir-print/thir-tree-loop-match.stdout +++ b/tests/ui/thir-print/thir-tree-loop-match.stdout @@ -32,7 +32,7 @@ body: kind: Scope { region_scope: Node(28) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).28)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).28) value: Expr { ty: bool @@ -53,7 +53,7 @@ body: kind: Scope { region_scope: Node(4) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).4)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).4) value: Expr { ty: bool @@ -76,7 +76,7 @@ body: kind: Scope { region_scope: Node(7) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).7)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).7) value: Expr { ty: bool @@ -101,7 +101,7 @@ body: kind: Scope { region_scope: Node(12) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).12)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).12) value: Expr { ty: bool @@ -135,7 +135,7 @@ body: kind: Scope { region_scope: Node(17) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).17)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).17) value: Expr { ty: bool @@ -166,7 +166,7 @@ body: kind: Scope { region_scope: Node(19) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).19)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).19) value: Expr { ty: ! @@ -183,7 +183,7 @@ body: kind: Scope { region_scope: Node(20) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).20)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).20) value: Expr { ty: bool @@ -209,7 +209,7 @@ body: } } } - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).16)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).16) scope: Node(16) span: $DIR/thir-tree-loop-match.rs:12:17: 15:18 (#0) } @@ -233,7 +233,7 @@ body: kind: Scope { region_scope: Node(25) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).25)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).25) value: Expr { ty: bool @@ -256,7 +256,7 @@ body: kind: Scope { region_scope: Node(26) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).26)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).26) value: Expr { ty: bool @@ -275,7 +275,7 @@ body: } } } - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).24)) + hir_id: HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).24) scope: Node(24) span: $DIR/thir-tree-loop-match.rs:16:17: 16:38 (#0) } @@ -304,7 +304,7 @@ body: kind: Scope { region_scope: Node(2) - lint_level: Explicit(HirId(DefId(0:4 ~ thir_tree_loop_match[3c53]::main).2)) + hir_id: HirId(DefId(0:4 ~ thir_tree_loop_match[3c53]::main).2) value: Expr { ty: () diff --git a/tests/ui/thir-print/thir-tree-match.stdout b/tests/ui/thir-print/thir-tree-match.stdout index ecc5fb21435f..a6d23ee204cb 100644 --- a/tests/ui/thir-print/thir-tree-match.stdout +++ b/tests/ui/thir-print/thir-tree-match.stdout @@ -32,7 +32,7 @@ body: kind: Scope { region_scope: Node(28) - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).28)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).28) value: Expr { ty: bool @@ -53,7 +53,7 @@ body: kind: Scope { region_scope: Node(4) - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).4)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).4) value: Expr { ty: bool @@ -69,7 +69,7 @@ body: kind: Scope { region_scope: Node(5) - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).5)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).5) value: Expr { ty: Foo @@ -129,7 +129,7 @@ body: kind: Scope { region_scope: Node(15) - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).15)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).15) value: Expr { ty: bool @@ -141,7 +141,7 @@ body: } } } - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).14)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).14) scope: Node(14) span: $DIR/thir-tree-match.rs:17:9: 17:40 (#0) } @@ -181,7 +181,7 @@ body: kind: Scope { region_scope: Node(21) - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).21)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).21) value: Expr { ty: bool @@ -193,7 +193,7 @@ body: } } } - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).20)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).20) scope: Node(20) span: $DIR/thir-tree-match.rs:18:9: 18:32 (#0) } @@ -225,7 +225,7 @@ body: kind: Scope { region_scope: Node(27) - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).27)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).27) value: Expr { ty: bool @@ -237,7 +237,7 @@ body: } } } - lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).26)) + hir_id: HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).26) scope: Node(26) span: $DIR/thir-tree-match.rs:19:9: 19:28 (#0) } @@ -263,7 +263,7 @@ body: kind: Scope { region_scope: Node(2) - lint_level: Explicit(HirId(DefId(0:17 ~ thir_tree_match[fcf8]::main).2)) + hir_id: HirId(DefId(0:17 ~ thir_tree_match[fcf8]::main).2) value: Expr { ty: () diff --git a/tests/ui/thir-print/thir-tree.stdout b/tests/ui/thir-print/thir-tree.stdout index d61176d6480f..25d0ccfa7a05 100644 --- a/tests/ui/thir-print/thir-tree.stdout +++ b/tests/ui/thir-print/thir-tree.stdout @@ -9,7 +9,7 @@ body: kind: Scope { region_scope: Node(2) - lint_level: Explicit(HirId(DefId(0:3 ~ thir_tree[7aaa]::main).2)) + hir_id: HirId(DefId(0:3 ~ thir_tree[7aaa]::main).2) value: Expr { ty: () diff --git a/tests/ui/unpretty/box.stdout b/tests/ui/unpretty/box.stdout index 54bd98c7a683..123273be4efe 100644 --- a/tests/ui/unpretty/box.stdout +++ b/tests/ui/unpretty/box.stdout @@ -9,7 +9,7 @@ body: kind: Scope { region_scope: Node(11) - lint_level: Explicit(HirId(DefId(0:3 ~ box[efb9]::main).11)) + hir_id: HirId(DefId(0:3 ~ box[efb9]::main).11) value: Expr { ty: () @@ -43,7 +43,7 @@ body: kind: Scope { region_scope: Node(3) - lint_level: Explicit(HirId(DefId(0:3 ~ box[efb9]::main).3)) + hir_id: HirId(DefId(0:3 ~ box[efb9]::main).3) value: Expr { ty: std::boxed::Box @@ -58,7 +58,7 @@ body: kind: Scope { region_scope: Node(8) - lint_level: Explicit(HirId(DefId(0:3 ~ box[efb9]::main).8)) + hir_id: HirId(DefId(0:3 ~ box[efb9]::main).8) value: Expr { ty: i32 @@ -76,7 +76,7 @@ body: } ) else_block: None - lint_level: Explicit(HirId(DefId(0:3 ~ box[efb9]::main).9)) + hir_id: HirId(DefId(0:3 ~ box[efb9]::main).9) span: $DIR/box.rs:7:5: 7:35 (#0) } } From 8868b479a81cdf27e7493c2ac41d2b7efa2dbe89 Mon Sep 17 00:00:00 2001 From: dianne Date: Thu, 8 Jan 2026 16:04:02 -0800 Subject: [PATCH 038/146] move `LintLevel` to `rustc_mir_build` --- compiler/rustc_middle/src/thir.rs | 6 ------ compiler/rustc_mir_build/src/builder/block.rs | 1 + .../rustc_mir_build/src/builder/expr/as_operand.rs | 1 + compiler/rustc_mir_build/src/builder/expr/as_place.rs | 1 + compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs | 1 + compiler/rustc_mir_build/src/builder/expr/as_temp.rs | 2 +- compiler/rustc_mir_build/src/builder/expr/into.rs | 1 + compiler/rustc_mir_build/src/builder/expr/stmt.rs | 2 +- compiler/rustc_mir_build/src/builder/matches/mod.rs | 2 +- compiler/rustc_mir_build/src/builder/mod.rs | 4 ++-- compiler/rustc_mir_build/src/builder/scope.rs | 10 +++++++++- 11 files changed, 19 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 86bd6fb803b7..86c19520e072 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -116,12 +116,6 @@ pub struct Param<'tcx> { pub hir_id: Option, } -#[derive(Copy, Clone, Debug, HashStable)] -pub enum LintLevel { - Inherited, - Explicit(HirId), -} - #[derive(Clone, Debug, HashStable)] pub struct Block { /// Whether the block itself has a label. Used by `label: {}` diff --git a/compiler/rustc_mir_build/src/builder/block.rs b/compiler/rustc_mir_build/src/builder/block.rs index d8837d2b195a..bfbb6fa7d169 100644 --- a/compiler/rustc_mir_build/src/builder/block.rs +++ b/compiler/rustc_mir_build/src/builder/block.rs @@ -7,6 +7,7 @@ use tracing::debug; use crate::builder::ForGuard::OutsideGuard; use crate::builder::matches::{DeclareLetBindings, ScheduleDrops}; +use crate::builder::scope::LintLevel; use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; impl<'a, 'tcx> Builder<'a, 'tcx> { diff --git a/compiler/rustc_mir_build/src/builder/expr/as_operand.rs b/compiler/rustc_mir_build/src/builder/expr/as_operand.rs index c9c166b7f018..d2f06cc9d57b 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_operand.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_operand.rs @@ -6,6 +6,7 @@ use rustc_middle::thir::*; use tracing::{debug, instrument}; use crate::builder::expr::category::Category; +use crate::builder::scope::LintLevel; use crate::builder::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; impl<'a, 'tcx> Builder<'a, 'tcx> { diff --git a/compiler/rustc_mir_build/src/builder/expr/as_place.rs b/compiler/rustc_mir_build/src/builder/expr/as_place.rs index db9aa3cd8704..139c6da29d44 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_place.rs @@ -16,6 +16,7 @@ use tracing::{debug, instrument, trace}; use crate::builder::ForGuard::{OutsideGuard, RefWithinGuard}; use crate::builder::expr::category::Category; +use crate::builder::scope::LintLevel; use crate::builder::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap}; /// The "outermost" place that holds this value. diff --git a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs index 3d1774bd1d68..8de79ab2531f 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs @@ -18,6 +18,7 @@ use tracing::debug; use crate::builder::expr::as_place::PlaceBase; use crate::builder::expr::category::{Category, RvalueFunc}; +use crate::builder::scope::LintLevel; use crate::builder::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; impl<'a, 'tcx> Builder<'a, 'tcx> { diff --git a/compiler/rustc_mir_build/src/builder/expr/as_temp.rs b/compiler/rustc_mir_build/src/builder/expr/as_temp.rs index 2aace64062cd..55296c647c81 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_temp.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_temp.rs @@ -7,7 +7,7 @@ use rustc_middle::mir::*; use rustc_middle::thir::*; use tracing::{debug, instrument}; -use crate::builder::scope::DropKind; +use crate::builder::scope::{DropKind, LintLevel}; use crate::builder::{BlockAnd, BlockAndExtension, Builder}; impl<'a, 'tcx> Builder<'a, 'tcx> { diff --git a/compiler/rustc_mir_build/src/builder/expr/into.rs b/compiler/rustc_mir_build/src/builder/expr/into.rs index 9731f0de135f..60e05b691a83 100644 --- a/compiler/rustc_mir_build/src/builder/expr/into.rs +++ b/compiler/rustc_mir_build/src/builder/expr/into.rs @@ -16,6 +16,7 @@ use tracing::{debug, instrument}; use crate::builder::expr::category::{Category, RvalueFunc}; use crate::builder::matches::{DeclareLetBindings, HasMatchGuard}; +use crate::builder::scope::LintLevel; use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTemporary}; use crate::errors::{LoopMatchArmWithGuard, LoopMatchUnsupportedType}; diff --git a/compiler/rustc_mir_build/src/builder/expr/stmt.rs b/compiler/rustc_mir_build/src/builder/expr/stmt.rs index f28e483b6a5d..3d603afbaa4a 100644 --- a/compiler/rustc_mir_build/src/builder/expr/stmt.rs +++ b/compiler/rustc_mir_build/src/builder/expr/stmt.rs @@ -5,7 +5,7 @@ use rustc_middle::thir::*; use rustc_span::source_map::Spanned; use tracing::debug; -use crate::builder::scope::BreakableTarget; +use crate::builder::scope::{BreakableTarget, LintLevel}; use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; impl<'a, 'tcx> Builder<'a, 'tcx> { diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 49caee4a1896..565d97fa68b8 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -29,7 +29,7 @@ use crate::builder::ForGuard::{self, OutsideGuard, RefWithinGuard}; use crate::builder::expr::as_place::PlaceBuilder; use crate::builder::matches::buckets::PartitionedCandidates; use crate::builder::matches::user_ty::ProjectedUserTypesNode; -use crate::builder::scope::DropKind; +use crate::builder::scope::{DropKind, LintLevel}; use crate::builder::{ BlockAnd, BlockAndExtension, Builder, GuardFrame, GuardFrameLocal, LocalsForNode, }; diff --git a/compiler/rustc_mir_build/src/builder/mod.rs b/compiler/rustc_mir_build/src/builder/mod.rs index 40f1fe0d5d11..132062961da6 100644 --- a/compiler/rustc_mir_build/src/builder/mod.rs +++ b/compiler/rustc_mir_build/src/builder/mod.rs @@ -38,14 +38,14 @@ use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_middle::hir::place::PlaceBase as HirPlaceBase; use rustc_middle::middle::region; use rustc_middle::mir::*; -use rustc_middle::thir::{self, ExprId, LintLevel, LocalVarId, Param, ParamId, PatKind, Thir}; +use rustc_middle::thir::{self, ExprId, LocalVarId, Param, ParamId, PatKind, Thir}; use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt, TypeVisitableExt, TypingMode}; use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_span::{Span, Symbol, sym}; use crate::builder::expr::as_place::PlaceBuilder; -use crate::builder::scope::DropKind; +use crate::builder::scope::{DropKind, LintLevel}; use crate::errors; pub(crate) fn closure_saved_names_of_captured_variables<'tcx>( diff --git a/compiler/rustc_mir_build/src/builder/scope.rs b/compiler/rustc_mir_build/src/builder/scope.rs index 981704052536..b10df60e0f75 100644 --- a/compiler/rustc_mir_build/src/builder/scope.rs +++ b/compiler/rustc_mir_build/src/builder/scope.rs @@ -89,7 +89,7 @@ use rustc_hir::HirId; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::middle::region; use rustc_middle::mir::{self, *}; -use rustc_middle::thir::{AdtExpr, AdtExprBase, ArmId, ExprId, ExprKind, LintLevel}; +use rustc_middle::thir::{AdtExpr, AdtExprBase, ArmId, ExprId, ExprKind}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, ValTree}; use rustc_middle::{bug, span_bug}; use rustc_pattern_analysis::rustc::RustcPatCtxt; @@ -522,6 +522,14 @@ impl<'tcx> Scopes<'tcx> { } } +/// Used by [`Builder::in_scope`] to create source scopes mapping from MIR back to HIR at points +/// where lint levels change. +#[derive(Copy, Clone, Debug)] +pub(crate) enum LintLevel { + Inherited, + Explicit(HirId), +} + impl<'a, 'tcx> Builder<'a, 'tcx> { // Adding and removing scopes // ========================== From cd79ff2e2c804c626c5ab0dce701077afc35db83 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 15 Jan 2026 09:37:16 +0800 Subject: [PATCH 039/146] Revert "avoid phi node for pointers flowing into Vec appends #130998" This reverts PR because the added test seems to be flaky / non-deterministic, and has been failing in unrelated PRs during merge CI. --- compiler/rustc_codegen_llvm/src/attributes.rs | 11 +------ library/alloc/src/slice.rs | 8 ++--- library/alloc/src/vec/mod.rs | 6 +--- .../lib-optimizations/append-elements.rs | 30 ------------------- 4 files changed, 5 insertions(+), 50 deletions(-) delete mode 100644 tests/codegen-llvm/lib-optimizations/append-elements.rs diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index bf6bb81b53b0..a25ce9e5a90a 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -517,16 +517,7 @@ pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>( to_add.push(llvm::CreateAllocKindAttr(cx.llcx, AllocKindFlags::Free)); // applies to argument place instead of function place let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx); - let attrs: &[_] = if llvm_util::get_version() >= (21, 0, 0) { - // "Does not capture provenance" means "if the function call stashes the pointer somewhere, - // accessing that pointer after the function returns is UB". That is definitely the case here since - // freeing will destroy the provenance. - let captures_addr = AttributeKind::CapturesAddress.create_attr(cx.llcx); - &[allocated_pointer, captures_addr] - } else { - &[allocated_pointer] - }; - attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), attrs); + attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), &[allocated_pointer]); } if let Some(align) = codegen_fn_attrs.alignment { llvm::set_alignment(llfn, align); diff --git a/library/alloc/src/slice.rs b/library/alloc/src/slice.rs index 58abf4bd6571..e7d0fc3454ee 100644 --- a/library/alloc/src/slice.rs +++ b/library/alloc/src/slice.rs @@ -448,11 +448,9 @@ impl [T] { // SAFETY: // allocated above with the capacity of `s`, and initialize to `s.len()` in // ptr::copy_to_non_overlapping below. - if s.len() > 0 { - unsafe { - s.as_ptr().copy_to_nonoverlapping(v.as_mut_ptr(), s.len()); - v.set_len(s.len()); - } + unsafe { + s.as_ptr().copy_to_nonoverlapping(v.as_mut_ptr(), s.len()); + v.set_len(s.len()); } v } diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index ac86399df7ab..379e964f0a0c 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -2818,11 +2818,7 @@ impl Vec { let count = other.len(); self.reserve(count); let len = self.len(); - if count > 0 { - unsafe { - ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) - }; - } + unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; self.len += count; } diff --git a/tests/codegen-llvm/lib-optimizations/append-elements.rs b/tests/codegen-llvm/lib-optimizations/append-elements.rs deleted file mode 100644 index 8ee520a131f0..000000000000 --- a/tests/codegen-llvm/lib-optimizations/append-elements.rs +++ /dev/null @@ -1,30 +0,0 @@ -//@ compile-flags: -O -Zmerge-functions=disabled -//@ min-llvm-version: 21 -#![crate_type = "lib"] - -//! Check that a temporary intermediate allocations can eliminated and replaced -//! with memcpy forwarding. -//! This requires Vec code to be structured in a way that avoids phi nodes from the -//! zero-capacity length flowing into the memcpy arguments. - -// CHECK-LABEL: @vec_append_with_temp_alloc -#[no_mangle] -pub fn vec_append_with_temp_alloc(dst: &mut Vec, src: &[u8]) { - // CHECK-NOT: call void @llvm.memcpy - // CHECK: call void @llvm.memcpy.{{.*}}%dst.i{{.*}}%src.0 - // CHECK-NOT: call void @llvm.memcpy - let temp = src.to_vec(); - dst.extend(&temp); - // CHECK: ret -} - -// CHECK-LABEL: @string_append_with_temp_alloc -#[no_mangle] -pub fn string_append_with_temp_alloc(dst: &mut String, src: &str) { - // CHECK-NOT: call void @llvm.memcpy - // CHECK: call void @llvm.memcpy.{{.*}}%dst.i{{.*}}%src.0 - // CHECK-NOT: call void @llvm.memcpy - let temp = src.to_string(); - dst.push_str(&temp); - // CHECK: ret -} From cd05071ec4a4b62d469603fb7b89d0a35857cbe1 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 14 Jan 2026 20:18:09 +0300 Subject: [PATCH 040/146] resolve: Downgrade `ambiguous_glob_imports` to warn-by-default But still keep it report-in-deps. To revert after ~February 27 2026, when Rust 1.95 branches out from the main branch. --- compiler/rustc_lint_defs/src/builtin.rs | 2 +- tests/ui/imports/ambiguous-10.rs | 4 ++-- tests/ui/imports/ambiguous-10.stderr | 10 ++++----- tests/ui/imports/ambiguous-12.rs | 4 ++-- tests/ui/imports/ambiguous-12.stderr | 10 ++++----- tests/ui/imports/ambiguous-13.rs | 4 ++-- tests/ui/imports/ambiguous-13.stderr | 10 ++++----- tests/ui/imports/ambiguous-14.rs | 4 ++-- tests/ui/imports/ambiguous-14.stderr | 10 ++++----- tests/ui/imports/ambiguous-15.rs | 4 ++-- tests/ui/imports/ambiguous-15.stderr | 10 ++++----- tests/ui/imports/ambiguous-16.rs | 4 ++-- tests/ui/imports/ambiguous-16.stderr | 10 ++++----- tests/ui/imports/ambiguous-17.rs | 4 ++-- tests/ui/imports/ambiguous-17.stderr | 10 ++++----- tests/ui/imports/ambiguous-2.rs | 4 ++-- tests/ui/imports/ambiguous-2.stderr | 10 ++++----- tests/ui/imports/ambiguous-3.rs | 4 ++-- tests/ui/imports/ambiguous-3.stderr | 10 ++++----- tests/ui/imports/ambiguous-4.rs | 4 ++-- tests/ui/imports/ambiguous-4.stderr | 10 ++++----- tests/ui/imports/ambiguous-5.rs | 4 ++-- tests/ui/imports/ambiguous-5.stderr | 10 ++++----- tests/ui/imports/ambiguous-6.rs | 4 ++-- tests/ui/imports/ambiguous-6.stderr | 10 ++++----- tests/ui/imports/ambiguous-9.rs | 6 ++--- tests/ui/imports/ambiguous-9.stderr | 16 +++++++------- .../ui/imports/ambiguous-panic-globvsglob.rs | 4 ++-- .../imports/ambiguous-panic-globvsglob.stderr | 10 ++++----- tests/ui/imports/duplicate.rs | 2 +- tests/ui/imports/duplicate.stderr | 10 ++++----- .../ui/imports/glob-conflict-cross-crate-1.rs | 6 ++--- .../glob-conflict-cross-crate-1.stderr | 16 +++++++------- .../ui/imports/glob-conflict-cross-crate-2.rs | 4 ++-- .../glob-conflict-cross-crate-2.stderr | 10 ++++----- .../ui/imports/glob-conflict-cross-crate-3.rs | 6 ++--- .../glob-conflict-cross-crate-3.stderr | 16 +++++++------- tests/ui/imports/issue-114682-2.rs | 6 ++--- tests/ui/imports/issue-114682-2.stderr | 16 +++++++------- tests/ui/imports/issue-114682-4.rs | 2 +- tests/ui/imports/issue-114682-4.stderr | 10 ++++----- tests/ui/imports/issue-114682-5.rs | 2 +- tests/ui/imports/issue-114682-5.stderr | 10 ++++----- tests/ui/imports/issue-114682-6.rs | 4 ++-- tests/ui/imports/issue-114682-6.stderr | 10 ++++----- .../ui/imports/overwrite-different-ambig-2.rs | 4 +++- .../overwrite-different-ambig-2.stderr | 22 +++++++++---------- .../imports/unresolved-seg-after-ambiguous.rs | 2 +- .../unresolved-seg-after-ambiguous.stderr | 10 ++++----- 49 files changed, 188 insertions(+), 186 deletions(-) diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 4230aa7568e2..c165b91cc916 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -4465,7 +4465,7 @@ declare_lint! { /// /// [future-incompatible]: ../index.md#future-incompatible-lints pub AMBIGUOUS_GLOB_IMPORTS, - Deny, + Warn, "detects certain glob imports that require reporting an ambiguity error", @future_incompatible = FutureIncompatibleInfo { reason: fcw!(FutureReleaseError #114095), diff --git a/tests/ui/imports/ambiguous-10.rs b/tests/ui/imports/ambiguous-10.rs index 166b01ede12d..61069cb75124 100644 --- a/tests/ui/imports/ambiguous-10.rs +++ b/tests/ui/imports/ambiguous-10.rs @@ -1,5 +1,5 @@ // https://github.com/rust-lang/rust/pull/113099#issuecomment-1637022296 - +//@ check-pass mod a { pub enum Token {} } @@ -13,6 +13,6 @@ mod b { use crate::a::*; use crate::b::*; fn c(_: Token) {} -//~^ ERROR `Token` is ambiguous +//~^ WARN `Token` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! fn main() { } diff --git a/tests/ui/imports/ambiguous-10.stderr b/tests/ui/imports/ambiguous-10.stderr index f175d27c99e9..4ae3e4203fab 100644 --- a/tests/ui/imports/ambiguous-10.stderr +++ b/tests/ui/imports/ambiguous-10.stderr @@ -1,4 +1,4 @@ -error: `Token` is ambiguous +warning: `Token` is ambiguous --> $DIR/ambiguous-10.rs:15:9 | LL | fn c(_: Token) {} @@ -19,12 +19,12 @@ note: `Token` could also refer to the enum imported here LL | use crate::b::*; | ^^^^^^^^^^^ = help: consider adding an explicit import of `Token` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `Token` is ambiguous +warning: `Token` is ambiguous --> $DIR/ambiguous-10.rs:15:9 | LL | fn c(_: Token) {} @@ -45,5 +45,5 @@ note: `Token` could also refer to the enum imported here LL | use crate::b::*; | ^^^^^^^^^^^ = help: consider adding an explicit import of `Token` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-12.rs b/tests/ui/imports/ambiguous-12.rs index 543396b8dfe5..93cd3ca6f347 100644 --- a/tests/ui/imports/ambiguous-12.rs +++ b/tests/ui/imports/ambiguous-12.rs @@ -1,5 +1,5 @@ // https://github.com/rust-lang/rust/pull/113099#issuecomment-1637022296 - +//@ check-pass macro_rules! m { () => { pub fn b() {} @@ -19,6 +19,6 @@ use crate::public::*; fn main() { b(); - //~^ ERROR `b` is ambiguous + //~^ WARN `b` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } diff --git a/tests/ui/imports/ambiguous-12.stderr b/tests/ui/imports/ambiguous-12.stderr index 5f92eae0dbcb..1a1777dedac4 100644 --- a/tests/ui/imports/ambiguous-12.stderr +++ b/tests/ui/imports/ambiguous-12.stderr @@ -1,4 +1,4 @@ -error: `b` is ambiguous +warning: `b` is ambiguous --> $DIR/ambiguous-12.rs:21:5 | LL | b(); @@ -19,12 +19,12 @@ note: `b` could also refer to the function imported here LL | use crate::public::*; | ^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `b` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `b` is ambiguous +warning: `b` is ambiguous --> $DIR/ambiguous-12.rs:21:5 | LL | b(); @@ -45,5 +45,5 @@ note: `b` could also refer to the function imported here LL | use crate::public::*; | ^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `b` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-13.rs b/tests/ui/imports/ambiguous-13.rs index 3569dd5d9adc..5fbb71d8545a 100644 --- a/tests/ui/imports/ambiguous-13.rs +++ b/tests/ui/imports/ambiguous-13.rs @@ -1,5 +1,5 @@ // https://github.com/rust-lang/rust/pull/113099#issuecomment-1637022296 - +//@ check-pass pub mod object { #[derive(Debug)] pub struct Rect; @@ -16,6 +16,6 @@ use crate::object::*; use crate::content::*; fn a(_: Rect) {} -//~^ ERROR `Rect` is ambiguous +//~^ WARN `Rect` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! fn main() { } diff --git a/tests/ui/imports/ambiguous-13.stderr b/tests/ui/imports/ambiguous-13.stderr index 279b4e8f1420..ca83cf63c12c 100644 --- a/tests/ui/imports/ambiguous-13.stderr +++ b/tests/ui/imports/ambiguous-13.stderr @@ -1,4 +1,4 @@ -error: `Rect` is ambiguous +warning: `Rect` is ambiguous --> $DIR/ambiguous-13.rs:18:9 | LL | fn a(_: Rect) {} @@ -19,12 +19,12 @@ note: `Rect` could also refer to the struct imported here LL | use crate::content::*; | ^^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `Rect` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `Rect` is ambiguous +warning: `Rect` is ambiguous --> $DIR/ambiguous-13.rs:18:9 | LL | fn a(_: Rect) {} @@ -45,5 +45,5 @@ note: `Rect` could also refer to the struct imported here LL | use crate::content::*; | ^^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `Rect` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-14.rs b/tests/ui/imports/ambiguous-14.rs index ba2d7dc4e016..325b29f3b481 100644 --- a/tests/ui/imports/ambiguous-14.rs +++ b/tests/ui/imports/ambiguous-14.rs @@ -1,6 +1,6 @@ //@ edition:2015 // https://github.com/rust-lang/rust/issues/98467 - +//@ check-pass mod a { pub fn foo() {} } @@ -21,6 +21,6 @@ mod g { fn main() { g::foo(); - //~^ ERROR `foo` is ambiguous + //~^ WARN `foo` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } diff --git a/tests/ui/imports/ambiguous-14.stderr b/tests/ui/imports/ambiguous-14.stderr index 2a3557c31f12..6823d728c368 100644 --- a/tests/ui/imports/ambiguous-14.stderr +++ b/tests/ui/imports/ambiguous-14.stderr @@ -1,4 +1,4 @@ -error: `foo` is ambiguous +warning: `foo` is ambiguous --> $DIR/ambiguous-14.rs:23:8 | LL | g::foo(); @@ -19,12 +19,12 @@ note: `foo` could also refer to the function imported here LL | pub use f::*; | ^^^^ = help: consider adding an explicit import of `foo` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `foo` is ambiguous +warning: `foo` is ambiguous --> $DIR/ambiguous-14.rs:23:8 | LL | g::foo(); @@ -45,5 +45,5 @@ note: `foo` could also refer to the function imported here LL | pub use f::*; | ^^^^ = help: consider adding an explicit import of `foo` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-15.rs b/tests/ui/imports/ambiguous-15.rs index 07d8893b2dea..f90d9696e8ef 100644 --- a/tests/ui/imports/ambiguous-15.rs +++ b/tests/ui/imports/ambiguous-15.rs @@ -1,5 +1,5 @@ // https://github.com/rust-lang/rust/pull/113099#issuecomment-1638206152 - +//@ check-pass mod t2 { #[derive(Debug)] pub enum Error {} @@ -20,7 +20,7 @@ mod t3 { use self::t3::*; fn a(_: E) {} -//~^ ERROR `Error` is ambiguous +//~^ WARN `Error` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! fn main() {} diff --git a/tests/ui/imports/ambiguous-15.stderr b/tests/ui/imports/ambiguous-15.stderr index 15f83546532e..59f9cb0526fc 100644 --- a/tests/ui/imports/ambiguous-15.stderr +++ b/tests/ui/imports/ambiguous-15.stderr @@ -1,4 +1,4 @@ -error: `Error` is ambiguous +warning: `Error` is ambiguous --> $DIR/ambiguous-15.rs:22:9 | LL | fn a(_: E) {} @@ -19,12 +19,12 @@ note: `Error` could also refer to the enum imported here LL | pub use t2::*; | ^^^^^ = help: consider adding an explicit import of `Error` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `Error` is ambiguous +warning: `Error` is ambiguous --> $DIR/ambiguous-15.rs:22:9 | LL | fn a(_: E) {} @@ -45,5 +45,5 @@ note: `Error` could also refer to the enum imported here LL | pub use t2::*; | ^^^^^ = help: consider adding an explicit import of `Error` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-16.rs b/tests/ui/imports/ambiguous-16.rs index f31c78d18a38..2cd1e2aca9d3 100644 --- a/tests/ui/imports/ambiguous-16.rs +++ b/tests/ui/imports/ambiguous-16.rs @@ -1,5 +1,5 @@ // https://github.com/rust-lang/rust/pull/113099 - +//@ check-pass mod framing { mod public_message { use super::*; @@ -20,7 +20,7 @@ mod framing { } use crate::framing::ConfirmedTranscriptHashInput; -//~^ ERROR `ConfirmedTranscriptHashInput` is ambiguous +//~^ WARN `ConfirmedTranscriptHashInput` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! fn main() { } diff --git a/tests/ui/imports/ambiguous-16.stderr b/tests/ui/imports/ambiguous-16.stderr index 7c80dee17f04..bb76111ebe89 100644 --- a/tests/ui/imports/ambiguous-16.stderr +++ b/tests/ui/imports/ambiguous-16.stderr @@ -1,4 +1,4 @@ -error: `ConfirmedTranscriptHashInput` is ambiguous +warning: `ConfirmedTranscriptHashInput` is ambiguous --> $DIR/ambiguous-16.rs:22:21 | LL | use crate::framing::ConfirmedTranscriptHashInput; @@ -19,12 +19,12 @@ note: `ConfirmedTranscriptHashInput` could also refer to the struct imported her LL | pub use self::public_message_in::*; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `ConfirmedTranscriptHashInput` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `ConfirmedTranscriptHashInput` is ambiguous +warning: `ConfirmedTranscriptHashInput` is ambiguous --> $DIR/ambiguous-16.rs:22:21 | LL | use crate::framing::ConfirmedTranscriptHashInput; @@ -45,5 +45,5 @@ note: `ConfirmedTranscriptHashInput` could also refer to the struct imported her LL | pub use self::public_message_in::*; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `ConfirmedTranscriptHashInput` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-17.rs b/tests/ui/imports/ambiguous-17.rs index 3a51c156d34c..8ef0318fa046 100644 --- a/tests/ui/imports/ambiguous-17.rs +++ b/tests/ui/imports/ambiguous-17.rs @@ -1,6 +1,6 @@ //@ edition:2015 // https://github.com/rust-lang/rust/pull/113099#issuecomment-1638206152 - +//@ check-pass pub use evp::*; //~ WARNING ambiguous glob re-exports pub use handwritten::*; @@ -24,6 +24,6 @@ mod handwritten { fn main() { id(); - //~^ ERROR `id` is ambiguous + //~^ WARN `id` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } diff --git a/tests/ui/imports/ambiguous-17.stderr b/tests/ui/imports/ambiguous-17.stderr index 1849b83d76a3..ef4a835a0b3c 100644 --- a/tests/ui/imports/ambiguous-17.stderr +++ b/tests/ui/imports/ambiguous-17.stderr @@ -8,7 +8,7 @@ LL | pub use handwritten::*; | = note: `#[warn(ambiguous_glob_reexports)]` on by default -error: `id` is ambiguous +warning: `id` is ambiguous --> $DIR/ambiguous-17.rs:26:5 | LL | id(); @@ -29,12 +29,12 @@ note: `id` could also refer to the function imported here LL | pub use handwritten::*; | ^^^^^^^^^^^^^^ = help: consider adding an explicit import of `id` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error; 1 warning emitted +warning: 2 warnings emitted Future incompatibility report: Future breakage diagnostic: -error: `id` is ambiguous +warning: `id` is ambiguous --> $DIR/ambiguous-17.rs:26:5 | LL | id(); @@ -55,5 +55,5 @@ note: `id` could also refer to the function imported here LL | pub use handwritten::*; | ^^^^^^^^^^^^^^ = help: consider adding an explicit import of `id` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-2.rs b/tests/ui/imports/ambiguous-2.rs index 65c971c00b9a..978655bc0177 100644 --- a/tests/ui/imports/ambiguous-2.rs +++ b/tests/ui/imports/ambiguous-2.rs @@ -1,9 +1,9 @@ //@ aux-build: ../ambiguous-1.rs // https://github.com/rust-lang/rust/pull/113099#issuecomment-1633574396 - +//@ check-pass extern crate ambiguous_1; fn main() { - ambiguous_1::id(); //~ ERROR `id` is ambiguous + ambiguous_1::id(); //~ WARN `id` is ambiguous //~| WARN this was previously accepted } diff --git a/tests/ui/imports/ambiguous-2.stderr b/tests/ui/imports/ambiguous-2.stderr index d428e58a78fd..a0222099239a 100644 --- a/tests/ui/imports/ambiguous-2.stderr +++ b/tests/ui/imports/ambiguous-2.stderr @@ -1,4 +1,4 @@ -error: `id` is ambiguous +warning: `id` is ambiguous --> $DIR/ambiguous-2.rs:7:18 | LL | ambiguous_1::id(); @@ -17,12 +17,12 @@ note: `id` could also refer to the function defined here | LL | pub use self::handwritten::*; | ^^^^^^^^^^^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `id` is ambiguous +warning: `id` is ambiguous --> $DIR/ambiguous-2.rs:7:18 | LL | ambiguous_1::id(); @@ -41,5 +41,5 @@ note: `id` could also refer to the function defined here | LL | pub use self::handwritten::*; | ^^^^^^^^^^^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-3.rs b/tests/ui/imports/ambiguous-3.rs index ff0dcc221ec0..717c1eb8597a 100644 --- a/tests/ui/imports/ambiguous-3.rs +++ b/tests/ui/imports/ambiguous-3.rs @@ -1,9 +1,9 @@ // https://github.com/rust-lang/rust/issues/47525 - +//@ check-pass fn main() { use a::*; x(); - //~^ ERROR `x` is ambiguous + //~^ WARN `x` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } diff --git a/tests/ui/imports/ambiguous-3.stderr b/tests/ui/imports/ambiguous-3.stderr index 27fa05a195b9..7addf9bc797c 100644 --- a/tests/ui/imports/ambiguous-3.stderr +++ b/tests/ui/imports/ambiguous-3.stderr @@ -1,4 +1,4 @@ -error: `x` is ambiguous +warning: `x` is ambiguous --> $DIR/ambiguous-3.rs:5:5 | LL | x(); @@ -19,12 +19,12 @@ note: `x` could also refer to the function imported here LL | pub use self::c::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `x` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `x` is ambiguous +warning: `x` is ambiguous --> $DIR/ambiguous-3.rs:5:5 | LL | x(); @@ -45,5 +45,5 @@ note: `x` could also refer to the function imported here LL | pub use self::c::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `x` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-4.rs b/tests/ui/imports/ambiguous-4.rs index e66d231f93cc..1a2bfeaf53dc 100644 --- a/tests/ui/imports/ambiguous-4.rs +++ b/tests/ui/imports/ambiguous-4.rs @@ -1,9 +1,9 @@ //@ edition:2015 //@ aux-build: ../ambiguous-4-extern.rs - +//@ check-pass extern crate ambiguous_4_extern; fn main() { - ambiguous_4_extern::id(); //~ ERROR `id` is ambiguous + ambiguous_4_extern::id(); //~ WARN `id` is ambiguous //~| WARN this was previously accepted } diff --git a/tests/ui/imports/ambiguous-4.stderr b/tests/ui/imports/ambiguous-4.stderr index cf4127cbbb1c..6c1a2679fcae 100644 --- a/tests/ui/imports/ambiguous-4.stderr +++ b/tests/ui/imports/ambiguous-4.stderr @@ -1,4 +1,4 @@ -error: `id` is ambiguous +warning: `id` is ambiguous --> $DIR/ambiguous-4.rs:7:25 | LL | ambiguous_4_extern::id(); @@ -17,12 +17,12 @@ note: `id` could also refer to the function defined here | LL | pub use handwritten::*; | ^^^^^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `id` is ambiguous +warning: `id` is ambiguous --> $DIR/ambiguous-4.rs:7:25 | LL | ambiguous_4_extern::id(); @@ -41,5 +41,5 @@ note: `id` could also refer to the function defined here | LL | pub use handwritten::*; | ^^^^^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-5.rs b/tests/ui/imports/ambiguous-5.rs index 8f89c966d4a5..9879216280a2 100644 --- a/tests/ui/imports/ambiguous-5.rs +++ b/tests/ui/imports/ambiguous-5.rs @@ -1,5 +1,5 @@ // https://github.com/rust-lang/rust/pull/113099#issuecomment-1637022296 - +//@ check-pass mod a { pub struct Class(u16); } @@ -10,7 +10,7 @@ mod gpos { use super::gsubgpos::*; use super::*; struct MarkRecord(Class); - //~^ ERROR`Class` is ambiguous + //~^ WARN`Class` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } diff --git a/tests/ui/imports/ambiguous-5.stderr b/tests/ui/imports/ambiguous-5.stderr index 1fc5f4543f35..a4f3151c9e85 100644 --- a/tests/ui/imports/ambiguous-5.stderr +++ b/tests/ui/imports/ambiguous-5.stderr @@ -1,4 +1,4 @@ -error: `Class` is ambiguous +warning: `Class` is ambiguous --> $DIR/ambiguous-5.rs:12:23 | LL | struct MarkRecord(Class); @@ -19,12 +19,12 @@ note: `Class` could also refer to the struct imported here LL | use super::gsubgpos::*; | ^^^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `Class` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `Class` is ambiguous +warning: `Class` is ambiguous --> $DIR/ambiguous-5.rs:12:23 | LL | struct MarkRecord(Class); @@ -45,5 +45,5 @@ note: `Class` could also refer to the struct imported here LL | use super::gsubgpos::*; | ^^^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `Class` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-6.rs b/tests/ui/imports/ambiguous-6.rs index 1c6e34377165..9a3a138bda4c 100644 --- a/tests/ui/imports/ambiguous-6.rs +++ b/tests/ui/imports/ambiguous-6.rs @@ -1,10 +1,10 @@ //@ edition: 2021 // https://github.com/rust-lang/rust/issues/112713 - +//@ check-pass pub fn foo() -> u32 { use sub::*; C - //~^ ERROR `C` is ambiguous + //~^ WARN `C` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } diff --git a/tests/ui/imports/ambiguous-6.stderr b/tests/ui/imports/ambiguous-6.stderr index 681bc40931f5..d811cfa4236a 100644 --- a/tests/ui/imports/ambiguous-6.stderr +++ b/tests/ui/imports/ambiguous-6.stderr @@ -1,4 +1,4 @@ -error: `C` is ambiguous +warning: `C` is ambiguous --> $DIR/ambiguous-6.rs:6:5 | LL | C @@ -19,12 +19,12 @@ note: `C` could also refer to the constant imported here LL | pub use mod2::*; | ^^^^^^^ = help: consider adding an explicit import of `C` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `C` is ambiguous +warning: `C` is ambiguous --> $DIR/ambiguous-6.rs:6:5 | LL | C @@ -45,5 +45,5 @@ note: `C` could also refer to the constant imported here LL | pub use mod2::*; | ^^^^^^^ = help: consider adding an explicit import of `C` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-9.rs b/tests/ui/imports/ambiguous-9.rs index c10b1268060c..e6329b8d46ac 100644 --- a/tests/ui/imports/ambiguous-9.rs +++ b/tests/ui/imports/ambiguous-9.rs @@ -1,5 +1,5 @@ // https://github.com/rust-lang/rust/pull/113099#issuecomment-1638206152 - +//@ check-pass pub mod dsl { mod range { pub fn date_range() {} @@ -21,8 +21,8 @@ use prelude::*; fn main() { date_range(); - //~^ ERROR `date_range` is ambiguous + //~^ WARN `date_range` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - //~| ERROR `date_range` is ambiguous + //~| WARN `date_range` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } diff --git a/tests/ui/imports/ambiguous-9.stderr b/tests/ui/imports/ambiguous-9.stderr index 800a2e10c9d7..da7d2d970fdd 100644 --- a/tests/ui/imports/ambiguous-9.stderr +++ b/tests/ui/imports/ambiguous-9.stderr @@ -8,7 +8,7 @@ LL | use super::prelude::*; | = note: `#[warn(ambiguous_glob_reexports)]` on by default -error: `date_range` is ambiguous +warning: `date_range` is ambiguous --> $DIR/ambiguous-9.rs:23:5 | LL | date_range(); @@ -29,7 +29,7 @@ note: `date_range` could also refer to the function imported here LL | use super::prelude::*; | ^^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `date_range` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default warning: ambiguous glob re-exports --> $DIR/ambiguous-9.rs:15:13 @@ -39,7 +39,7 @@ LL | pub use self::t::*; LL | pub use super::dsl::*; | ------------- but the name `date_range` in the value namespace is also re-exported here -error: `date_range` is ambiguous +warning: `date_range` is ambiguous --> $DIR/ambiguous-9.rs:23:5 | LL | date_range(); @@ -61,10 +61,10 @@ LL | use prelude::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `date_range` to disambiguate -error: aborting due to 2 previous errors; 2 warnings emitted +warning: 4 warnings emitted Future incompatibility report: Future breakage diagnostic: -error: `date_range` is ambiguous +warning: `date_range` is ambiguous --> $DIR/ambiguous-9.rs:23:5 | LL | date_range(); @@ -85,10 +85,10 @@ note: `date_range` could also refer to the function imported here LL | use super::prelude::*; | ^^^^^^^^^^^^^^^^^ = help: consider adding an explicit import of `date_range` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default Future breakage diagnostic: -error: `date_range` is ambiguous +warning: `date_range` is ambiguous --> $DIR/ambiguous-9.rs:23:5 | LL | date_range(); @@ -109,5 +109,5 @@ note: `date_range` could also refer to the function imported here LL | use prelude::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `date_range` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/ambiguous-panic-globvsglob.rs b/tests/ui/imports/ambiguous-panic-globvsglob.rs index 4ff3cc822535..335fba74b208 100644 --- a/tests/ui/imports/ambiguous-panic-globvsglob.rs +++ b/tests/ui/imports/ambiguous-panic-globvsglob.rs @@ -3,7 +3,7 @@ mod m1 { pub use core::prelude::v1::*; } - +//@ check-pass mod m2 { pub use std::prelude::v1::*; } @@ -18,6 +18,6 @@ fn foo() { panic!(); //~^ WARN: `panic` is ambiguous [ambiguous_panic_imports] //~| WARN: this was previously accepted by the compiler - //~| ERROR: `panic` is ambiguous [ambiguous_glob_imports] + //~| WARN: `panic` is ambiguous [ambiguous_glob_imports] //~| WARN: this was previously accepted by the compiler } diff --git a/tests/ui/imports/ambiguous-panic-globvsglob.stderr b/tests/ui/imports/ambiguous-panic-globvsglob.stderr index 455c58bb6c02..8e216b21734f 100644 --- a/tests/ui/imports/ambiguous-panic-globvsglob.stderr +++ b/tests/ui/imports/ambiguous-panic-globvsglob.stderr @@ -1,4 +1,4 @@ -error: `panic` is ambiguous +warning: `panic` is ambiguous --> $DIR/ambiguous-panic-globvsglob.rs:18:5 | LL | panic!(); @@ -19,7 +19,7 @@ note: `panic` could also refer to the macro imported here LL | use m2::*; | ^^^^^ = help: consider adding an explicit import of `panic` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default warning: `panic` is ambiguous --> $DIR/ambiguous-panic-globvsglob.rs:18:5 @@ -40,10 +40,10 @@ note: `panic` could also refer to a macro from prelude --> $SRC_DIR/std/src/prelude/mod.rs:LL:COL = note: `#[warn(ambiguous_panic_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error; 1 warning emitted +warning: 2 warnings emitted Future incompatibility report: Future breakage diagnostic: -error: `panic` is ambiguous +warning: `panic` is ambiguous --> $DIR/ambiguous-panic-globvsglob.rs:18:5 | LL | panic!(); @@ -64,5 +64,5 @@ note: `panic` could also refer to the macro imported here LL | use m2::*; | ^^^^^ = help: consider adding an explicit import of `panic` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/duplicate.rs b/tests/ui/imports/duplicate.rs index 0a652889ca8a..ef54726c9a93 100644 --- a/tests/ui/imports/duplicate.rs +++ b/tests/ui/imports/duplicate.rs @@ -34,7 +34,7 @@ fn main() { e::foo(); f::foo(); //~ ERROR `foo` is ambiguous g::foo(); - //~^ ERROR `foo` is ambiguous + //~^ WARN `foo` is ambiguous //~| WARNING this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } diff --git a/tests/ui/imports/duplicate.stderr b/tests/ui/imports/duplicate.stderr index 74829fc21e22..9252a041749d 100644 --- a/tests/ui/imports/duplicate.stderr +++ b/tests/ui/imports/duplicate.stderr @@ -68,7 +68,7 @@ LL | use self::m2::*; | ^^^^^^^^^^^ = help: consider adding an explicit import of `foo` to disambiguate -error: `foo` is ambiguous +warning: `foo` is ambiguous --> $DIR/duplicate.rs:36:8 | LL | g::foo(); @@ -89,14 +89,14 @@ note: `foo` could also refer to the function imported here LL | pub use crate::f::*; | ^^^^^^^^^^^ = help: consider adding an explicit import of `foo` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 5 previous errors +error: aborting due to 4 previous errors; 1 warning emitted Some errors have detailed explanations: E0252, E0659. For more information about an error, try `rustc --explain E0252`. Future incompatibility report: Future breakage diagnostic: -error: `foo` is ambiguous +warning: `foo` is ambiguous --> $DIR/duplicate.rs:36:8 | LL | g::foo(); @@ -117,5 +117,5 @@ note: `foo` could also refer to the function imported here LL | pub use crate::f::*; | ^^^^^^^^^^^ = help: consider adding an explicit import of `foo` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/glob-conflict-cross-crate-1.rs b/tests/ui/imports/glob-conflict-cross-crate-1.rs index 08ce6166b5c1..787fa36db2d9 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-1.rs +++ b/tests/ui/imports/glob-conflict-cross-crate-1.rs @@ -1,11 +1,11 @@ //@ edition:2015 //@ aux-build:glob-conflict.rs - +//@ check-pass extern crate glob_conflict; fn main() { - glob_conflict::f(); //~ ERROR `f` is ambiguous + glob_conflict::f(); //~ WARN `f` is ambiguous //~| WARN this was previously accepted - glob_conflict::glob::f(); //~ ERROR `f` is ambiguous + glob_conflict::glob::f(); //~ WARN `f` is ambiguous //~| WARN this was previously accepted } diff --git a/tests/ui/imports/glob-conflict-cross-crate-1.stderr b/tests/ui/imports/glob-conflict-cross-crate-1.stderr index 54b7976b057e..440113653675 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-1.stderr +++ b/tests/ui/imports/glob-conflict-cross-crate-1.stderr @@ -1,4 +1,4 @@ -error: `f` is ambiguous +warning: `f` is ambiguous --> $DIR/glob-conflict-cross-crate-1.rs:7:20 | LL | glob_conflict::f(); @@ -17,9 +17,9 @@ note: `f` could also refer to the function defined here | LL | pub use m2::*; | ^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: `f` is ambiguous +warning: `f` is ambiguous --> $DIR/glob-conflict-cross-crate-1.rs:9:26 | LL | glob_conflict::glob::f(); @@ -39,10 +39,10 @@ note: `f` could also refer to the function defined here LL | pub use m2::*; | ^^ -error: aborting due to 2 previous errors +warning: 2 warnings emitted Future incompatibility report: Future breakage diagnostic: -error: `f` is ambiguous +warning: `f` is ambiguous --> $DIR/glob-conflict-cross-crate-1.rs:7:20 | LL | glob_conflict::f(); @@ -61,10 +61,10 @@ note: `f` could also refer to the function defined here | LL | pub use m2::*; | ^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default Future breakage diagnostic: -error: `f` is ambiguous +warning: `f` is ambiguous --> $DIR/glob-conflict-cross-crate-1.rs:9:26 | LL | glob_conflict::glob::f(); @@ -83,5 +83,5 @@ note: `f` could also refer to the function defined here | LL | pub use m2::*; | ^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/glob-conflict-cross-crate-2.rs b/tests/ui/imports/glob-conflict-cross-crate-2.rs index b4dd3d8eeb44..018a74d35d7f 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-2.rs +++ b/tests/ui/imports/glob-conflict-cross-crate-2.rs @@ -1,10 +1,10 @@ //@ aux-build:glob-conflict-cross-crate-2-extern.rs - +//@ check-pass extern crate glob_conflict_cross_crate_2_extern; use glob_conflict_cross_crate_2_extern::*; fn main() { - let _a: C = 1; //~ ERROR `C` is ambiguous + let _a: C = 1; //~ WARN `C` is ambiguous //~| WARN this was previously accepted } diff --git a/tests/ui/imports/glob-conflict-cross-crate-2.stderr b/tests/ui/imports/glob-conflict-cross-crate-2.stderr index cbc2180c14f4..2ee519a364b3 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-2.stderr +++ b/tests/ui/imports/glob-conflict-cross-crate-2.stderr @@ -1,4 +1,4 @@ -error: `C` is ambiguous +warning: `C` is ambiguous --> $DIR/glob-conflict-cross-crate-2.rs:8:13 | LL | let _a: C = 1; @@ -17,12 +17,12 @@ note: `C` could also refer to the type alias defined here | LL | pub use b::*; | ^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `C` is ambiguous +warning: `C` is ambiguous --> $DIR/glob-conflict-cross-crate-2.rs:8:13 | LL | let _a: C = 1; @@ -41,5 +41,5 @@ note: `C` could also refer to the type alias defined here | LL | pub use b::*; | ^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/glob-conflict-cross-crate-3.rs b/tests/ui/imports/glob-conflict-cross-crate-3.rs index 31c234b9250f..a7b215359090 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-3.rs +++ b/tests/ui/imports/glob-conflict-cross-crate-3.rs @@ -1,5 +1,5 @@ //@ aux-build:glob-conflict-cross-crate-2-extern.rs - +//@ check-pass extern crate glob_conflict_cross_crate_2_extern; mod a { @@ -11,8 +11,8 @@ use a::*; fn main() { let _a: C = 1; - //~^ ERROR `C` is ambiguous - //~| ERROR `C` is ambiguous + //~^ WARN `C` is ambiguous + //~| WARN `C` is ambiguous //~| WARN this was previously accepted //~| WARN this was previously accepted } diff --git a/tests/ui/imports/glob-conflict-cross-crate-3.stderr b/tests/ui/imports/glob-conflict-cross-crate-3.stderr index 213eafda20b7..c7457efe866e 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-3.stderr +++ b/tests/ui/imports/glob-conflict-cross-crate-3.stderr @@ -1,4 +1,4 @@ -error: `C` is ambiguous +warning: `C` is ambiguous --> $DIR/glob-conflict-cross-crate-3.rs:13:13 | LL | let _a: C = 1; @@ -17,9 +17,9 @@ note: `C` could also refer to the type alias defined here | LL | pub use b::*; | ^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: `C` is ambiguous +warning: `C` is ambiguous --> $DIR/glob-conflict-cross-crate-3.rs:13:13 | LL | let _a: C = 1; @@ -41,10 +41,10 @@ LL | use a::*; | ^^^^ = help: consider adding an explicit import of `C` to disambiguate -error: aborting due to 2 previous errors +warning: 2 warnings emitted Future incompatibility report: Future breakage diagnostic: -error: `C` is ambiguous +warning: `C` is ambiguous --> $DIR/glob-conflict-cross-crate-3.rs:13:13 | LL | let _a: C = 1; @@ -63,10 +63,10 @@ note: `C` could also refer to the type alias defined here | LL | pub use b::*; | ^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default Future breakage diagnostic: -error: `C` is ambiguous +warning: `C` is ambiguous --> $DIR/glob-conflict-cross-crate-3.rs:13:13 | LL | let _a: C = 1; @@ -87,5 +87,5 @@ note: `C` could also refer to the type alias imported here LL | use a::*; | ^^^^ = help: consider adding an explicit import of `C` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/issue-114682-2.rs b/tests/ui/imports/issue-114682-2.rs index a9459c5b02ef..da145f3addc0 100644 --- a/tests/ui/imports/issue-114682-2.rs +++ b/tests/ui/imports/issue-114682-2.rs @@ -1,12 +1,12 @@ //@ aux-build: issue-114682-2-extern.rs // https://github.com/rust-lang/rust/pull/114682#issuecomment-1879998900 - +//@ check-pass extern crate issue_114682_2_extern; -use issue_114682_2_extern::max; //~ ERROR `max` is ambiguous +use issue_114682_2_extern::max; //~ WARN `max` is ambiguous //~| WARN this was previously accepted -type A = issue_114682_2_extern::max; //~ ERROR `max` is ambiguous +type A = issue_114682_2_extern::max; //~ WARN `max` is ambiguous //~| WARN this was previously accepted fn main() {} diff --git a/tests/ui/imports/issue-114682-2.stderr b/tests/ui/imports/issue-114682-2.stderr index 07c696651c38..f93e4409f0c4 100644 --- a/tests/ui/imports/issue-114682-2.stderr +++ b/tests/ui/imports/issue-114682-2.stderr @@ -1,4 +1,4 @@ -error: `max` is ambiguous +warning: `max` is ambiguous --> $DIR/issue-114682-2.rs:6:28 | LL | use issue_114682_2_extern::max; @@ -17,9 +17,9 @@ note: `max` could also refer to the module defined here | LL | pub use self::d::*; | ^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: `max` is ambiguous +warning: `max` is ambiguous --> $DIR/issue-114682-2.rs:9:33 | LL | type A = issue_114682_2_extern::max; @@ -39,10 +39,10 @@ note: `max` could also refer to the module defined here LL | pub use self::d::*; | ^^^^^^^ -error: aborting due to 2 previous errors +warning: 2 warnings emitted Future incompatibility report: Future breakage diagnostic: -error: `max` is ambiguous +warning: `max` is ambiguous --> $DIR/issue-114682-2.rs:6:28 | LL | use issue_114682_2_extern::max; @@ -61,10 +61,10 @@ note: `max` could also refer to the module defined here | LL | pub use self::d::*; | ^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default Future breakage diagnostic: -error: `max` is ambiguous +warning: `max` is ambiguous --> $DIR/issue-114682-2.rs:9:33 | LL | type A = issue_114682_2_extern::max; @@ -83,5 +83,5 @@ note: `max` could also refer to the module defined here | LL | pub use self::d::*; | ^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/issue-114682-4.rs b/tests/ui/imports/issue-114682-4.rs index 01921928a007..29e175b5ed54 100644 --- a/tests/ui/imports/issue-114682-4.rs +++ b/tests/ui/imports/issue-114682-4.rs @@ -6,7 +6,7 @@ extern crate issue_114682_4_extern; use issue_114682_4_extern::*; //~v ERROR type alias takes 1 generic argument but 2 generic arguments were supplied -fn a() -> Result { //~ ERROR `Result` is ambiguous +fn a() -> Result { //~ WARN `Result` is ambiguous //~| WARN this was previously accepted Ok(1) } diff --git a/tests/ui/imports/issue-114682-4.stderr b/tests/ui/imports/issue-114682-4.stderr index 5e677cd7ae72..12cb9ae95a42 100644 --- a/tests/ui/imports/issue-114682-4.stderr +++ b/tests/ui/imports/issue-114682-4.stderr @@ -1,4 +1,4 @@ -error: `Result` is ambiguous +warning: `Result` is ambiguous --> $DIR/issue-114682-4.rs:9:11 | LL | fn a() -> Result { @@ -17,7 +17,7 @@ note: `Result` could also refer to the type alias defined here | LL | pub use b::*; | ^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default error[E0107]: type alias takes 1 generic argument but 2 generic arguments were supplied --> $DIR/issue-114682-4.rs:9:11 @@ -33,11 +33,11 @@ note: type alias defined here, with 1 generic parameter: `T` LL | pub type Result = std::result::Result; | ^^^^^^ - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error; 1 warning emitted For more information about this error, try `rustc --explain E0107`. Future incompatibility report: Future breakage diagnostic: -error: `Result` is ambiguous +warning: `Result` is ambiguous --> $DIR/issue-114682-4.rs:9:11 | LL | fn a() -> Result { @@ -56,5 +56,5 @@ note: `Result` could also refer to the type alias defined here | LL | pub use b::*; | ^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/issue-114682-5.rs b/tests/ui/imports/issue-114682-5.rs index be33960e40b8..1408a8105d75 100644 --- a/tests/ui/imports/issue-114682-5.rs +++ b/tests/ui/imports/issue-114682-5.rs @@ -9,7 +9,7 @@ extern crate issue_114682_5_extern_2; use issue_114682_5_extern_2::p::*; use issue_114682_5_extern_1::Url; //~^ ERROR `issue_114682_5_extern_1` is ambiguous -//~| ERROR `issue_114682_5_extern_1` is ambiguous +//~| WARN `issue_114682_5_extern_1` is ambiguous //~| ERROR unresolved import `issue_114682_5_extern_1::Url` //~| WARN this was previously accepted diff --git a/tests/ui/imports/issue-114682-5.stderr b/tests/ui/imports/issue-114682-5.stderr index 427a5b16765b..74b42e0990b7 100644 --- a/tests/ui/imports/issue-114682-5.stderr +++ b/tests/ui/imports/issue-114682-5.stderr @@ -26,7 +26,7 @@ LL | use issue_114682_5_extern_2::p::*; = help: consider adding an explicit import of `issue_114682_5_extern_1` to disambiguate = help: or use `crate::issue_114682_5_extern_1` to refer to this module unambiguously -error: `issue_114682_5_extern_1` is ambiguous +warning: `issue_114682_5_extern_1` is ambiguous --> $DIR/issue-114682-5.rs:10:5 | LL | use issue_114682_5_extern_1::Url; @@ -46,14 +46,14 @@ note: `issue_114682_5_extern_1` could also refer to the crate defined here LL | pub use crate::*; | ^^^^^ = help: use `::issue_114682_5_extern_1` to refer to this crate unambiguously - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors; 1 warning emitted Some errors have detailed explanations: E0432, E0659. For more information about an error, try `rustc --explain E0432`. Future incompatibility report: Future breakage diagnostic: -error: `issue_114682_5_extern_1` is ambiguous +warning: `issue_114682_5_extern_1` is ambiguous --> $DIR/issue-114682-5.rs:10:5 | LL | use issue_114682_5_extern_1::Url; @@ -73,5 +73,5 @@ note: `issue_114682_5_extern_1` could also refer to the crate defined here LL | pub use crate::*; | ^^^^^ = help: use `::issue_114682_5_extern_1` to refer to this crate unambiguously - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/issue-114682-6.rs b/tests/ui/imports/issue-114682-6.rs index 92173f4b8464..480caedb70a1 100644 --- a/tests/ui/imports/issue-114682-6.rs +++ b/tests/ui/imports/issue-114682-6.rs @@ -1,12 +1,12 @@ //@ aux-build: issue-114682-6-extern.rs // https://github.com/rust-lang/rust/pull/114682#issuecomment-1880755441 - +//@ check-pass extern crate issue_114682_6_extern; use issue_114682_6_extern::*; fn main() { - let log = 2; //~ ERROR `log` is ambiguous + let log = 2; //~ WARN `log` is ambiguous //~| WARN this was previously accepted let _ = log; } diff --git a/tests/ui/imports/issue-114682-6.stderr b/tests/ui/imports/issue-114682-6.stderr index 67ad25798c19..37f8f6c16ff2 100644 --- a/tests/ui/imports/issue-114682-6.stderr +++ b/tests/ui/imports/issue-114682-6.stderr @@ -1,4 +1,4 @@ -error: `log` is ambiguous +warning: `log` is ambiguous --> $DIR/issue-114682-6.rs:9:9 | LL | let log = 2; @@ -17,12 +17,12 @@ note: `log` could also refer to the function defined here | LL | pub use self::b::*; | ^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `log` is ambiguous +warning: `log` is ambiguous --> $DIR/issue-114682-6.rs:9:9 | LL | let log = 2; @@ -41,5 +41,5 @@ note: `log` could also refer to the function defined here | LL | pub use self::b::*; | ^^^^^^^ - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/overwrite-different-ambig-2.rs b/tests/ui/imports/overwrite-different-ambig-2.rs index 1b6d20e24d30..1d6416c00fdc 100644 --- a/tests/ui/imports/overwrite-different-ambig-2.rs +++ b/tests/ui/imports/overwrite-different-ambig-2.rs @@ -1,3 +1,5 @@ +//@ check-pass + mod m1 { mod inner { pub struct S {} @@ -19,6 +21,6 @@ use m1::*; use m2::*; fn main() { - let _: m1::S = S {}; //~ ERROR `S` is ambiguous + let _: m1::S = S {}; //~ WARN `S` is ambiguous //~| WARN this was previously accepted } diff --git a/tests/ui/imports/overwrite-different-ambig-2.stderr b/tests/ui/imports/overwrite-different-ambig-2.stderr index e75f552d119c..2d8446585717 100644 --- a/tests/ui/imports/overwrite-different-ambig-2.stderr +++ b/tests/ui/imports/overwrite-different-ambig-2.stderr @@ -1,5 +1,5 @@ -error: `S` is ambiguous - --> $DIR/overwrite-different-ambig-2.rs:22:20 +warning: `S` is ambiguous + --> $DIR/overwrite-different-ambig-2.rs:24:20 | LL | let _: m1::S = S {}; | ^ ambiguous name @@ -8,24 +8,24 @@ LL | let _: m1::S = S {}; = note: for more information, see issue #114095 = note: ambiguous because of multiple glob imports of a name in the same module note: `S` could refer to the struct imported here - --> $DIR/overwrite-different-ambig-2.rs:18:5 + --> $DIR/overwrite-different-ambig-2.rs:20:5 | LL | use m1::*; | ^^^^^ = help: consider adding an explicit import of `S` to disambiguate note: `S` could also refer to the struct imported here - --> $DIR/overwrite-different-ambig-2.rs:19:5 + --> $DIR/overwrite-different-ambig-2.rs:21:5 | LL | use m2::*; | ^^^^^ = help: consider adding an explicit import of `S` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 1 previous error +warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: -error: `S` is ambiguous - --> $DIR/overwrite-different-ambig-2.rs:22:20 +warning: `S` is ambiguous + --> $DIR/overwrite-different-ambig-2.rs:24:20 | LL | let _: m1::S = S {}; | ^ ambiguous name @@ -34,16 +34,16 @@ LL | let _: m1::S = S {}; = note: for more information, see issue #114095 = note: ambiguous because of multiple glob imports of a name in the same module note: `S` could refer to the struct imported here - --> $DIR/overwrite-different-ambig-2.rs:18:5 + --> $DIR/overwrite-different-ambig-2.rs:20:5 | LL | use m1::*; | ^^^^^ = help: consider adding an explicit import of `S` to disambiguate note: `S` could also refer to the struct imported here - --> $DIR/overwrite-different-ambig-2.rs:19:5 + --> $DIR/overwrite-different-ambig-2.rs:21:5 | LL | use m2::*; | ^^^^^ = help: consider adding an explicit import of `S` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default diff --git a/tests/ui/imports/unresolved-seg-after-ambiguous.rs b/tests/ui/imports/unresolved-seg-after-ambiguous.rs index 67366deabaaf..820f579ae3bb 100644 --- a/tests/ui/imports/unresolved-seg-after-ambiguous.rs +++ b/tests/ui/imports/unresolved-seg-after-ambiguous.rs @@ -18,7 +18,7 @@ mod a { use self::a::E::in_exist; //~^ ERROR: unresolved import `self::a::E` -//~| ERROR: `E` is ambiguous +//~| WARN: `E` is ambiguous //~| WARNING: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! fn main() {} diff --git a/tests/ui/imports/unresolved-seg-after-ambiguous.stderr b/tests/ui/imports/unresolved-seg-after-ambiguous.stderr index 67316462a27e..411cd1dbe5ef 100644 --- a/tests/ui/imports/unresolved-seg-after-ambiguous.stderr +++ b/tests/ui/imports/unresolved-seg-after-ambiguous.stderr @@ -4,7 +4,7 @@ error[E0432]: unresolved import `self::a::E` LL | use self::a::E::in_exist; | ^ `E` is a struct, not a module -error: `E` is ambiguous +warning: `E` is ambiguous --> $DIR/unresolved-seg-after-ambiguous.rs:19:14 | LL | use self::a::E::in_exist; @@ -25,13 +25,13 @@ note: `E` could also refer to the struct imported here LL | pub use self::d::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `E` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default -error: aborting due to 2 previous errors +error: aborting due to 1 previous error; 1 warning emitted For more information about this error, try `rustc --explain E0432`. Future incompatibility report: Future breakage diagnostic: -error: `E` is ambiguous +warning: `E` is ambiguous --> $DIR/unresolved-seg-after-ambiguous.rs:19:14 | LL | use self::a::E::in_exist; @@ -52,5 +52,5 @@ note: `E` could also refer to the struct imported here LL | pub use self::d::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `E` to disambiguate - = note: `#[deny(ambiguous_glob_imports)]` (part of `#[deny(future_incompatible)]`) on by default + = note: `#[warn(ambiguous_glob_imports)]` (part of `#[warn(future_incompatible)]`) on by default From cd7d40d97507d75b4d0341e19a24edfaf654c6c5 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 15 Jan 2026 15:06:29 +0100 Subject: [PATCH 041/146] Update `rustc_attr_parsing::SharedContext::target` type from `Option` to `Target` --- compiler/rustc_attr_parsing/src/attributes/cfg.rs | 3 ++- compiler/rustc_attr_parsing/src/attributes/cfg_select.rs | 4 +++- compiler/rustc_attr_parsing/src/attributes/doc.rs | 4 ++-- compiler/rustc_attr_parsing/src/context.rs | 2 +- compiler/rustc_attr_parsing/src/interface.rs | 9 ++++++--- compiler/rustc_builtin_macros/src/cfg.rs | 4 +++- compiler/rustc_expand/src/config.rs | 3 +++ compiler/rustc_expand/src/expand.rs | 2 ++ 8 files changed, 22 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index ccf0a394afd0..3e430cf59485 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -9,7 +9,7 @@ use rustc_feature::{ }; use rustc_hir::attrs::CfgEntry; use rustc_hir::lints::AttributeLintKind; -use rustc_hir::{AttrPath, RustcVersion}; +use rustc_hir::{AttrPath, RustcVersion, Target}; use rustc_parse::parser::{ForceCollect, Parser}; use rustc_parse::{exp, parse_in}; use rustc_session::Session; @@ -374,6 +374,7 @@ fn parse_cfg_attr_internal<'a>( ParsedDescription::Attribute, pred_span, CRATE_NODE_ID, + Target::Crate, features, ShouldEmit::ErrorsAndLints, &meta, diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs b/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs index 24b989e22a2b..e80084021a84 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs @@ -2,8 +2,8 @@ use rustc_ast::token::Token; use rustc_ast::tokenstream::TokenStream; use rustc_ast::{AttrStyle, NodeId, token}; use rustc_feature::{AttributeTemplate, Features}; -use rustc_hir::AttrPath; use rustc_hir::attrs::CfgEntry; +use rustc_hir::{AttrPath, Target}; use rustc_parse::exp; use rustc_parse::parser::Parser; use rustc_session::Session; @@ -91,6 +91,8 @@ pub fn parse_cfg_select( ParsedDescription::Macro, cfg_span, lint_node_id, + // Doesn't matter what the target actually is here. + Target::Crate, features, ShouldEmit::ErrorsAndLints, &meta, diff --git a/compiler/rustc_attr_parsing/src/attributes/doc.rs b/compiler/rustc_attr_parsing/src/attributes/doc.rs index 6cc4ac35eadb..99825d93216f 100644 --- a/compiler/rustc_attr_parsing/src/attributes/doc.rs +++ b/compiler/rustc_attr_parsing/src/attributes/doc.rs @@ -50,7 +50,7 @@ fn check_attr_not_crate_level( span: Span, attr_name: Symbol, ) -> bool { - if cx.shared.target.is_some_and(|target| target == Target::Crate) { + if cx.shared.target == Target::Crate { cx.emit_err(DocAttrNotCrateLevel { span, attr_name }); return false; } @@ -59,7 +59,7 @@ fn check_attr_not_crate_level( /// Checks that an attribute is used at the crate level. Returns `true` if valid. fn check_attr_crate_level(cx: &mut AcceptContext<'_, '_, S>, span: Span) -> bool { - if cx.shared.target.is_some_and(|target| target != Target::Crate) { + if cx.shared.target != Target::Crate { cx.emit_lint( rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES, AttributeLintKind::AttrCrateLevelOnly, diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 8305d027d13c..f885151330a3 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -665,7 +665,7 @@ pub struct SharedContext<'p, 'sess, S: Stage> { pub(crate) target_span: Span, /// The id ([`NodeId`] if `S` is `Early`, [`HirId`] if `S` is `Late`) of the syntactical component this attribute was applied to pub(crate) target_id: S::Id, - pub(crate) target: Option, + pub(crate) target: rustc_hir::Target, pub(crate) emit_lint: &'p mut dyn FnMut(AttributeLint), } diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index b7137c60e63a..8f2c36fa8c9e 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -135,6 +135,7 @@ impl<'sess> AttributeParser<'sess, Early> { attr: &ast::Attribute, target_span: Span, target_node_id: NodeId, + target: Target, features: Option<&'sess Features>, emit_errors: ShouldEmit, parse_fn: fn(cx: &mut AcceptContext<'_, '_, Early>, item: &ArgParser) -> Option, @@ -163,6 +164,7 @@ impl<'sess> AttributeParser<'sess, Early> { ParsedDescription::Attribute, target_span, target_node_id, + target, features, emit_errors, &args, @@ -183,6 +185,7 @@ impl<'sess> AttributeParser<'sess, Early> { parsed_description: ParsedDescription, target_span: Span, target_node_id: NodeId, + target: Target, features: Option<&'sess Features>, emit_errors: ShouldEmit, args: &I, @@ -218,7 +221,7 @@ impl<'sess> AttributeParser<'sess, Early> { cx: &mut parser, target_span, target_id: target_node_id, - target: None, + target, emit_lint: &mut emit_lint, }, attr_span, @@ -379,7 +382,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { cx: self, target_span, target_id, - target: Some(target), + target, emit_lint: &mut emit_lint, }, attr_span, @@ -431,7 +434,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { cx: self, target_span, target_id, - target: Some(target), + target, emit_lint: &mut emit_lint, }, all_attrs: &attr_paths, diff --git a/compiler/rustc_builtin_macros/src/cfg.rs b/compiler/rustc_builtin_macros/src/cfg.rs index 557daa94b98e..be1ce5a06d5e 100644 --- a/compiler/rustc_builtin_macros/src/cfg.rs +++ b/compiler/rustc_builtin_macros/src/cfg.rs @@ -10,8 +10,8 @@ use rustc_attr_parsing::{ AttributeParser, CFG_TEMPLATE, ParsedDescription, ShouldEmit, parse_cfg_entry, }; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; -use rustc_hir::AttrPath; use rustc_hir::attrs::CfgEntry; +use rustc_hir::{AttrPath, Target}; use rustc_parse::exp; use rustc_span::{ErrorGuaranteed, Span, sym}; @@ -52,6 +52,8 @@ fn parse_cfg(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream) -> Result StripUnconfigured<'a> { attr, attr.span, self.lint_node_id, + // Doesn't matter what the target actually is here. + Target::Crate, self.features, emit_errors, parse_cfg, diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index c130d9f59940..fabe1f5a8c5d 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -2218,6 +2218,8 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { &attr, attr.span, self.cfg().lint_node_id, + // Target doesn't matter for `cfg` parsing. + Target::Crate, self.cfg().features, ShouldEmit::ErrorsAndLints, parse_cfg, From 820579243f5cd9a27c3831d6c335f138a4567c41 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 15 Jan 2026 15:39:00 +0100 Subject: [PATCH 042/146] Remove `rustc_attr_parsing::SharedContext::target_id` field --- compiler/rustc_ast_lowering/src/lib.rs | 12 +++-- compiler/rustc_attr_parsing/src/context.rs | 11 +++-- compiler/rustc_attr_parsing/src/interface.rs | 47 +++++++------------- compiler/rustc_attr_parsing/src/safety.rs | 16 +++---- compiler/rustc_resolve/src/def_collector.rs | 3 +- 5 files changed, 36 insertions(+), 53 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 350fa04ab3bd..51d1fd20cec6 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -51,7 +51,7 @@ use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId}; use rustc_hir::definitions::{DefPathData, DisambiguatorState}; -use rustc_hir::lints::DelayedLint; +use rustc_hir::lints::{AttributeLint, DelayedLint}; use rustc_hir::{ self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource, LifetimeSyntax, ParamName, Target, TraitCandidate, find_attr, @@ -1022,12 +1022,16 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.attribute_parser.parse_attribute_list( attrs, target_span, - target_hir_id, target, OmitDoc::Lower, |s| l.lower(s), - |l| { - self.delayed_lints.push(DelayedLint::AttributeParsing(l)); + |lint_id, span, kind| { + self.delayed_lints.push(DelayedLint::AttributeParsing(AttributeLint { + lint_id, + id: target_hir_id, + span, + kind, + })); }, ) } diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index f885151330a3..d6a3ddf4d300 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -8,7 +8,7 @@ use rustc_ast::{AttrStyle, MetaItemLit, NodeId}; use rustc_errors::{Diag, Diagnostic, Level}; use rustc_feature::{AttrSuggestionStyle, AttributeTemplate}; use rustc_hir::attrs::AttributeKind; -use rustc_hir::lints::{AttributeLint, AttributeLintKind}; +use rustc_hir::lints::AttributeLintKind; use rustc_hir::{AttrPath, HirId}; use rustc_session::Session; use rustc_session::lint::{Lint, LintId}; @@ -417,8 +417,7 @@ impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> { ) { return; } - let id = self.target_id; - (self.emit_lint)(AttributeLint { lint_id: LintId::of(lint), id, span, kind }); + (self.emit_lint)(LintId::of(lint), span, kind); } pub(crate) fn warn_unused_duplicate(&mut self, used_span: Span, unused_span: Span) { @@ -663,11 +662,11 @@ pub struct SharedContext<'p, 'sess, S: Stage> { pub(crate) cx: &'p mut AttributeParser<'sess, S>, /// The span of the syntactical component this attribute was applied to pub(crate) target_span: Span, - /// The id ([`NodeId`] if `S` is `Early`, [`HirId`] if `S` is `Late`) of the syntactical component this attribute was applied to - pub(crate) target_id: S::Id, pub(crate) target: rustc_hir::Target, - pub(crate) emit_lint: &'p mut dyn FnMut(AttributeLint), + /// The second argument of the closure is a [`NodeId`] if `S` is `Early` and a [`HirId`] if `S` + /// is `Late` and is the ID of the syntactical component this attribute was applied to. + pub(crate) emit_lint: &'p mut dyn FnMut(LintId, Span, AttributeLintKind), } /// Context given to every attribute parser during finalization. diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 8f2c36fa8c9e..c6be18321b5e 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -6,10 +6,10 @@ use rustc_ast::{AttrItemKind, AttrStyle, NodeId, Safety}; use rustc_errors::DiagCtxtHandle; use rustc_feature::{AttributeTemplate, Features}; use rustc_hir::attrs::AttributeKind; -use rustc_hir::lints::AttributeLint; +use rustc_hir::lints::AttributeLintKind; use rustc_hir::{AttrArgs, AttrItem, AttrPath, Attribute, HashIgnoredAttrId, Target}; use rustc_session::Session; -use rustc_session::lint::BuiltinLintDiag; +use rustc_session::lint::{BuiltinLintDiag, LintId}; use rustc_span::{DUMMY_SP, Span, Symbol, sym}; use crate::context::{AcceptContext, FinalizeContext, SharedContext, Stage}; @@ -113,16 +113,15 @@ impl<'sess> AttributeParser<'sess, Early> { p.parse_attribute_list( attrs, target_span, - target_node_id, target, OmitDoc::Skip, std::convert::identity, - |lint| { + |lint_id, span, kind| { sess.psess.buffer_lint( - lint.lint_id.lint, - lint.span, - lint.id, - BuiltinLintDiag::AttributeLint(lint.kind), + lint_id.lint, + span, + target_node_id, + BuiltinLintDiag::AttributeLint(kind), ) }, ) @@ -199,28 +198,21 @@ impl<'sess> AttributeParser<'sess, Early> { sess, stage: Early { emit_errors }, }; - let mut emit_lint = |lint: AttributeLint| { + let mut emit_lint = |lint_id: LintId, span: Span, kind: AttributeLintKind| { sess.psess.buffer_lint( - lint.lint_id.lint, - lint.span, - lint.id, - BuiltinLintDiag::AttributeLint(lint.kind), + lint_id.lint, + span, + target_node_id, + BuiltinLintDiag::AttributeLint(kind), ) }; if let Some(safety) = attr_safety { - parser.check_attribute_safety( - &attr_path, - inner_span, - safety, - &mut emit_lint, - target_node_id, - ) + parser.check_attribute_safety(&attr_path, inner_span, safety, &mut emit_lint) } let mut cx: AcceptContext<'_, 'sess, Early> = AcceptContext { shared: SharedContext { cx: &mut parser, target_span, - target_id: target_node_id, target, emit_lint: &mut emit_lint, }, @@ -269,11 +261,10 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { &mut self, attrs: &[ast::Attribute], target_span: Span, - target_id: S::Id, target: Target, omit_doc: OmitDoc, lower_span: impl Copy + Fn(Span) -> Span, - mut emit_lint: impl FnMut(AttributeLint), + mut emit_lint: impl FnMut(LintId, Span, AttributeLintKind), ) -> Vec { let mut attributes = Vec::new(); let mut attr_paths: Vec> = Vec::new(); @@ -329,7 +320,6 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { lower_span(n.item.span()), n.item.unsafety, &mut emit_lint, - target_id, ); let parts = @@ -381,7 +371,6 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { shared: SharedContext { cx: self, target_span, - target_id, target, emit_lint: &mut emit_lint, }, @@ -430,13 +419,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { early_parsed_state.finalize_early_parsed_attributes(&mut attributes); for f in &S::parsers().finalizers { if let Some(attr) = f(&mut FinalizeContext { - shared: SharedContext { - cx: self, - target_span, - target_id, - target, - emit_lint: &mut emit_lint, - }, + shared: SharedContext { cx: self, target_span, target, emit_lint: &mut emit_lint }, all_attrs: &attr_paths, }) { attributes.push(Attribute::Parsed(attr)); diff --git a/compiler/rustc_attr_parsing/src/safety.rs b/compiler/rustc_attr_parsing/src/safety.rs index 9fca57f88025..4cc703c5d0cc 100644 --- a/compiler/rustc_attr_parsing/src/safety.rs +++ b/compiler/rustc_attr_parsing/src/safety.rs @@ -1,7 +1,7 @@ use rustc_ast::Safety; use rustc_feature::{AttributeSafety, BUILTIN_ATTRIBUTE_MAP}; use rustc_hir::AttrPath; -use rustc_hir::lints::{AttributeLint, AttributeLintKind}; +use rustc_hir::lints::AttributeLintKind; use rustc_session::lint::LintId; use rustc_session::lint::builtin::UNSAFE_ATTR_OUTSIDE_UNSAFE; use rustc_span::Span; @@ -15,8 +15,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { attr_path: &AttrPath, attr_span: Span, attr_safety: Safety, - emit_lint: &mut impl FnMut(AttributeLint), - target_id: S::Id, + emit_lint: &mut impl FnMut(LintId, Span, AttributeLintKind), ) { if matches!(self.stage.should_emit(), ShouldEmit::Nothing) { return; @@ -82,16 +81,15 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { }, ); } else { - emit_lint(AttributeLint { - lint_id: LintId::of(UNSAFE_ATTR_OUTSIDE_UNSAFE), - id: target_id, - span: path_span, - kind: AttributeLintKind::UnsafeAttrOutsideUnsafe { + emit_lint( + LintId::of(UNSAFE_ATTR_OUTSIDE_UNSAFE), + path_span, + AttributeLintKind::UnsafeAttrOutsideUnsafe { attribute_name_span: path_span, sugg_spans: not_from_proc_macro .then(|| (diag_span.shrink_to_lo(), diag_span.shrink_to_hi())), }, - }) + ) } } diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index ea5640ecc1fa..8f1a43c090b1 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -148,11 +148,10 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { let attrs = parser.parse_attribute_list( &i.attrs, i.span, - i.id, Target::MacroDef, OmitDoc::Skip, std::convert::identity, - |_l| { + |_lint_id, _span, _kind| { // FIXME(jdonszelmann): emit lints here properly // NOTE that before new attribute parsing, they didn't happen either // but it would be nice if we could change that. From 6cd43592a8dbbe8f4c888eca3a4994710b57d978 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Bj=C3=B8rnager=20Jensen?= Date: Thu, 15 Jan 2026 15:46:39 +0100 Subject: [PATCH 043/146] Stabilise 'EULER_GAMMA' and 'GOLDEN_RATIO' constants; --- library/core/src/num/f128.rs | 8 ++++---- library/core/src/num/f16.rs | 6 ++---- library/core/src/num/f32.rs | 8 ++++---- library/core/src/num/f64.rs | 8 ++++---- 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index bf99fee4fc78..65afdd2969b8 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -34,13 +34,13 @@ pub mod consts { /// The golden ratio (φ) #[unstable(feature = "f128", issue = "116909")] - // Also, #[unstable(feature = "more_float_constants", issue = "146939")] - pub const PHI: f128 = 1.61803398874989484820458683436563811772030917980576286213545_f128; + pub const GOLDEN_RATIO: f128 = + 1.61803398874989484820458683436563811772030917980576286213545_f128; /// The Euler-Mascheroni constant (γ) #[unstable(feature = "f128", issue = "116909")] - // Also, #[unstable(feature = "more_float_constants", issue = "146939")] - pub const EGAMMA: f128 = 0.577215664901532860606512090082402431042159335939923598805767_f128; + pub const EULER_GAMMA: f128 = + 0.577215664901532860606512090082402431042159335939923598805767_f128; /// π/2 #[unstable(feature = "f128", issue = "116909")] diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index f39ee22871d5..bcf0f3fc45c2 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -36,13 +36,11 @@ pub mod consts { /// The golden ratio (φ) #[unstable(feature = "f16", issue = "116909")] - // Also, #[unstable(feature = "more_float_constants", issue = "146939")] - pub const PHI: f16 = 1.618033988749894848204586834365638118_f16; + pub const GOLDEN_RATIO: f16 = 1.618033988749894848204586834365638118_f16; /// The Euler-Mascheroni constant (γ) #[unstable(feature = "f16", issue = "116909")] - // Also, #[unstable(feature = "more_float_constants", issue = "146939")] - pub const EGAMMA: f16 = 0.577215664901532860606512090082402431_f16; + pub const EULER_GAMMA: f16 = 0.577215664901532860606512090082402431_f16; /// π/2 #[unstable(feature = "f16", issue = "116909")] diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index 6fe4285374b2..f7f16b57a526 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -292,12 +292,12 @@ pub mod consts { pub const TAU: f32 = 6.28318530717958647692528676655900577_f32; /// The golden ratio (φ) - #[unstable(feature = "more_float_constants", issue = "146939")] - pub const PHI: f32 = 1.618033988749894848204586834365638118_f32; + #[stable(feature = "euler_gamma_golden_ratio", since = "CURRENT_RUSTC_VERSION")] + pub const GOLDEN_RATIO: f32 = 1.618033988749894848204586834365638118_f32; /// The Euler-Mascheroni constant (γ) - #[unstable(feature = "more_float_constants", issue = "146939")] - pub const EGAMMA: f32 = 0.577215664901532860606512090082402431_f32; + #[stable(feature = "euler_gamma_golden_ratio", since = "CURRENT_RUSTC_VERSION")] + pub const EULER_GAMMA: f32 = 0.577215664901532860606512090082402431_f32; /// π/2 #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index d0aca152415e..f021c88f2235 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -292,12 +292,12 @@ pub mod consts { pub const TAU: f64 = 6.28318530717958647692528676655900577_f64; /// The golden ratio (φ) - #[unstable(feature = "more_float_constants", issue = "146939")] - pub const PHI: f64 = 1.618033988749894848204586834365638118_f64; + #[stable(feature = "euler_gamma_golden_ratio", since = "CURRENT_RUSTC_VERSION")] + pub const GOLDEN_RATIO: f64 = 1.618033988749894848204586834365638118_f64; /// The Euler-Mascheroni constant (γ) - #[unstable(feature = "more_float_constants", issue = "146939")] - pub const EGAMMA: f64 = 0.577215664901532860606512090082402431_f64; + #[stable(feature = "euler_gamma_golden_ratio", since = "CURRENT_RUSTC_VERSION")] + pub const EULER_GAMMA: f64 = 0.577215664901532860606512090082402431_f64; /// π/2 #[stable(feature = "rust1", since = "1.0.0")] From 08362d3e51a2da3eb10fa7a918c5739249873cd8 Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Fri, 16 Jan 2026 00:35:10 +0900 Subject: [PATCH 044/146] fix: Do not delay E0107 when there exists an assoc ty with the same name --- .../src/hir_ty_lowering/generics.rs | 22 ++++++++++-- ...me-name-with-lacking-generic-arg-148121.rs | 17 +++++++++ ...ame-with-lacking-generic-arg-148121.stderr | 35 +++++++++++++++++++ 3 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 tests/ui/traits/associated_type_bound/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.rs create mode 100644 tests/ui/traits/associated_type_bound/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.stderr diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs index f5a64ede398e..0a2946323c7b 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs @@ -9,6 +9,7 @@ use rustc_middle::ty::{ }; use rustc_session::lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS; use rustc_span::kw; +use rustc_trait_selection::traits; use smallvec::SmallVec; use tracing::{debug, instrument}; @@ -535,9 +536,26 @@ pub(crate) fn check_generic_arg_count( .map(|param| param.name) .collect(); if constraint_names == param_names { + let has_assoc_ty_with_same_name = + if let DefKind::Trait = cx.tcx().def_kind(def_id) { + gen_args.constraints.iter().any(|constraint| { + traits::supertrait_def_ids(cx.tcx(), def_id).any(|trait_did| { + cx.probe_trait_that_defines_assoc_item( + trait_did, + ty::AssocTag::Type, + constraint.ident, + ) + }) + }) + } else { + false + }; // We set this to true and delay emitting `WrongNumberOfGenericArgs` - // to provide a succinct error for cases like issue #113073 - all_params_are_binded = true; + // to provide a succinct error for cases like issue #113073, + // but only if when we don't have any assoc type with the same name with a + // generic arg. Otherwise it will cause an ICE due to a delayed error because we + // don't have any error other than `WrongNumberOfGenericArgs`. + all_params_are_binded = !has_assoc_ty_with_same_name; }; } diff --git a/tests/ui/traits/associated_type_bound/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.rs b/tests/ui/traits/associated_type_bound/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.rs new file mode 100644 index 000000000000..f1dffc0ff6b4 --- /dev/null +++ b/tests/ui/traits/associated_type_bound/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.rs @@ -0,0 +1,17 @@ +// A regression test for https://github.com/rust-lang/rust/issues/148121 + +pub trait Super { + type X; +} + +pub trait Zelf: Super {} + +pub trait A {} + +impl A for dyn Super {} +//~^ ERROR: trait takes 1 generic argument but 0 generic arguments were supplied + +impl A for dyn Zelf {} +//~^ ERROR: trait takes 1 generic argument but 0 generic arguments were supplied + +fn main() {} diff --git a/tests/ui/traits/associated_type_bound/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.stderr b/tests/ui/traits/associated_type_bound/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.stderr new file mode 100644 index 000000000000..5a7969193b55 --- /dev/null +++ b/tests/ui/traits/associated_type_bound/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.stderr @@ -0,0 +1,35 @@ +error[E0107]: trait takes 1 generic argument but 0 generic arguments were supplied + --> $DIR/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.rs:11:16 + | +LL | impl A for dyn Super {} + | ^^^^^ expected 1 generic argument + | +note: trait defined here, with 1 generic parameter: `X` + --> $DIR/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.rs:3:11 + | +LL | pub trait Super { + | ^^^^^ - +help: add missing generic argument + | +LL | impl A for dyn Super {} + | ++ + +error[E0107]: trait takes 1 generic argument but 0 generic arguments were supplied + --> $DIR/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.rs:14:16 + | +LL | impl A for dyn Zelf {} + | ^^^^ expected 1 generic argument + | +note: trait defined here, with 1 generic parameter: `X` + --> $DIR/assoc-type-bounds-with-the-same-name-with-lacking-generic-arg-148121.rs:7:11 + | +LL | pub trait Zelf: Super {} + | ^^^^ - +help: add missing generic argument + | +LL | impl A for dyn Zelf {} + | ++ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0107`. From 8536979cdb67143bc09398150cf7d2f023992488 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maja=20K=C4=85dzio=C5=82ka?= Date: Thu, 15 Jan 2026 16:50:20 +0100 Subject: [PATCH 045/146] Move some match edge case tests While these test cases were inspired by issue 137467, they aren't directly related, and better fit into match-edge-cases_2.rs --- .../match/match-edge-cases_2.rs | 78 +++++++++++++++++++ tests/ui/closures/or-patterns-issue-137467.rs | 64 --------------- 2 files changed, 78 insertions(+), 64 deletions(-) diff --git a/tests/ui/closures/2229_closure_analysis/match/match-edge-cases_2.rs b/tests/ui/closures/2229_closure_analysis/match/match-edge-cases_2.rs index a3b19708899a..81013e5b2cd1 100644 --- a/tests/ui/closures/2229_closure_analysis/match/match-edge-cases_2.rs +++ b/tests/ui/closures/2229_closure_analysis/match/match-edge-cases_2.rs @@ -34,4 +34,82 @@ fn edge_case_if() { _b(); } +struct Unit; + +enum TSingle { + A(u32, u32), +} + +enum SSingle { + A { a: u32, b: u32 }, +} + +struct TStruct(u32, u32); +struct SStruct { a: u32, b: u32 } + + +// Destructuring a unit struct should not capture it +fn match_unit_struct(mut x: (Unit, u32)) { + let r = &mut x.0; + let _ = || { + let (Unit, a) = x; + a + }; + + let _ = *r; +} + +// The same is true for an equivalent enum +fn match_unit_enum(mut x: (SingleVariant, u32)) { + let r = &mut x.0; + let _ = || { + let (SingleVariant::A, a) = x; + a + }; + + let _ = *r; +} + +// More generally, destructuring a struct should only capture the fields being touched +fn match_struct(mut x: SStruct) { + let r = &mut x.a; + let _ = || { + let SStruct { b, .. } = x; + b + }; + + let _ = *r; +} + +fn match_tuple_struct(mut x: TStruct) { + let r = &mut x.0; + let _ = || { + let TStruct(_, a) = x; + a + }; + + let _ = *r; +} + +// The same is true for an equivalent enum as well +fn match_singleton(mut x: SSingle) { + let SSingle::A { a: ref mut r, .. } = x; + let _ = || { + let SSingle::A { b, .. } = x; + b + }; + + let _ = *r; +} + +fn match_tuple_singleton(mut x: TSingle) { + let TSingle::A(ref mut r, _) = x; + let _ = || { + let TSingle::A(_, a) = x; + a + }; + + let _ = *r; +} + fn main() {} diff --git a/tests/ui/closures/or-patterns-issue-137467.rs b/tests/ui/closures/or-patterns-issue-137467.rs index 5a1e84e1c9a0..de2a4beeaf9d 100644 --- a/tests/ui/closures/or-patterns-issue-137467.rs +++ b/tests/ui/closures/or-patterns-issue-137467.rs @@ -40,30 +40,6 @@ fn match_unit_variant(x: (Choice, u32, u32)) { }; } -struct Unit; - -fn match_unit_struct(mut x: (Unit, u32)) { - let r = &mut x.0; - let _ = || { - let (Unit, a) = x; - a - }; - - let _ = *r; -} - -enum Also { Unit } - -fn match_unit_enum(mut x: (Also, u32)) { - let r = &mut x.0; - let _ = || { - let (Also::Unit, a) = x; - a - }; - - let _ = *r; -} - enum TEnum { A(u32), B(u32), @@ -99,46 +75,6 @@ enum SSingle { struct TStruct(u32, u32); struct SStruct { a: u32, b: u32 } -fn match_struct(mut x: SStruct) { - let r = &mut x.a; - let _ = || { - let SStruct { b, .. } = x; - b - }; - - let _ = *r; -} - -fn match_tuple_struct(mut x: TStruct) { - let r = &mut x.0; - let _ = || { - let TStruct(_, a) = x; - a - }; - - let _ = *r; -} - -fn match_singleton(mut x: SSingle) { - let SSingle::A { a: ref mut r, .. } = x; - let _ = || { - let SSingle::A { b, .. } = x; - b - }; - - let _ = *r; -} - -fn match_tuple_singleton(mut x: TSingle) { - let TSingle::A(ref mut r, _) = x; - let _ = || { - let TSingle::A(_, a) = x; - a - }; - - let _ = *r; -} - fn match_slice(x: (&[u32], u32, u32)) { let _ = || { let (([], a, _) | ([_, ..], _, a)) = x; From 4e090078b46833b2b71179b7e4382ddbddafc4f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maja=20K=C4=85dzio=C5=82ka?= Date: Thu, 15 Jan 2026 17:24:27 +0100 Subject: [PATCH 046/146] capture-enums.rs: get rid of feature gate noise --- .../2229_closure_analysis/capture-enums.rs | 7 +-- .../capture-enums.stderr | 51 ++++++------------- 2 files changed, 16 insertions(+), 42 deletions(-) diff --git a/tests/ui/closures/2229_closure_analysis/capture-enums.rs b/tests/ui/closures/2229_closure_analysis/capture-enums.rs index 4c600ccdaa43..36b98351854b 100644 --- a/tests/ui/closures/2229_closure_analysis/capture-enums.rs +++ b/tests/ui/closures/2229_closure_analysis/capture-enums.rs @@ -1,6 +1,7 @@ //@ edition:2021 #![feature(rustc_attrs)] +#![feature(stmt_expr_attributes)] enum Info { Point(i32, i32, String), @@ -14,9 +15,6 @@ fn multi_variant_enum() { let meta = Info::Meta("meta".into(), vec); let c = #[rustc_capture_analysis] - //~^ ERROR: attributes on expressions are experimental - //~| NOTE: see issue #15701 - //~| NOTE: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date || { //~^ ERROR First Pass analysis includes: //~| ERROR Min Capture analysis includes: @@ -48,9 +46,6 @@ fn single_variant_enum() { let point = SingleVariant::Point(10, -10, "1".into()); let c = #[rustc_capture_analysis] - //~^ ERROR: attributes on expressions are experimental - //~| NOTE: see issue #15701 - //~| NOTE: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date || { //~^ ERROR First Pass analysis includes: //~| ERROR Min Capture analysis includes: diff --git a/tests/ui/closures/2229_closure_analysis/capture-enums.stderr b/tests/ui/closures/2229_closure_analysis/capture-enums.stderr index b62384ffe12e..2f49c8668f85 100644 --- a/tests/ui/closures/2229_closure_analysis/capture-enums.stderr +++ b/tests/ui/closures/2229_closure_analysis/capture-enums.stderr @@ -1,25 +1,5 @@ -error[E0658]: attributes on expressions are experimental - --> $DIR/capture-enums.rs:16:13 - | -LL | let c = #[rustc_capture_analysis] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #15701 for more information - = help: add `#![feature(stmt_expr_attributes)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: attributes on expressions are experimental - --> $DIR/capture-enums.rs:50:13 - | -LL | let c = #[rustc_capture_analysis] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #15701 for more information - = help: add `#![feature(stmt_expr_attributes)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - error: First Pass analysis includes: - --> $DIR/capture-enums.rs:20:5 + --> $DIR/capture-enums.rs:18:5 | LL | / || { LL | | @@ -30,38 +10,38 @@ LL | | }; | |_____^ | note: Capturing point[] -> Immutable - --> $DIR/capture-enums.rs:23:41 + --> $DIR/capture-enums.rs:21:41 | LL | if let Info::Point(_, _, str) = point { | ^^^^^ note: Capturing point[] -> Immutable - --> $DIR/capture-enums.rs:23:41 + --> $DIR/capture-enums.rs:21:41 | LL | if let Info::Point(_, _, str) = point { | ^^^^^ note: Capturing point[(2, 0)] -> ByValue - --> $DIR/capture-enums.rs:23:41 + --> $DIR/capture-enums.rs:21:41 | LL | if let Info::Point(_, _, str) = point { | ^^^^^ note: Capturing meta[] -> Immutable - --> $DIR/capture-enums.rs:31:35 + --> $DIR/capture-enums.rs:29:35 | LL | if let Info::Meta(_, v) = meta { | ^^^^ note: Capturing meta[] -> Immutable - --> $DIR/capture-enums.rs:31:35 + --> $DIR/capture-enums.rs:29:35 | LL | if let Info::Meta(_, v) = meta { | ^^^^ note: Capturing meta[(1, 1)] -> ByValue - --> $DIR/capture-enums.rs:31:35 + --> $DIR/capture-enums.rs:29:35 | LL | if let Info::Meta(_, v) = meta { | ^^^^ error: Min Capture analysis includes: - --> $DIR/capture-enums.rs:20:5 + --> $DIR/capture-enums.rs:18:5 | LL | / || { LL | | @@ -72,18 +52,18 @@ LL | | }; | |_____^ | note: Min Capture point[] -> ByValue - --> $DIR/capture-enums.rs:23:41 + --> $DIR/capture-enums.rs:21:41 | LL | if let Info::Point(_, _, str) = point { | ^^^^^ note: Min Capture meta[] -> ByValue - --> $DIR/capture-enums.rs:31:35 + --> $DIR/capture-enums.rs:29:35 | LL | if let Info::Meta(_, v) = meta { | ^^^^ error: First Pass analysis includes: - --> $DIR/capture-enums.rs:54:5 + --> $DIR/capture-enums.rs:49:5 | LL | / || { LL | | @@ -95,13 +75,13 @@ LL | | }; | |_____^ | note: Capturing point[(2, 0)] -> ByValue - --> $DIR/capture-enums.rs:57:47 + --> $DIR/capture-enums.rs:52:47 | LL | let SingleVariant::Point(_, _, str) = point; | ^^^^^ error: Min Capture analysis includes: - --> $DIR/capture-enums.rs:54:5 + --> $DIR/capture-enums.rs:49:5 | LL | / || { LL | | @@ -113,11 +93,10 @@ LL | | }; | |_____^ | note: Min Capture point[(2, 0)] -> ByValue - --> $DIR/capture-enums.rs:57:47 + --> $DIR/capture-enums.rs:52:47 | LL | let SingleVariant::Point(_, _, str) = point; | ^^^^^ -error: aborting due to 6 previous errors +error: aborting due to 4 previous errors -For more information about this error, try `rustc --explain E0658`. From 940a48966fd1c4cf8809abcac8d501cf47e4576c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maja=20K=C4=85dzio=C5=82ka?= Date: Thu, 15 Jan 2026 17:30:51 +0100 Subject: [PATCH 047/146] non-exhaustive-match.rs: actually test what the comments say --- .../2229_closure_analysis/match/non-exhaustive-match.rs | 2 ++ .../match/non-exhaustive-match.stderr | 8 ++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/ui/closures/2229_closure_analysis/match/non-exhaustive-match.rs b/tests/ui/closures/2229_closure_analysis/match/non-exhaustive-match.rs index 322555827181..5b7259c6c2cc 100644 --- a/tests/ui/closures/2229_closure_analysis/match/non-exhaustive-match.rs +++ b/tests/ui/closures/2229_closure_analysis/match/non-exhaustive-match.rs @@ -10,6 +10,8 @@ // Ignore non_exhaustive in the same crate #[non_exhaustive] enum L1 { A, B } + +#[non_exhaustive] enum L2 { C } extern crate match_non_exhaustive_lib; diff --git a/tests/ui/closures/2229_closure_analysis/match/non-exhaustive-match.stderr b/tests/ui/closures/2229_closure_analysis/match/non-exhaustive-match.stderr index 85426dd9a5ea..99d33b05429e 100644 --- a/tests/ui/closures/2229_closure_analysis/match/non-exhaustive-match.stderr +++ b/tests/ui/closures/2229_closure_analysis/match/non-exhaustive-match.stderr @@ -1,5 +1,5 @@ error[E0004]: non-exhaustive patterns: `L1::B` not covered - --> $DIR/non-exhaustive-match.rs:26:25 + --> $DIR/non-exhaustive-match.rs:28:25 | LL | let _b = || { match l1 { L1::A => () } }; | ^^ pattern `L1::B` not covered @@ -16,7 +16,7 @@ LL | let _b = || { match l1 { L1::A => (), L1::B => todo!() } }; | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: type `E1` is non-empty - --> $DIR/non-exhaustive-match.rs:37:25 + --> $DIR/non-exhaustive-match.rs:39:25 | LL | let _d = || { match e1 {} }; | ^^ @@ -35,7 +35,7 @@ LL ~ } }; | error[E0004]: non-exhaustive patterns: `_` not covered - --> $DIR/non-exhaustive-match.rs:39:25 + --> $DIR/non-exhaustive-match.rs:41:25 | LL | let _e = || { match e2 { E2::A => (), E2::B => () } }; | ^^ pattern `_` not covered @@ -53,7 +53,7 @@ LL | let _e = || { match e2 { E2::A => (), E2::B => (), _ => todo!() } }; | ++++++++++++++ error[E0505]: cannot move out of `e3` because it is borrowed - --> $DIR/non-exhaustive-match.rs:46:22 + --> $DIR/non-exhaustive-match.rs:48:22 | LL | let _g = || { match e3 { E3::C => (), _ => () } }; | -- -- borrow occurs due to use in closure From a28b279357283aacb9cfb0ecb8321a798738df46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maja=20K=C4=85dzio=C5=82ka?= Date: Wed, 14 Jan 2026 23:47:33 +0100 Subject: [PATCH 048/146] Make some mir-opt tests more resilient --- tests/mir-opt/unreachable.rs | 7 ++++--- tests/mir-opt/unreachable_enum_branching.rs | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/tests/mir-opt/unreachable.rs b/tests/mir-opt/unreachable.rs index f7f4815ae7ce..afab1291fc3d 100644 --- a/tests/mir-opt/unreachable.rs +++ b/tests/mir-opt/unreachable.rs @@ -47,10 +47,11 @@ fn as_match() { // CHECK: bb1: { // CHECK: [[eq:_.*]] = Ne({{.*}}, const 1_isize); // CHECK-NEXT: assume(move [[eq]]); - // CHECK-NEXT: goto -> bb2; - // CHECK: bb2: { + // CHECK-NEXT: goto -> [[return:bb.*]]; + // CHECK: [[return]]: { + // CHECK-NOT: {{bb.*}}: { // CHECK: return; - // CHECK: bb3: { + // CHECK: {{bb.*}}: { // CHECK-NEXT: unreachable; match empty() { Some(_x) => match _x {}, diff --git a/tests/mir-opt/unreachable_enum_branching.rs b/tests/mir-opt/unreachable_enum_branching.rs index 7647f9bf0779..0f6656f4168e 100644 --- a/tests/mir-opt/unreachable_enum_branching.rs +++ b/tests/mir-opt/unreachable_enum_branching.rs @@ -49,7 +49,7 @@ struct Plop { fn simple() { // CHECK-LABEL: fn simple( // CHECK: [[discr:_.*]] = discriminant( - // CHECK: switchInt(move [[discr]]) -> [0: [[unreachable:bb.*]], 1: [[unreachable]], 2: bb1, otherwise: [[unreachable]]]; + // CHECK: switchInt(move [[discr]]) -> [0: [[unreachable:bb.*]], 1: [[unreachable]], 2: {{bb.*}}, otherwise: [[unreachable]]]; // CHECK: [[unreachable]]: { // CHECK-NEXT: unreachable; match Test1::C { @@ -63,7 +63,7 @@ fn simple() { fn custom_discriminant() { // CHECK-LABEL: fn custom_discriminant( // CHECK: [[discr:_.*]] = discriminant( - // CHECK: switchInt(move [[discr]]) -> [4: bb3, 5: bb2, otherwise: [[unreachable:bb.*]]]; + // CHECK: switchInt(move [[discr]]) -> [4: {{bb.*}}, 5: {{bb.*}}, otherwise: [[unreachable:bb.*]]]; // CHECK: [[unreachable]]: { // CHECK-NEXT: unreachable; match Test2::D { @@ -76,7 +76,7 @@ fn custom_discriminant() { fn otherwise_t1() { // CHECK-LABEL: fn otherwise_t1( // CHECK: [[discr:_.*]] = discriminant( - // CHECK: switchInt(move [[discr]]) -> [0: bb5, 1: bb5, 2: bb1, otherwise: [[unreachable:bb.*]]]; + // CHECK: switchInt(move [[discr]]) -> [0: {{bb.*}}, 1: {{bb.*}}, 2: {{bb.*}}, otherwise: [[unreachable:bb.*]]]; // CHECK: [[unreachable]]: { // CHECK-NEXT: unreachable; match Test1::C { @@ -90,7 +90,7 @@ fn otherwise_t1() { fn otherwise_t2() { // CHECK-LABEL: fn otherwise_t2( // CHECK: [[discr:_.*]] = discriminant( - // CHECK: switchInt(move [[discr]]) -> [4: bb2, 5: bb1, otherwise: [[unreachable:bb.*]]]; + // CHECK: switchInt(move [[discr]]) -> [4: {{bb.*}}, 5: {{bb.*}}, otherwise: [[unreachable:bb.*]]]; // CHECK: [[unreachable]]: { // CHECK-NEXT: unreachable; match Test2::D { From d194795f142639a7155ce82422f47fc56c53ed4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 15 Jan 2026 19:32:39 +0000 Subject: [PATCH 049/146] Do not recover from `Trait()` if generic list is unterminated If we encounter `fn foo`), we bail from the recovery as more likely there could have been a missing closing `>` and the `(` corresponds to the start of the fn parameter list. --- compiler/rustc_parse/src/parser/generics.rs | 13 ++++- compiler/rustc_parse/src/parser/mod.rs | 3 ++ compiler/rustc_parse/src/parser/ty.rs | 47 +++++++++++++++++-- .../missing-closing-generics-bracket.fixed | 10 ++++ .../missing-closing-generics-bracket.rs | 10 ++++ .../missing-closing-generics-bracket.stderr | 13 +++++ 6 files changed, 91 insertions(+), 5 deletions(-) create mode 100644 tests/ui/parser/missing-closing-generics-bracket.fixed create mode 100644 tests/ui/parser/missing-closing-generics-bracket.rs create mode 100644 tests/ui/parser/missing-closing-generics-bracket.stderr diff --git a/compiler/rustc_parse/src/parser/generics.rs b/compiler/rustc_parse/src/parser/generics.rs index ef6c9cc344ce..8c02092fd678 100644 --- a/compiler/rustc_parse/src/parser/generics.rs +++ b/compiler/rustc_parse/src/parser/generics.rs @@ -204,9 +204,11 @@ impl<'a> Parser<'a> { pub(super) fn parse_generic_params(&mut self) -> PResult<'a, ThinVec> { let mut params = ThinVec::new(); let mut done = false; + let prev = self.parsing_generics; + self.parsing_generics = true; while !done { let attrs = self.parse_outer_attributes()?; - let param = self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| { + let param = match self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| { if this.eat_keyword_noexpect(kw::SelfUpper) { // `Self` as a generic param is invalid. Here we emit the diagnostic and continue parsing // as if `Self` never existed. @@ -288,7 +290,13 @@ impl<'a> Parser<'a> { } // We just ate the comma, so no need to capture the trailing token. Ok((param, Trailing::No, UsePreAttrPos::No)) - })?; + }) { + Ok(param) => param, + Err(err) => { + self.parsing_generics = prev; + return Err(err); + } + }; if let Some(param) = param { params.push(param); @@ -296,6 +304,7 @@ impl<'a> Parser<'a> { break; } } + self.parsing_generics = prev; Ok(params) } diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index d6e99bc540f7..ca2048d07147 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -212,6 +212,8 @@ pub struct Parser<'a> { /// See the comments in the `parse_path_segment` function for more details. unmatched_angle_bracket_count: u16, angle_bracket_nesting: u16, + /// Keep track of when we're within `<...>` for proper error recovery. + parsing_generics: bool = false, last_unexpected_token_span: Option, /// If present, this `Parser` is not parsing Rust code but rather a macro call. @@ -372,6 +374,7 @@ impl<'a> Parser<'a> { }, current_closure: None, recovery: Recovery::Allowed, + .. }; // Make parser point to the first token. diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 0185c51c5c56..380b6a214846 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -1488,14 +1488,44 @@ impl<'a> Parser<'a> { return Ok(()); } + let snapshot = if self.parsing_generics { + // The snapshot is only relevant if we're parsing the generics of an `fn` to avoid + // incorrect recovery. + Some(self.create_snapshot_for_diagnostic()) + } else { + None + }; // Parse `(T, U) -> R`. let inputs_lo = self.token.span; let mode = FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false }; - let inputs: ThinVec<_> = - self.parse_fn_params(&mode)?.into_iter().map(|input| input.ty).collect(); + let params = match self.parse_fn_params(&mode) { + Ok(params) => params, + Err(err) => { + if let Some(snapshot) = snapshot { + self.restore_snapshot(snapshot); + err.cancel(); + return Ok(()); + } else { + return Err(err); + } + } + }; + let inputs: ThinVec<_> = params.into_iter().map(|input| input.ty).collect(); let inputs_span = inputs_lo.to(self.prev_token.span); - let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?; + let output = match self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No) + { + Ok(output) => output, + Err(err) => { + if let Some(snapshot) = snapshot { + self.restore_snapshot(snapshot); + err.cancel(); + return Ok(()); + } else { + return Err(err); + } + } + }; let args = ast::ParenthesizedArgs { span: fn_path_segment.span().to(self.prev_token.span), inputs, @@ -1503,6 +1533,17 @@ impl<'a> Parser<'a> { output, } .into(); + + if let Some(snapshot) = snapshot + && ![token::Comma, token::Gt, token::Plus].contains(&self.token.kind) + { + // We would expect another bound or the end of type params by now. Most likely we've + // encountered a `(` *not* representing `Trait()`, but rather the start of the `fn`'s + // argument list where the generic param list wasn't properly closed. + self.restore_snapshot(snapshot); + return Ok(()); + } + *fn_path_segment = ast::PathSegment { ident: fn_path_segment.ident, args: Some(args), diff --git a/tests/ui/parser/missing-closing-generics-bracket.fixed b/tests/ui/parser/missing-closing-generics-bracket.fixed new file mode 100644 index 000000000000..3166887fa8c3 --- /dev/null +++ b/tests/ui/parser/missing-closing-generics-bracket.fixed @@ -0,0 +1,10 @@ +// Issue #141436 +//@ run-rustfix +#![allow(dead_code)] + +trait Trait<'a> {} + +fn foo>() {} +//~^ ERROR expected one of + +fn main() {} diff --git a/tests/ui/parser/missing-closing-generics-bracket.rs b/tests/ui/parser/missing-closing-generics-bracket.rs new file mode 100644 index 000000000000..9424e3467246 --- /dev/null +++ b/tests/ui/parser/missing-closing-generics-bracket.rs @@ -0,0 +1,10 @@ +// Issue #141436 +//@ run-rustfix +#![allow(dead_code)] + +trait Trait<'a> {} + +fn foo() {} +//~^ ERROR expected one of + +fn main() {} diff --git a/tests/ui/parser/missing-closing-generics-bracket.stderr b/tests/ui/parser/missing-closing-generics-bracket.stderr new file mode 100644 index 000000000000..c4287301c595 --- /dev/null +++ b/tests/ui/parser/missing-closing-generics-bracket.stderr @@ -0,0 +1,13 @@ +error: expected one of `+`, `,`, `::`, `=`, or `>`, found `(` + --> $DIR/missing-closing-generics-bracket.rs:7:25 + | +LL | fn foo() {} + | ^ expected one of `+`, `,`, `::`, `=`, or `>` + | +help: you might have meant to end the type parameters here + | +LL | fn foo>() {} + | + + +error: aborting due to 1 previous error + From c6c4372f8231bab89007267c23a42e35b177578b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 15 Jan 2026 19:46:54 +0000 Subject: [PATCH 050/146] Use default field values in `Parser` --- compiler/rustc_ast/src/token.rs | 4 +- compiler/rustc_parse/src/parser/mod.rs | 39 +++++++------------ compiler/rustc_parse/src/parser/token_type.rs | 2 +- 3 files changed, 16 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_ast/src/token.rs b/compiler/rustc_ast/src/token.rs index accf4d181632..e0807dbceee4 100644 --- a/compiler/rustc_ast/src/token.rs +++ b/compiler/rustc_ast/src/token.rs @@ -625,12 +625,12 @@ impl TokenKind { } impl Token { - pub fn new(kind: TokenKind, span: Span) -> Self { + pub const fn new(kind: TokenKind, span: Span) -> Self { Token { kind, span } } /// Some token that will be thrown away later. - pub fn dummy() -> Self { + pub const fn dummy() -> Self { Token::new(TokenKind::Question, DUMMY_SP) } diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index ca2048d07147..4145cd5727dc 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -175,17 +175,17 @@ pub enum Recovery { pub struct Parser<'a> { pub psess: &'a ParseSess, /// The current token. - pub token: Token, + pub token: Token = Token::dummy(), /// The spacing for the current token. - token_spacing: Spacing, + token_spacing: Spacing = Spacing::Alone, /// The previous token. - pub prev_token: Token, - pub capture_cfg: bool, - restrictions: Restrictions, - expected_token_types: TokenTypeSet, + pub prev_token: Token = Token::dummy(), + pub capture_cfg: bool = false, + restrictions: Restrictions = Restrictions::empty(), + expected_token_types: TokenTypeSet = TokenTypeSet::new(), token_cursor: TokenCursor, // The number of calls to `bump`, i.e. the position in the token stream. - num_bump_calls: u32, + num_bump_calls: u32 = 0, // During parsing we may sometimes need to "unglue" a glued token into two // or three component tokens (e.g. `>>` into `>` and `>`, or `>>=` into `>` // and `>` and `=`), so the parser can consume them one at a time. This @@ -204,27 +204,27 @@ pub struct Parser<'a> { // // This value is always 0, 1, or 2. It can only reach 2 when splitting // `>>=` or `<<=`. - break_last_token: u32, + break_last_token: u32 = 0, /// This field is used to keep track of how many left angle brackets we have seen. This is /// required in order to detect extra leading left angle brackets (`<` characters) and error /// appropriately. /// /// See the comments in the `parse_path_segment` function for more details. - unmatched_angle_bracket_count: u16, - angle_bracket_nesting: u16, + unmatched_angle_bracket_count: u16 = 0, + angle_bracket_nesting: u16 = 0, /// Keep track of when we're within `<...>` for proper error recovery. parsing_generics: bool = false, - last_unexpected_token_span: Option, + last_unexpected_token_span: Option = None, /// If present, this `Parser` is not parsing Rust code but rather a macro call. subparser_name: Option<&'static str>, capture_state: CaptureState, /// This allows us to recover when the user forget to add braces around /// multiple statements in the closure body. - current_closure: Option, + current_closure: Option = None, /// Whether the parser is allowed to do recovery. /// This is disabled when parsing macro arguments, see #103534 - recovery: Recovery, + recovery: Recovery = Recovery::Allowed, } // This type is used a lot, e.g. it's cloned when matching many declarative macro rules with @@ -353,18 +353,7 @@ impl<'a> Parser<'a> { ) -> Self { let mut parser = Parser { psess, - token: Token::dummy(), - token_spacing: Spacing::Alone, - prev_token: Token::dummy(), - capture_cfg: false, - restrictions: Restrictions::empty(), - expected_token_types: TokenTypeSet::new(), token_cursor: TokenCursor { curr: TokenTreeCursor::new(stream), stack: Vec::new() }, - num_bump_calls: 0, - break_last_token: 0, - unmatched_angle_bracket_count: 0, - angle_bracket_nesting: 0, - last_unexpected_token_span: None, subparser_name, capture_state: CaptureState { capturing: Capturing::No, @@ -372,8 +361,6 @@ impl<'a> Parser<'a> { inner_attr_parser_ranges: Default::default(), seen_attrs: IntervalSet::new(u32::MAX as usize), }, - current_closure: None, - recovery: Recovery::Allowed, .. }; diff --git a/compiler/rustc_parse/src/parser/token_type.rs b/compiler/rustc_parse/src/parser/token_type.rs index e5dda7cf9104..567b1be5e5d9 100644 --- a/compiler/rustc_parse/src/parser/token_type.rs +++ b/compiler/rustc_parse/src/parser/token_type.rs @@ -585,7 +585,7 @@ macro_rules! exp { pub(super) struct TokenTypeSet(u128); impl TokenTypeSet { - pub(super) fn new() -> TokenTypeSet { + pub(super) const fn new() -> TokenTypeSet { TokenTypeSet(0) } From 9750d22c17092fa747e088ae24bb749077edefa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 13 Jan 2026 21:13:48 +0000 Subject: [PATCH 051/146] Silence unused type param and inference errors on struct parse error --- compiler/rustc_hir/src/hir.rs | 20 +++++++++++++++ .../rustc_hir_analysis/src/check/wfcheck.rs | 7 +++++- .../error_reporting/infer/need_type_info.rs | 25 ++++++++++++++++++- .../structs/parse-error-with-type-param.fixed | 14 +++++++++++ .../ui/structs/parse-error-with-type-param.rs | 14 +++++++++++ .../parse-error-with-type-param.stderr | 18 +++++++++++++ 6 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 tests/ui/structs/parse-error-with-type-param.fixed create mode 100644 tests/ui/structs/parse-error-with-type-param.rs create mode 100644 tests/ui/structs/parse-error-with-type-param.stderr diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index dac4c7e3965a..b296522749f0 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -4525,6 +4525,26 @@ impl ItemKind<'_> { _ => return None, }) } + + pub fn recovered(&self) -> bool { + match self { + ItemKind::Struct( + _, + _, + VariantData::Struct { recovered: ast::Recovered::Yes(_), .. }, + ) => true, + ItemKind::Union( + _, + _, + VariantData::Struct { recovered: ast::Recovered::Yes(_), .. }, + ) => true, + ItemKind::Enum(_, _, def) => def.variants.iter().any(|v| match v.data { + VariantData::Struct { recovered: ast::Recovered::Yes(_), .. } => true, + _ => false, + }), + _ => false, + } + } } // The bodies for items are stored "out of line", in a separate diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index cfc7e57cc14e..8b50eceb26e4 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -2160,7 +2160,12 @@ fn report_bivariance<'tcx>( const_param_help, }); diag.code(E0392); - diag.emit() + if item.kind.recovered() { + // Silence potentially redundant error, as the item had a parse error. + diag.delay_as_bug() + } else { + diag.emit() + } } /// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index 0a2442b71e78..e3c8bfe4a452 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -488,7 +488,30 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } let Some(InferSource { span, kind }) = local_visitor.infer_source else { - return self.bad_inference_failure_err(failure_span, arg_data, error_code); + let silence = if let DefKind::AssocFn = self.tcx.def_kind(body_def_id) + && let parent = self.tcx.parent(body_def_id.into()) + && self.tcx.is_automatically_derived(parent) + && let Some(parent) = parent.as_local() + && let hir::Node::Item(item) = self.tcx.hir_node_by_def_id(parent) + && let hir::ItemKind::Impl(imp) = item.kind + && let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = imp.self_ty.kind + && let Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, def_id) = path.res + && let Some(def_id) = def_id.as_local() + && let hir::Node::Item(item) = self.tcx.hir_node_by_def_id(def_id) + { + // We have encountered an inference error within an automatically derived `impl`, + // from a `#[derive(..)]` on an item that had a parse error. Because the parse + // error might have caused the expanded code to be malformed, we silence the + // inference error. + item.kind.recovered() + } else { + false + }; + let mut err = self.bad_inference_failure_err(failure_span, arg_data, error_code); + if silence { + err.downgrade_to_delayed_bug(); + } + return err; }; let (source_kind, name, long_ty_path) = kind.ty_localized_msg(self); diff --git a/tests/ui/structs/parse-error-with-type-param.fixed b/tests/ui/structs/parse-error-with-type-param.fixed new file mode 100644 index 000000000000..46d1c2722843 --- /dev/null +++ b/tests/ui/structs/parse-error-with-type-param.fixed @@ -0,0 +1,14 @@ +//@ run-rustfix +// #141403 +#![allow(dead_code)] + +#[derive(Clone)] +struct B { + a: A<(T, u32)>, // <- note, comma is missing here + /// asdf + //~^ ERROR found a documentation comment that doesn't document anything + b: u32, +} +#[derive(Clone)] +struct A(T); +fn main() {} diff --git a/tests/ui/structs/parse-error-with-type-param.rs b/tests/ui/structs/parse-error-with-type-param.rs new file mode 100644 index 000000000000..27a9fc854f57 --- /dev/null +++ b/tests/ui/structs/parse-error-with-type-param.rs @@ -0,0 +1,14 @@ +//@ run-rustfix +// #141403 +#![allow(dead_code)] + +#[derive(Clone)] +struct B { + a: A<(T, u32)> // <- note, comma is missing here + /// asdf + //~^ ERROR found a documentation comment that doesn't document anything + b: u32, +} +#[derive(Clone)] +struct A(T); +fn main() {} diff --git a/tests/ui/structs/parse-error-with-type-param.stderr b/tests/ui/structs/parse-error-with-type-param.stderr new file mode 100644 index 000000000000..d01eae193b14 --- /dev/null +++ b/tests/ui/structs/parse-error-with-type-param.stderr @@ -0,0 +1,18 @@ +error[E0585]: found a documentation comment that doesn't document anything + --> $DIR/parse-error-with-type-param.rs:8:5 + | +LL | struct B { + | - while parsing this struct +LL | a: A<(T, u32)> // <- note, comma is missing here +LL | /// asdf + | ^^^^^^^^ + | + = help: doc comments must come before what they document, if a comment was intended use `//` +help: missing comma here + | +LL | a: A<(T, u32)>, // <- note, comma is missing here + | + + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0585`. From 559e67248921197206f009792560fa2861dd1750 Mon Sep 17 00:00:00 2001 From: reddevilmidzy Date: Thu, 15 Jan 2026 15:41:27 +0900 Subject: [PATCH 052/146] move some tests --- .../issue-50600.rs => array-slice-vec/closure-in-array-len.rs} | 0 .../closure-in-array-len.stderr} | 0 .../issue-51714.rs => array-slice-vec/return-in-array-len.rs} | 0 .../return-in-array-len.stderr} | 0 .../issue-17503.rs => array-slice-vec/slice-of-multi-ref.rs} | 0 .../issue-42453.rs => derives/derive-hygiene-struct-builder.rs} | 0 tests/ui/{issues/issue-17361.rs => dst/unsized-str-mutability.rs} | 0 .../issue-28105.rs => for-loop-while/break-outside-loop-2.rs} | 0 .../break-outside-loop-2.stderr} | 0 .../issue-22706.rs => generics/type-args-on-module-in-bound.rs} | 0 .../type-args-on-module-in-bound.stderr} | 0 .../ui/{issues/issue-28109.rs => label/undeclared-label-span.rs} | 0 .../issue-28109.stderr => label/undeclared-label-span.stderr} | 0 .../{issues/issue-43057.rs => macros/column-macro-collision.rs} | 0 .../array-repeat-unit-struct.rs} | 0 .../array-repeat-unit-struct.stderr} | 0 .../vec-hashset-type-mismatch.rs} | 0 .../vec-hashset-type-mismatch.stderr} | 0 .../issue-16725.rs => privacy/auxiliary/private-extern-fn.rs} | 0 tests/ui/{issues/issue-28433.rs => privacy/privacy-sanity-2.rs} | 0 .../issue-28433.stderr => privacy/privacy-sanity-2.stderr} | 0 .../issue-16725.rs => privacy/private-extern-fn-visibility.rs} | 0 .../private-extern-fn-visibility.stderr} | 0 .../ui/{issues/issue-22894.rs => static/static-str-deref-ref.rs} | 0 .../std-sync-right-kind-impls-2.rs} | 0 25 files changed, 0 insertions(+), 0 deletions(-) rename tests/ui/{issues/issue-50600.rs => array-slice-vec/closure-in-array-len.rs} (100%) rename tests/ui/{issues/issue-50600.stderr => array-slice-vec/closure-in-array-len.stderr} (100%) rename tests/ui/{issues/issue-51714.rs => array-slice-vec/return-in-array-len.rs} (100%) rename tests/ui/{issues/issue-51714.stderr => array-slice-vec/return-in-array-len.stderr} (100%) rename tests/ui/{issues/issue-17503.rs => array-slice-vec/slice-of-multi-ref.rs} (100%) rename tests/ui/{issues/issue-42453.rs => derives/derive-hygiene-struct-builder.rs} (100%) rename tests/ui/{issues/issue-17361.rs => dst/unsized-str-mutability.rs} (100%) rename tests/ui/{issues/issue-28105.rs => for-loop-while/break-outside-loop-2.rs} (100%) rename tests/ui/{issues/issue-28105.stderr => for-loop-while/break-outside-loop-2.stderr} (100%) rename tests/ui/{issues/issue-22706.rs => generics/type-args-on-module-in-bound.rs} (100%) rename tests/ui/{issues/issue-22706.stderr => generics/type-args-on-module-in-bound.stderr} (100%) rename tests/ui/{issues/issue-28109.rs => label/undeclared-label-span.rs} (100%) rename tests/ui/{issues/issue-28109.stderr => label/undeclared-label-span.stderr} (100%) rename tests/ui/{issues/issue-43057.rs => macros/column-macro-collision.rs} (100%) rename tests/ui/{issues/issue-27008.rs => mismatched_types/array-repeat-unit-struct.rs} (100%) rename tests/ui/{issues/issue-27008.stderr => mismatched_types/array-repeat-unit-struct.stderr} (100%) rename tests/ui/{issues/issue-24819.rs => mismatched_types/vec-hashset-type-mismatch.rs} (100%) rename tests/ui/{issues/issue-24819.stderr => mismatched_types/vec-hashset-type-mismatch.stderr} (100%) rename tests/ui/{issues/auxiliary/issue-16725.rs => privacy/auxiliary/private-extern-fn.rs} (100%) rename tests/ui/{issues/issue-28433.rs => privacy/privacy-sanity-2.rs} (100%) rename tests/ui/{issues/issue-28433.stderr => privacy/privacy-sanity-2.stderr} (100%) rename tests/ui/{issues/issue-16725.rs => privacy/private-extern-fn-visibility.rs} (100%) rename tests/ui/{issues/issue-16725.stderr => privacy/private-extern-fn-visibility.stderr} (100%) rename tests/ui/{issues/issue-22894.rs => static/static-str-deref-ref.rs} (100%) rename tests/ui/{issues/issue-22577.rs => threads-sendsync/std-sync-right-kind-impls-2.rs} (100%) diff --git a/tests/ui/issues/issue-50600.rs b/tests/ui/array-slice-vec/closure-in-array-len.rs similarity index 100% rename from tests/ui/issues/issue-50600.rs rename to tests/ui/array-slice-vec/closure-in-array-len.rs diff --git a/tests/ui/issues/issue-50600.stderr b/tests/ui/array-slice-vec/closure-in-array-len.stderr similarity index 100% rename from tests/ui/issues/issue-50600.stderr rename to tests/ui/array-slice-vec/closure-in-array-len.stderr diff --git a/tests/ui/issues/issue-51714.rs b/tests/ui/array-slice-vec/return-in-array-len.rs similarity index 100% rename from tests/ui/issues/issue-51714.rs rename to tests/ui/array-slice-vec/return-in-array-len.rs diff --git a/tests/ui/issues/issue-51714.stderr b/tests/ui/array-slice-vec/return-in-array-len.stderr similarity index 100% rename from tests/ui/issues/issue-51714.stderr rename to tests/ui/array-slice-vec/return-in-array-len.stderr diff --git a/tests/ui/issues/issue-17503.rs b/tests/ui/array-slice-vec/slice-of-multi-ref.rs similarity index 100% rename from tests/ui/issues/issue-17503.rs rename to tests/ui/array-slice-vec/slice-of-multi-ref.rs diff --git a/tests/ui/issues/issue-42453.rs b/tests/ui/derives/derive-hygiene-struct-builder.rs similarity index 100% rename from tests/ui/issues/issue-42453.rs rename to tests/ui/derives/derive-hygiene-struct-builder.rs diff --git a/tests/ui/issues/issue-17361.rs b/tests/ui/dst/unsized-str-mutability.rs similarity index 100% rename from tests/ui/issues/issue-17361.rs rename to tests/ui/dst/unsized-str-mutability.rs diff --git a/tests/ui/issues/issue-28105.rs b/tests/ui/for-loop-while/break-outside-loop-2.rs similarity index 100% rename from tests/ui/issues/issue-28105.rs rename to tests/ui/for-loop-while/break-outside-loop-2.rs diff --git a/tests/ui/issues/issue-28105.stderr b/tests/ui/for-loop-while/break-outside-loop-2.stderr similarity index 100% rename from tests/ui/issues/issue-28105.stderr rename to tests/ui/for-loop-while/break-outside-loop-2.stderr diff --git a/tests/ui/issues/issue-22706.rs b/tests/ui/generics/type-args-on-module-in-bound.rs similarity index 100% rename from tests/ui/issues/issue-22706.rs rename to tests/ui/generics/type-args-on-module-in-bound.rs diff --git a/tests/ui/issues/issue-22706.stderr b/tests/ui/generics/type-args-on-module-in-bound.stderr similarity index 100% rename from tests/ui/issues/issue-22706.stderr rename to tests/ui/generics/type-args-on-module-in-bound.stderr diff --git a/tests/ui/issues/issue-28109.rs b/tests/ui/label/undeclared-label-span.rs similarity index 100% rename from tests/ui/issues/issue-28109.rs rename to tests/ui/label/undeclared-label-span.rs diff --git a/tests/ui/issues/issue-28109.stderr b/tests/ui/label/undeclared-label-span.stderr similarity index 100% rename from tests/ui/issues/issue-28109.stderr rename to tests/ui/label/undeclared-label-span.stderr diff --git a/tests/ui/issues/issue-43057.rs b/tests/ui/macros/column-macro-collision.rs similarity index 100% rename from tests/ui/issues/issue-43057.rs rename to tests/ui/macros/column-macro-collision.rs diff --git a/tests/ui/issues/issue-27008.rs b/tests/ui/mismatched_types/array-repeat-unit-struct.rs similarity index 100% rename from tests/ui/issues/issue-27008.rs rename to tests/ui/mismatched_types/array-repeat-unit-struct.rs diff --git a/tests/ui/issues/issue-27008.stderr b/tests/ui/mismatched_types/array-repeat-unit-struct.stderr similarity index 100% rename from tests/ui/issues/issue-27008.stderr rename to tests/ui/mismatched_types/array-repeat-unit-struct.stderr diff --git a/tests/ui/issues/issue-24819.rs b/tests/ui/mismatched_types/vec-hashset-type-mismatch.rs similarity index 100% rename from tests/ui/issues/issue-24819.rs rename to tests/ui/mismatched_types/vec-hashset-type-mismatch.rs diff --git a/tests/ui/issues/issue-24819.stderr b/tests/ui/mismatched_types/vec-hashset-type-mismatch.stderr similarity index 100% rename from tests/ui/issues/issue-24819.stderr rename to tests/ui/mismatched_types/vec-hashset-type-mismatch.stderr diff --git a/tests/ui/issues/auxiliary/issue-16725.rs b/tests/ui/privacy/auxiliary/private-extern-fn.rs similarity index 100% rename from tests/ui/issues/auxiliary/issue-16725.rs rename to tests/ui/privacy/auxiliary/private-extern-fn.rs diff --git a/tests/ui/issues/issue-28433.rs b/tests/ui/privacy/privacy-sanity-2.rs similarity index 100% rename from tests/ui/issues/issue-28433.rs rename to tests/ui/privacy/privacy-sanity-2.rs diff --git a/tests/ui/issues/issue-28433.stderr b/tests/ui/privacy/privacy-sanity-2.stderr similarity index 100% rename from tests/ui/issues/issue-28433.stderr rename to tests/ui/privacy/privacy-sanity-2.stderr diff --git a/tests/ui/issues/issue-16725.rs b/tests/ui/privacy/private-extern-fn-visibility.rs similarity index 100% rename from tests/ui/issues/issue-16725.rs rename to tests/ui/privacy/private-extern-fn-visibility.rs diff --git a/tests/ui/issues/issue-16725.stderr b/tests/ui/privacy/private-extern-fn-visibility.stderr similarity index 100% rename from tests/ui/issues/issue-16725.stderr rename to tests/ui/privacy/private-extern-fn-visibility.stderr diff --git a/tests/ui/issues/issue-22894.rs b/tests/ui/static/static-str-deref-ref.rs similarity index 100% rename from tests/ui/issues/issue-22894.rs rename to tests/ui/static/static-str-deref-ref.rs diff --git a/tests/ui/issues/issue-22577.rs b/tests/ui/threads-sendsync/std-sync-right-kind-impls-2.rs similarity index 100% rename from tests/ui/issues/issue-22577.rs rename to tests/ui/threads-sendsync/std-sync-right-kind-impls-2.rs From 77b2a196fb13a1b4c6751c9361dad7d55a0e7d9d Mon Sep 17 00:00:00 2001 From: reddevilmidzy Date: Thu, 15 Jan 2026 18:34:54 +0900 Subject: [PATCH 053/146] cleaned up some tests merge privacy/privacy-sanity-2 with privacy/privacy-sanity.rs Add comment to generics/type-args-on-module-in-bound.rs Add comment to array-slice-vec/closure-in-array-eln.rs Add comment to array-slice-vec/return-in-array-len.rs Merge for-loop-while/break-outside-loop-2.rs with for-loop-while/break-outside-loop.rs Add comment to macros/column-macro-collision.rs Add comment to privacy/private-extern-fn-visibility.rs Add comment to mismatched_types/vec-hashset-type-mismatch.rs Merge std-sync-right-kind-impls-2.rs with std-sync-right-kind-impls.rs Add comment to array-slice-vec/slice-of-multi-ref.rs Add comment to mismatched_types\vec-hashset-type-mismatch.rs Add comment to derives/derive-hygiene-struct-builder.rs Add comment to label/undeclared-label-span.rs Add comment to label\undeclared-label-span.rs Add comment to mismatched_types/array-repeat-unit-struct.rs --- .../array-slice-vec/closure-in-array-len.rs | 3 +- .../closure-in-array-len.stderr | 4 +- .../ui/array-slice-vec/return-in-array-len.rs | 1 + .../return-in-array-len.stderr | 8 +-- .../ui/array-slice-vec/slice-of-multi-ref.rs | 1 + .../derives/derive-hygiene-struct-builder.rs | 6 +- tests/ui/dst/unsized-str-mutability.rs | 4 +- .../ui/for-loop-while/break-outside-loop-2.rs | 8 --- .../break-outside-loop-2.stderr | 15 ----- tests/ui/for-loop-while/break-outside-loop.rs | 40 ++++++++++--- .../for-loop-while/break-outside-loop.stderr | 43 +++++++++----- .../generics/type-args-on-module-in-bound.rs | 1 + .../type-args-on-module-in-bound.stderr | 2 +- tests/ui/label/undeclared-label-span.rs | 3 +- tests/ui/label/undeclared-label-span.stderr | 4 +- tests/ui/macros/column-macro-collision.rs | 3 + .../array-repeat-unit-struct.rs | 2 + .../array-repeat-unit-struct.stderr | 2 +- .../vec-hashset-type-mismatch.rs | 4 +- .../vec-hashset-type-mismatch.stderr | 6 +- tests/ui/privacy/privacy-sanity-2.rs | 12 ---- tests/ui/privacy/privacy-sanity-2.stderr | 19 ------ tests/ui/privacy/privacy-sanity.rs | 15 +++++ tests/ui/privacy/privacy-sanity.stderr | 58 ++++++++++++++----- .../privacy/private-extern-fn-visibility.rs | 11 ++-- .../private-extern-fn-visibility.stderr | 8 +-- tests/ui/static/static-str-deref-ref.rs | 1 + .../std-sync-right-kind-impls-2.rs | 25 -------- .../std-sync-right-kind-impls.rs | 18 +++++- 29 files changed, 180 insertions(+), 147 deletions(-) delete mode 100644 tests/ui/for-loop-while/break-outside-loop-2.rs delete mode 100644 tests/ui/for-loop-while/break-outside-loop-2.stderr delete mode 100644 tests/ui/privacy/privacy-sanity-2.rs delete mode 100644 tests/ui/privacy/privacy-sanity-2.stderr delete mode 100644 tests/ui/threads-sendsync/std-sync-right-kind-impls-2.rs diff --git a/tests/ui/array-slice-vec/closure-in-array-len.rs b/tests/ui/array-slice-vec/closure-in-array-len.rs index 963e607afcfd..ce13e0f16081 100644 --- a/tests/ui/array-slice-vec/closure-in-array-len.rs +++ b/tests/ui/array-slice-vec/closure-in-array-len.rs @@ -1,4 +1,5 @@ -struct Foo ( +//! regression test for +struct Foo( fn([u8; |x: u8| {}]), //~ ERROR mismatched types ); diff --git a/tests/ui/array-slice-vec/closure-in-array-len.stderr b/tests/ui/array-slice-vec/closure-in-array-len.stderr index e3ae7f144c35..decdde042c6f 100644 --- a/tests/ui/array-slice-vec/closure-in-array-len.stderr +++ b/tests/ui/array-slice-vec/closure-in-array-len.stderr @@ -1,11 +1,11 @@ error[E0308]: mismatched types - --> $DIR/issue-50600.rs:2:13 + --> $DIR/closure-in-array-len.rs:3:13 | LL | fn([u8; |x: u8| {}]), | ^^^^^^^^^^ expected `usize`, found closure | = note: expected type `usize` - found closure `{closure@$DIR/issue-50600.rs:2:13: 2:20}` + found closure `{closure@$DIR/closure-in-array-len.rs:3:13: 3:20}` error: aborting due to 1 previous error diff --git a/tests/ui/array-slice-vec/return-in-array-len.rs b/tests/ui/array-slice-vec/return-in-array-len.rs index 03b50b7963ea..dea1bb2818bb 100644 --- a/tests/ui/array-slice-vec/return-in-array-len.rs +++ b/tests/ui/array-slice-vec/return-in-array-len.rs @@ -1,3 +1,4 @@ +//! regression test for fn main() { //~^ NOTE: not the enclosing function body //~| NOTE: not the enclosing function body diff --git a/tests/ui/array-slice-vec/return-in-array-len.stderr b/tests/ui/array-slice-vec/return-in-array-len.stderr index da3e3caea29a..974a748edc93 100644 --- a/tests/ui/array-slice-vec/return-in-array-len.stderr +++ b/tests/ui/array-slice-vec/return-in-array-len.stderr @@ -1,5 +1,5 @@ error[E0572]: return statement outside of function body - --> $DIR/issue-51714.rs:6:13 + --> $DIR/return-in-array-len.rs:7:13 | LL | / fn main() { ... | @@ -10,7 +10,7 @@ LL | | } | |_- ...not the enclosing function body error[E0572]: return statement outside of function body - --> $DIR/issue-51714.rs:10:10 + --> $DIR/return-in-array-len.rs:11:10 | LL | / fn main() { ... | @@ -21,7 +21,7 @@ LL | | } | |_- ...not the enclosing function body error[E0572]: return statement outside of function body - --> $DIR/issue-51714.rs:14:10 + --> $DIR/return-in-array-len.rs:15:10 | LL | / fn main() { ... | @@ -32,7 +32,7 @@ LL | | } | |_- ...not the enclosing function body error[E0572]: return statement outside of function body - --> $DIR/issue-51714.rs:18:10 + --> $DIR/return-in-array-len.rs:19:10 | LL | / fn main() { ... | diff --git a/tests/ui/array-slice-vec/slice-of-multi-ref.rs b/tests/ui/array-slice-vec/slice-of-multi-ref.rs index 6c966b5319cd..b4917f594d83 100644 --- a/tests/ui/array-slice-vec/slice-of-multi-ref.rs +++ b/tests/ui/array-slice-vec/slice-of-multi-ref.rs @@ -1,3 +1,4 @@ +//! regression test for //@ run-pass fn main() { let s: &[isize] = &[0, 1, 2, 3, 4]; diff --git a/tests/ui/derives/derive-hygiene-struct-builder.rs b/tests/ui/derives/derive-hygiene-struct-builder.rs index 9ed9080e8a92..95245a3b3f5a 100644 --- a/tests/ui/derives/derive-hygiene-struct-builder.rs +++ b/tests/ui/derives/derive-hygiene-struct-builder.rs @@ -1,3 +1,5 @@ +//! regression test for +//! struct named "builder" conflicted with derive macro internals. //@ run-pass #![allow(dead_code)] #![allow(non_camel_case_types)] @@ -5,6 +7,4 @@ #[derive(Debug)] struct builder; -fn main() { - -} +fn main() {} diff --git a/tests/ui/dst/unsized-str-mutability.rs b/tests/ui/dst/unsized-str-mutability.rs index 6f6fc42db383..d84fa001fd67 100644 --- a/tests/ui/dst/unsized-str-mutability.rs +++ b/tests/ui/dst/unsized-str-mutability.rs @@ -1,6 +1,6 @@ +//! regression test for +//! Test that HIR ty lowering doesn't forget about mutability of `&mut str`. //@ run-pass -// Test that HIR ty lowering doesn't forget about mutability of `&mut str`. - fn main() { fn foo(_: &mut T) {} diff --git a/tests/ui/for-loop-while/break-outside-loop-2.rs b/tests/ui/for-loop-while/break-outside-loop-2.rs deleted file mode 100644 index 1e8d2d6ccf13..000000000000 --- a/tests/ui/for-loop-while/break-outside-loop-2.rs +++ /dev/null @@ -1,8 +0,0 @@ -// Make sure that a continue span actually contains the keyword. - -fn main() { - continue //~ ERROR `continue` outside of a loop - ; - break //~ ERROR `break` outside of a loop - ; -} diff --git a/tests/ui/for-loop-while/break-outside-loop-2.stderr b/tests/ui/for-loop-while/break-outside-loop-2.stderr deleted file mode 100644 index f450256f3ecf..000000000000 --- a/tests/ui/for-loop-while/break-outside-loop-2.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error[E0268]: `continue` outside of a loop - --> $DIR/issue-28105.rs:4:5 - | -LL | continue - | ^^^^^^^^ cannot `continue` outside of a loop - -error[E0268]: `break` outside of a loop or labeled block - --> $DIR/issue-28105.rs:6:5 - | -LL | break - | ^^^^^ cannot `break` outside of a loop or labeled block - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0268`. diff --git a/tests/ui/for-loop-while/break-outside-loop.rs b/tests/ui/for-loop-while/break-outside-loop.rs index 26769b30dd5f..06c513aa8457 100644 --- a/tests/ui/for-loop-while/break-outside-loop.rs +++ b/tests/ui/for-loop-while/break-outside-loop.rs @@ -1,25 +1,41 @@ struct Foo { - t: String + t: String, } -fn cond() -> bool { true } +fn cond() -> bool { + true +} -fn foo(_: F) where F: FnOnce() {} +fn foo(_: F) +where + F: FnOnce(), +{ +} fn main() { let pth = break; //~ ERROR: `break` outside of a loop - if cond() { continue } //~ ERROR: `continue` outside of a loop + if cond() { + continue; //~ ERROR: `continue` outside of a loop + } while cond() { - if cond() { break } - if cond() { continue } + if cond() { + break; + } + if cond() { + continue; + } foo(|| { - if cond() { break } //~ ERROR: `break` inside of a closure - if cond() { continue } //~ ERROR: `continue` inside of a closure + if cond() { + break; //~ ERROR: `break` inside of a closure + } + if cond() { + continue; //~ ERROR: `continue` inside of a closure + } }) } - let rs: Foo = Foo{t: pth}; + let rs: Foo = Foo { t: pth }; let unconstrained = break; //~ ERROR: `break` outside of a loop @@ -32,4 +48,10 @@ fn main() { //~| ERROR `break` inside of a closure }; } + + // Make sure that a continue span actually contains the keyword. (#28105) + continue //~ ERROR `continue` outside of a loop + ; + break //~ ERROR `break` outside of a loop + ; } diff --git a/tests/ui/for-loop-while/break-outside-loop.stderr b/tests/ui/for-loop-while/break-outside-loop.stderr index 9092f34df354..7dbff2d41245 100644 --- a/tests/ui/for-loop-while/break-outside-loop.stderr +++ b/tests/ui/for-loop-while/break-outside-loop.stderr @@ -1,5 +1,5 @@ error[E0767]: use of unreachable label `'lab` - --> $DIR/break-outside-loop.rs:30:19 + --> $DIR/break-outside-loop.rs:46:19 | LL | 'lab: loop { | ---- unreachable label defined here @@ -10,49 +10,62 @@ LL | break 'lab; = note: labels are unreachable through functions, closures, async blocks and modules error[E0268]: `break` outside of a loop or labeled block - --> $DIR/break-outside-loop.rs:10:15 + --> $DIR/break-outside-loop.rs:16:15 | LL | let pth = break; | ^^^^^ cannot `break` outside of a loop or labeled block error[E0268]: `continue` outside of a loop - --> $DIR/break-outside-loop.rs:11:17 + --> $DIR/break-outside-loop.rs:18:9 | -LL | if cond() { continue } - | ^^^^^^^^ cannot `continue` outside of a loop +LL | continue; + | ^^^^^^^^ cannot `continue` outside of a loop error[E0267]: `break` inside of a closure - --> $DIR/break-outside-loop.rs:17:25 + --> $DIR/break-outside-loop.rs:30:17 | LL | foo(|| { | -- enclosing closure -LL | if cond() { break } - | ^^^^^ cannot `break` inside of a closure +LL | if cond() { +LL | break; + | ^^^^^ cannot `break` inside of a closure error[E0267]: `continue` inside of a closure - --> $DIR/break-outside-loop.rs:18:25 + --> $DIR/break-outside-loop.rs:33:17 | LL | foo(|| { | -- enclosing closure -LL | if cond() { break } -LL | if cond() { continue } - | ^^^^^^^^ cannot `continue` inside of a closure +... +LL | continue; + | ^^^^^^^^ cannot `continue` inside of a closure error[E0268]: `break` outside of a loop or labeled block - --> $DIR/break-outside-loop.rs:24:25 + --> $DIR/break-outside-loop.rs:40:25 | LL | let unconstrained = break; | ^^^^^ cannot `break` outside of a loop or labeled block error[E0267]: `break` inside of a closure - --> $DIR/break-outside-loop.rs:30:13 + --> $DIR/break-outside-loop.rs:46:13 | LL | || { | -- enclosing closure LL | break 'lab; | ^^^^^^^^^^ cannot `break` inside of a closure -error: aborting due to 7 previous errors +error[E0268]: `continue` outside of a loop + --> $DIR/break-outside-loop.rs:53:5 + | +LL | continue + | ^^^^^^^^ cannot `continue` outside of a loop + +error[E0268]: `break` outside of a loop or labeled block + --> $DIR/break-outside-loop.rs:55:5 + | +LL | break + | ^^^^^ cannot `break` outside of a loop or labeled block + +error: aborting due to 9 previous errors Some errors have detailed explanations: E0267, E0268, E0767. For more information about an error, try `rustc --explain E0267`. diff --git a/tests/ui/generics/type-args-on-module-in-bound.rs b/tests/ui/generics/type-args-on-module-in-bound.rs index bb8a58d3d2ec..96ca37407cfc 100644 --- a/tests/ui/generics/type-args-on-module-in-bound.rs +++ b/tests/ui/generics/type-args-on-module-in-bound.rs @@ -1,3 +1,4 @@ +//! regression test for fn is_copy::Copy>() {} //~^ ERROR type arguments are not allowed on module `marker` [E0109] fn main() {} diff --git a/tests/ui/generics/type-args-on-module-in-bound.stderr b/tests/ui/generics/type-args-on-module-in-bound.stderr index 309e11a25f1a..ac70ae63e90b 100644 --- a/tests/ui/generics/type-args-on-module-in-bound.stderr +++ b/tests/ui/generics/type-args-on-module-in-bound.stderr @@ -1,5 +1,5 @@ error[E0109]: type arguments are not allowed on module `marker` - --> $DIR/issue-22706.rs:1:29 + --> $DIR/type-args-on-module-in-bound.rs:2:29 | LL | fn is_copy::Copy>() {} | ------ ^^^ type argument not allowed diff --git a/tests/ui/label/undeclared-label-span.rs b/tests/ui/label/undeclared-label-span.rs index 755a539b5003..c6f38c067192 100644 --- a/tests/ui/label/undeclared-label-span.rs +++ b/tests/ui/label/undeclared-label-span.rs @@ -1,4 +1,5 @@ -// Make sure that label for continue and break is spanned correctly +//! regression test for +//! Make sure that label for continue and break is spanned correctly. fn main() { loop { diff --git a/tests/ui/label/undeclared-label-span.stderr b/tests/ui/label/undeclared-label-span.stderr index 0f918d3b6f70..e5451b4655d8 100644 --- a/tests/ui/label/undeclared-label-span.stderr +++ b/tests/ui/label/undeclared-label-span.stderr @@ -1,11 +1,11 @@ error[E0426]: use of undeclared label `'b` - --> $DIR/issue-28109.rs:6:9 + --> $DIR/undeclared-label-span.rs:7:9 | LL | 'b | ^^ undeclared label `'b` error[E0426]: use of undeclared label `'c` - --> $DIR/issue-28109.rs:9:9 + --> $DIR/undeclared-label-span.rs:10:9 | LL | 'c | ^^ undeclared label `'c` diff --git a/tests/ui/macros/column-macro-collision.rs b/tests/ui/macros/column-macro-collision.rs index 4dd1fe461f1b..7acf491888af 100644 --- a/tests/ui/macros/column-macro-collision.rs +++ b/tests/ui/macros/column-macro-collision.rs @@ -1,3 +1,6 @@ +//! regression test for +//! user-defined `column!` macro must not shadow +//! the built-in `column!()` used internally by `panic!()`. //@ check-pass #![allow(unused)] diff --git a/tests/ui/mismatched_types/array-repeat-unit-struct.rs b/tests/ui/mismatched_types/array-repeat-unit-struct.rs index 20aa4f282c7e..db05e1daedbd 100644 --- a/tests/ui/mismatched_types/array-repeat-unit-struct.rs +++ b/tests/ui/mismatched_types/array-repeat-unit-struct.rs @@ -1,3 +1,5 @@ +//! regression test for + struct S; fn main() { diff --git a/tests/ui/mismatched_types/array-repeat-unit-struct.stderr b/tests/ui/mismatched_types/array-repeat-unit-struct.stderr index b4bfaa278633..9a9cc946f82a 100644 --- a/tests/ui/mismatched_types/array-repeat-unit-struct.stderr +++ b/tests/ui/mismatched_types/array-repeat-unit-struct.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-27008.rs:4:17 + --> $DIR/array-repeat-unit-struct.rs:6:17 | LL | let b = [0; S]; | ^ expected `usize`, found `S` diff --git a/tests/ui/mismatched_types/vec-hashset-type-mismatch.rs b/tests/ui/mismatched_types/vec-hashset-type-mismatch.rs index 97d288e5cb14..3724a423d0dd 100644 --- a/tests/ui/mismatched_types/vec-hashset-type-mismatch.rs +++ b/tests/ui/mismatched_types/vec-hashset-type-mismatch.rs @@ -1,3 +1,4 @@ +//! regression test for //@ dont-require-annotations: NOTE use std::collections::HashSet; @@ -9,5 +10,4 @@ fn main() { //~| NOTE expected `&mut HashSet`, found `&mut Vec<_>` } -fn foo(h: &mut HashSet) { -} +fn foo(h: &mut HashSet) {} diff --git a/tests/ui/mismatched_types/vec-hashset-type-mismatch.stderr b/tests/ui/mismatched_types/vec-hashset-type-mismatch.stderr index e144f37d6e48..e778422d0064 100644 --- a/tests/ui/mismatched_types/vec-hashset-type-mismatch.stderr +++ b/tests/ui/mismatched_types/vec-hashset-type-mismatch.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-24819.rs:7:9 + --> $DIR/vec-hashset-type-mismatch.rs:8:9 | LL | foo(&mut v); | --- ^^^^^^ expected `&mut HashSet`, found `&mut Vec<_>` @@ -9,9 +9,9 @@ LL | foo(&mut v); = note: expected mutable reference `&mut HashSet` found mutable reference `&mut Vec<_>` note: function defined here - --> $DIR/issue-24819.rs:12:4 + --> $DIR/vec-hashset-type-mismatch.rs:13:4 | -LL | fn foo(h: &mut HashSet) { +LL | fn foo(h: &mut HashSet) {} | ^^^ -------------------- error: aborting due to 1 previous error diff --git a/tests/ui/privacy/privacy-sanity-2.rs b/tests/ui/privacy/privacy-sanity-2.rs deleted file mode 100644 index 2298ad240d56..000000000000 --- a/tests/ui/privacy/privacy-sanity-2.rs +++ /dev/null @@ -1,12 +0,0 @@ -enum Bird { - pub Duck, - //~^ ERROR visibility qualifiers are not permitted here - Goose, - pub(crate) Dove - //~^ ERROR visibility qualifiers are not permitted here -} - - -fn main() { - let y = Bird::Goose; -} diff --git a/tests/ui/privacy/privacy-sanity-2.stderr b/tests/ui/privacy/privacy-sanity-2.stderr deleted file mode 100644 index 0fa67e35f1d4..000000000000 --- a/tests/ui/privacy/privacy-sanity-2.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error[E0449]: visibility qualifiers are not permitted here - --> $DIR/issue-28433.rs:2:5 - | -LL | pub Duck, - | ^^^ help: remove the qualifier - | - = note: enum variants and their fields always share the visibility of the enum they are in - -error[E0449]: visibility qualifiers are not permitted here - --> $DIR/issue-28433.rs:5:5 - | -LL | pub(crate) Dove - | ^^^^^^^^^^ help: remove the qualifier - | - = note: enum variants and their fields always share the visibility of the enum they are in - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0449`. diff --git a/tests/ui/privacy/privacy-sanity.rs b/tests/ui/privacy/privacy-sanity.rs index 6622089dda6d..fcd03394d631 100644 --- a/tests/ui/privacy/privacy-sanity.rs +++ b/tests/ui/privacy/privacy-sanity.rs @@ -25,6 +25,14 @@ pub extern "C" { //~ ERROR visibility qualifiers are not permitted here pub static St: u8; } +enum Bird { + pub Duck, + //~^ ERROR visibility qualifiers are not permitted here + pub(crate) Dove, + //~^ ERROR visibility qualifiers are not permitted here + Goose, +} + const MAIN: u8 = { pub trait Tr { fn f(); @@ -79,4 +87,11 @@ fn main() { pub fn f(); pub static St: u8; } + enum Bird { + pub Duck, + //~^ ERROR visibility qualifiers are not permitted here + pub(crate) Dove, + //~^ ERROR visibility qualifiers are not permitted here + Goose, + } } diff --git a/tests/ui/privacy/privacy-sanity.stderr b/tests/ui/privacy/privacy-sanity.stderr index 0acb05cbabaa..fd643357335a 100644 --- a/tests/ui/privacy/privacy-sanity.stderr +++ b/tests/ui/privacy/privacy-sanity.stderr @@ -47,7 +47,23 @@ LL | pub extern "C" { = note: place qualifiers on individual foreign items instead error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:39:5 + --> $DIR/privacy-sanity.rs:29:5 + | +LL | pub Duck, + | ^^^ help: remove the qualifier + | + = note: enum variants and their fields always share the visibility of the enum they are in + +error[E0449]: visibility qualifiers are not permitted here + --> $DIR/privacy-sanity.rs:31:5 + | +LL | pub(crate) Dove, + | ^^^^^^^^^^ help: remove the qualifier + | + = note: enum variants and their fields always share the visibility of the enum they are in + +error[E0449]: visibility qualifiers are not permitted here + --> $DIR/privacy-sanity.rs:47:5 | LL | pub impl Tr for S { | ^^^ help: remove the qualifier @@ -55,7 +71,7 @@ LL | pub impl Tr for S { = note: trait items always share the visibility of their trait error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:40:9 + --> $DIR/privacy-sanity.rs:48:9 | LL | pub fn f() {} | ^^^ help: remove the qualifier @@ -63,7 +79,7 @@ LL | pub fn f() {} = note: trait items always share the visibility of their trait error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:41:9 + --> $DIR/privacy-sanity.rs:49:9 | LL | pub const C: u8 = 0; | ^^^ help: remove the qualifier @@ -71,7 +87,7 @@ LL | pub const C: u8 = 0; = note: trait items always share the visibility of their trait error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:42:9 + --> $DIR/privacy-sanity.rs:50:9 | LL | pub type T = u8; | ^^^ help: remove the qualifier @@ -79,7 +95,7 @@ LL | pub type T = u8; = note: trait items always share the visibility of their trait error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:44:5 + --> $DIR/privacy-sanity.rs:52:5 | LL | pub impl S { | ^^^ help: remove the qualifier @@ -87,7 +103,7 @@ LL | pub impl S { = note: place qualifiers on individual impl items instead error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:49:5 + --> $DIR/privacy-sanity.rs:57:5 | LL | pub extern "C" { | ^^^ help: remove the qualifier @@ -95,7 +111,7 @@ LL | pub extern "C" { = note: place qualifiers on individual foreign items instead error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:68:5 + --> $DIR/privacy-sanity.rs:76:5 | LL | pub impl Tr for S { | ^^^ help: remove the qualifier @@ -103,7 +119,7 @@ LL | pub impl Tr for S { = note: trait items always share the visibility of their trait error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:69:9 + --> $DIR/privacy-sanity.rs:77:9 | LL | pub fn f() {} | ^^^ help: remove the qualifier @@ -111,7 +127,7 @@ LL | pub fn f() {} = note: trait items always share the visibility of their trait error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:70:9 + --> $DIR/privacy-sanity.rs:78:9 | LL | pub const C: u8 = 0; | ^^^ help: remove the qualifier @@ -119,7 +135,7 @@ LL | pub const C: u8 = 0; = note: trait items always share the visibility of their trait error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:71:9 + --> $DIR/privacy-sanity.rs:79:9 | LL | pub type T = u8; | ^^^ help: remove the qualifier @@ -127,7 +143,7 @@ LL | pub type T = u8; = note: trait items always share the visibility of their trait error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:73:5 + --> $DIR/privacy-sanity.rs:81:5 | LL | pub impl S { | ^^^ help: remove the qualifier @@ -135,13 +151,29 @@ LL | pub impl S { = note: place qualifiers on individual impl items instead error[E0449]: visibility qualifiers are not permitted here - --> $DIR/privacy-sanity.rs:78:5 + --> $DIR/privacy-sanity.rs:86:5 | LL | pub extern "C" { | ^^^ help: remove the qualifier | = note: place qualifiers on individual foreign items instead -error: aborting due to 18 previous errors +error[E0449]: visibility qualifiers are not permitted here + --> $DIR/privacy-sanity.rs:91:9 + | +LL | pub Duck, + | ^^^ help: remove the qualifier + | + = note: enum variants and their fields always share the visibility of the enum they are in + +error[E0449]: visibility qualifiers are not permitted here + --> $DIR/privacy-sanity.rs:93:9 + | +LL | pub(crate) Dove, + | ^^^^^^^^^^ help: remove the qualifier + | + = note: enum variants and their fields always share the visibility of the enum they are in + +error: aborting due to 22 previous errors For more information about this error, try `rustc --explain E0449`. diff --git a/tests/ui/privacy/private-extern-fn-visibility.rs b/tests/ui/privacy/private-extern-fn-visibility.rs index 7741f828c474..39f2c3c003d5 100644 --- a/tests/ui/privacy/private-extern-fn-visibility.rs +++ b/tests/ui/privacy/private-extern-fn-visibility.rs @@ -1,8 +1,11 @@ -//@ aux-build:issue-16725.rs +//! regression test for +//@ aux-build:private-extern-fn.rs -extern crate issue_16725 as foo; +extern crate private_extern_fn as foo; fn main() { - unsafe { foo::bar(); } - //~^ ERROR: function `bar` is private + unsafe { + foo::bar(); + //~^ ERROR: function `bar` is private + } } diff --git a/tests/ui/privacy/private-extern-fn-visibility.stderr b/tests/ui/privacy/private-extern-fn-visibility.stderr index dcb7d58b0f96..8b1fa512b5de 100644 --- a/tests/ui/privacy/private-extern-fn-visibility.stderr +++ b/tests/ui/privacy/private-extern-fn-visibility.stderr @@ -1,11 +1,11 @@ error[E0603]: function `bar` is private - --> $DIR/issue-16725.rs:6:19 + --> $DIR/private-extern-fn-visibility.rs:8:14 | -LL | unsafe { foo::bar(); } - | ^^^ private function +LL | foo::bar(); + | ^^^ private function | note: the function `bar` is defined here - --> $DIR/auxiliary/issue-16725.rs:2:5 + --> $DIR/auxiliary/private-extern-fn.rs:2:5 | LL | fn bar(); | ^^^^^^^^^ diff --git a/tests/ui/static/static-str-deref-ref.rs b/tests/ui/static/static-str-deref-ref.rs index e8fc680f0422..86c37e527657 100644 --- a/tests/ui/static/static-str-deref-ref.rs +++ b/tests/ui/static/static-str-deref-ref.rs @@ -1,3 +1,4 @@ +//! regression test for //@ build-pass #[allow(dead_code)] static X: &'static str = &*""; diff --git a/tests/ui/threads-sendsync/std-sync-right-kind-impls-2.rs b/tests/ui/threads-sendsync/std-sync-right-kind-impls-2.rs deleted file mode 100644 index 0fa284cc7c0c..000000000000 --- a/tests/ui/threads-sendsync/std-sync-right-kind-impls-2.rs +++ /dev/null @@ -1,25 +0,0 @@ -//@ run-pass -#![allow(dead_code)] - -use std::{fs, net}; - -fn assert_both() {} -fn assert_send() {} - -fn main() { - assert_both::(); - assert_both::(); - assert_both::(); - assert_both::(); - assert_both::(); - assert_both::(); - - assert_both::(); - assert_both::(); - assert_both::(); - assert_both::(); - assert_both::(); - assert_both::(); - assert_both::(); - assert_both::(); -} diff --git a/tests/ui/threads-sendsync/std-sync-right-kind-impls.rs b/tests/ui/threads-sendsync/std-sync-right-kind-impls.rs index b2d22631c1a5..42135fe1c45b 100644 --- a/tests/ui/threads-sendsync/std-sync-right-kind-impls.rs +++ b/tests/ui/threads-sendsync/std-sync-right-kind-impls.rs @@ -1,6 +1,6 @@ //@ run-pass -use std::sync; +use std::{fs, net, sync}; fn assert_both() {} @@ -12,4 +12,20 @@ fn main() { assert_both::>(); assert_both::>(); assert_both::(); + + assert_both::(); + assert_both::(); + assert_both::(); + assert_both::(); + assert_both::(); + assert_both::(); + + assert_both::(); + assert_both::(); + assert_both::(); + assert_both::(); + assert_both::(); + assert_both::(); + assert_both::(); + assert_both::(); } From 5c057ad89617b3872de836f6658f53db2a6c6e3a Mon Sep 17 00:00:00 2001 From: Asuna Date: Thu, 15 Jan 2026 21:12:04 +0100 Subject: [PATCH 054/146] Remove their own `TypeId` from type info for primitives --- .../src/const_eval/type_info.rs | 52 +++++-------------- library/core/src/mem/type_info.rs | 15 ++---- tests/ui/reflection/dump.bit32.run.stdout | 14 +---- tests/ui/reflection/dump.bit64.run.stdout | 14 +---- 4 files changed, 19 insertions(+), 76 deletions(-) diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index fc3378275be2..1e4b72d0ddac 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -66,55 +66,39 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { variant } ty::Bool => { - let (variant, variant_place) = downcast(sym::Bool)?; - let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_primitive_type_info(place, ty, None)?; + let (variant, _variant_place) = downcast(sym::Bool)?; variant } ty::Char => { - let (variant, variant_place) = downcast(sym::Char)?; - let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_primitive_type_info(place, ty, None)?; + let (variant, _variant_place) = downcast(sym::Char)?; variant } ty::Int(int_ty) => { let (variant, variant_place) = downcast(sym::Int)?; let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_primitive_type_info( + self.write_int_float_type_info( place, - ty, - Some( - int_ty - .bit_width() - .unwrap_or_else(/* isize */ ptr_bit_width), - ), + int_ty.bit_width().unwrap_or_else(/* isize */ ptr_bit_width), )?; variant } ty::Uint(uint_ty) => { let (variant, variant_place) = downcast(sym::Uint)?; let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_primitive_type_info( + self.write_int_float_type_info( place, - ty, - Some( - uint_ty - .bit_width() - .unwrap_or_else(/* usize */ ptr_bit_width), - ), + uint_ty.bit_width().unwrap_or_else(/* usize */ ptr_bit_width), )?; variant } ty::Float(float_ty) => { let (variant, variant_place) = downcast(sym::Float)?; let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_primitive_type_info(place, ty, Some(float_ty.bit_width()))?; + self.write_int_float_type_info(place, float_ty.bit_width())?; variant } ty::Str => { - let (variant, variant_place) = downcast(sym::Str)?; - let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_primitive_type_info(place, ty, None)?; + let (variant, _variant_place) = downcast(sym::Str)?; variant } ty::Adt(_, _) @@ -252,28 +236,20 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { interp_ok(()) } - // This method always writes to field `ty`. - // If field `bit_width` is present, it also writes to it (in which case parameter `write_bit_width` must be `Some`). - fn write_primitive_type_info( + fn write_int_float_type_info( &mut self, place: impl Writeable<'tcx, CtfeProvenance>, - ty: Ty<'tcx>, - write_bit_width: Option, + bit_width: u64, ) -> InterpResult<'tcx> { for (field_idx, field) in place.layout().ty.ty_adt_def().unwrap().non_enum_variant().fields.iter_enumerated() { let field_place = self.project_field(&place, field_idx)?; match field.name { - sym::ty => self.write_type_id(ty, &field_place)?, - sym::bit_width => { - let bit_width = write_bit_width - .expect("type info struct needs a `bit_width` but none was provided"); - self.write_scalar( - ScalarInt::try_from_target_usize(bit_width, self.tcx.tcx).unwrap(), - &field_place, - )? - } + sym::bit_width => self.write_scalar( + ScalarInt::try_from_target_usize(bit_width, self.tcx.tcx).unwrap(), + &field_place, + )?, other => span_bug!(self.tcx.def_span(field.did), "unimplemented field {other}"), } } diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 7db4f3b00123..e02e07ae3b4a 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -97,8 +97,7 @@ pub struct Array { #[non_exhaustive] #[unstable(feature = "type_info", issue = "146922")] pub struct Bool { - /// The type id of `bool`. - pub ty: TypeId, + // No additional information to provide for now. } /// Compile-time type information about `char`. @@ -106,8 +105,7 @@ pub struct Bool { #[non_exhaustive] #[unstable(feature = "type_info", issue = "146922")] pub struct Char { - /// The type id of `char`. - pub ty: TypeId, + // No additional information to provide for now. } /// Compile-time type information about signed integer types. @@ -115,8 +113,6 @@ pub struct Char { #[non_exhaustive] #[unstable(feature = "type_info", issue = "146922")] pub struct Int { - /// The type id of signed integer type. - pub ty: TypeId, /// The bit width of the signed integer type. pub bit_width: usize, } @@ -126,8 +122,6 @@ pub struct Int { #[non_exhaustive] #[unstable(feature = "type_info", issue = "146922")] pub struct Uint { - /// The type id of unsigned integer type. - pub ty: TypeId, /// The bit width of the unsigned integer type. pub bit_width: usize, } @@ -137,8 +131,6 @@ pub struct Uint { #[non_exhaustive] #[unstable(feature = "type_info", issue = "146922")] pub struct Float { - /// The type id of floating-point type. - pub ty: TypeId, /// The bit width of the floating-point type. pub bit_width: usize, } @@ -148,6 +140,5 @@ pub struct Float { #[non_exhaustive] #[unstable(feature = "type_info", issue = "146922")] pub struct Str { - /// The type id of `str`. - pub ty: TypeId, + // No additional information to provide for now. } diff --git a/tests/ui/reflection/dump.bit32.run.stdout b/tests/ui/reflection/dump.bit32.run.stdout index d747ee210204..c6df7b00bf4a 100644 --- a/tests/ui/reflection/dump.bit32.run.stdout +++ b/tests/ui/reflection/dump.bit32.run.stdout @@ -35,7 +35,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0x12427c993eca190c841e0d92c5b7a45d), bit_width: 8, }, ), @@ -46,7 +45,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0x56ced5e4a15bd89050bb9674fa2df013), bit_width: 32, }, ), @@ -57,7 +55,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0xae6c4318bb07632e00428affbea41961), bit_width: 64, }, ), @@ -68,7 +65,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0xc7164498f3902dde0d8194a7b9733e79), bit_width: 128, }, ), @@ -79,7 +75,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0x1e5f92831c560aac8658b980a22e60b0), bit_width: 32, }, ), @@ -90,7 +85,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), bit_width: 8, }, ), @@ -101,7 +95,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x1378bb1c0a0202683eb65e7c11f2e4d7), bit_width: 32, }, ), @@ -112,7 +105,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x9ed91be891e304132cb86891e578f4a5), bit_width: 64, }, ), @@ -123,7 +115,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x7bf7411d57d603e9fb393892a9c3f362), bit_width: 128, }, ), @@ -134,7 +125,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x763d199bccd319899208909ed1a860c6), bit_width: 32, }, ), @@ -174,9 +164,7 @@ Type { } Type { kind: Str( - Str { - ty: TypeId(0x474ccf3b5db264ef53916706f7d7bb2c), - }, + Str, ), size: None, } diff --git a/tests/ui/reflection/dump.bit64.run.stdout b/tests/ui/reflection/dump.bit64.run.stdout index 180a6e2882d7..0f39e3e4c6b0 100644 --- a/tests/ui/reflection/dump.bit64.run.stdout +++ b/tests/ui/reflection/dump.bit64.run.stdout @@ -35,7 +35,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0x12427c993eca190c841e0d92c5b7a45d), bit_width: 8, }, ), @@ -46,7 +45,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0x56ced5e4a15bd89050bb9674fa2df013), bit_width: 32, }, ), @@ -57,7 +55,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0xae6c4318bb07632e00428affbea41961), bit_width: 64, }, ), @@ -68,7 +65,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0xc7164498f3902dde0d8194a7b9733e79), bit_width: 128, }, ), @@ -79,7 +75,6 @@ Type { Type { kind: Int( Int { - ty: TypeId(0x1e5f92831c560aac8658b980a22e60b0), bit_width: 64, }, ), @@ -90,7 +85,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), bit_width: 8, }, ), @@ -101,7 +95,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x1378bb1c0a0202683eb65e7c11f2e4d7), bit_width: 32, }, ), @@ -112,7 +105,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x9ed91be891e304132cb86891e578f4a5), bit_width: 64, }, ), @@ -123,7 +115,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x7bf7411d57d603e9fb393892a9c3f362), bit_width: 128, }, ), @@ -134,7 +125,6 @@ Type { Type { kind: Uint( Uint { - ty: TypeId(0x763d199bccd319899208909ed1a860c6), bit_width: 64, }, ), @@ -174,9 +164,7 @@ Type { } Type { kind: Str( - Str { - ty: TypeId(0x474ccf3b5db264ef53916706f7d7bb2c), - }, + Str, ), size: None, } From b2a7b18ec4c93ef11eb51cb2dccbe5f257993bd1 Mon Sep 17 00:00:00 2001 From: Asuna Date: Thu, 15 Jan 2026 22:17:43 +0100 Subject: [PATCH 055/146] Merge type info variant `Uint` into `Int` --- .../src/const_eval/type_info.rs | 36 +++++++++++++++---- compiler/rustc_span/src/symbol.rs | 2 +- library/core/src/mem/type_info.rs | 17 +++------ library/coretests/tests/mem/type_info.rs | 16 +++++---- tests/ui/reflection/dump.bit32.run.stdout | 30 ++++++++++------ tests/ui/reflection/dump.bit64.run.stdout | 30 ++++++++++------ 6 files changed, 85 insertions(+), 46 deletions(-) diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index 1e4b72d0ddac..5d37db06d76a 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -1,6 +1,6 @@ use rustc_abi::FieldIdx; use rustc_hir::LangItem; -use rustc_middle::mir::interpret::CtfeProvenance; +use rustc_middle::mir::interpret::{CtfeProvenance, Scalar}; use rustc_middle::span_bug; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, Const, ScalarInt, Ty}; @@ -76,25 +76,27 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { ty::Int(int_ty) => { let (variant, variant_place) = downcast(sym::Int)?; let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_int_float_type_info( + self.write_int_type_info( place, int_ty.bit_width().unwrap_or_else(/* isize */ ptr_bit_width), + true, )?; variant } ty::Uint(uint_ty) => { - let (variant, variant_place) = downcast(sym::Uint)?; + let (variant, variant_place) = downcast(sym::Int)?; let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_int_float_type_info( + self.write_int_type_info( place, uint_ty.bit_width().unwrap_or_else(/* usize */ ptr_bit_width), + false, )?; variant } ty::Float(float_ty) => { let (variant, variant_place) = downcast(sym::Float)?; let place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_int_float_type_info(place, float_ty.bit_width())?; + self.write_float_type_info(place, float_ty.bit_width())?; variant } ty::Str => { @@ -236,7 +238,29 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { interp_ok(()) } - fn write_int_float_type_info( + fn write_int_type_info( + &mut self, + place: impl Writeable<'tcx, CtfeProvenance>, + bit_width: u64, + signed: bool, + ) -> InterpResult<'tcx> { + for (field_idx, field) in + place.layout().ty.ty_adt_def().unwrap().non_enum_variant().fields.iter_enumerated() + { + let field_place = self.project_field(&place, field_idx)?; + match field.name { + sym::bit_width => self.write_scalar( + ScalarInt::try_from_target_usize(bit_width, self.tcx.tcx).unwrap(), + &field_place, + )?, + sym::signed => self.write_scalar(Scalar::from_bool(signed), &field_place)?, + other => span_bug!(self.tcx.def_span(field.did), "unimplemented field {other}"), + } + } + interp_ok(()) + } + + fn write_float_type_info( &mut self, place: impl Writeable<'tcx, CtfeProvenance>, bit_width: u64, diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 4c19fa83fd3a..6aa6ce269517 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -391,7 +391,6 @@ symbols! { Ty, TyCtxt, TyKind, - Uint, Unknown, Unsize, UnsizedConstParamTy, @@ -2066,6 +2065,7 @@ symbols! { shr_assign, sig_dfl, sig_ign, + signed, simd, simd_add, simd_and, diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index e02e07ae3b4a..2e3bdb45ce05 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -49,10 +49,8 @@ pub enum TypeKind { Bool(Bool), /// Primitive character type. Char(Char), - /// Primitive signed integer type. + /// Primitive signed and unsigned integer type. Int(Int), - /// Primitive unsigned integer type. - Uint(Uint), /// Primitive floating-point type. Float(Float), /// String slice type. @@ -108,22 +106,15 @@ pub struct Char { // No additional information to provide for now. } -/// Compile-time type information about signed integer types. +/// Compile-time type information about signed and unsigned integer types. #[derive(Debug)] #[non_exhaustive] #[unstable(feature = "type_info", issue = "146922")] pub struct Int { /// The bit width of the signed integer type. pub bit_width: usize, -} - -/// Compile-time type information about unsigned integer types. -#[derive(Debug)] -#[non_exhaustive] -#[unstable(feature = "type_info", issue = "146922")] -pub struct Uint { - /// The bit width of the unsigned integer type. - pub bit_width: usize, + /// Whether the integer type is signed. + pub signed: bool, } /// Compile-time type information about floating-point types. diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index 5dd8f4034d11..fc13637a5574 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -38,7 +38,7 @@ fn test_tuples() { assert_tuple_arity::<(u8, u8), 2>(); const { - match Type::of::<(u8, u8)>().kind { + match Type::of::<(i8, u8)>().kind { TypeKind::Tuple(tup) => { let [a, b] = tup.fields else { unreachable!() }; @@ -46,9 +46,9 @@ fn test_tuples() { assert!(b.offset == 1); match (a.ty.info().kind, b.ty.info().kind) { - (TypeKind::Uint(a), TypeKind::Uint(b)) => { - assert!(a.bit_width == 8); - assert!(b.bit_width == 8); + (TypeKind::Int(a), TypeKind::Int(b)) => { + assert!(a.bit_width == 8 && a.signed); + assert!(b.bit_width == 8 && !b.signed); } _ => unreachable!(), } @@ -71,18 +71,22 @@ fn test_primitives() { let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(4)); assert_eq!(ty.bit_width, 32); + assert!(ty.signed); let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(size_of::())); assert_eq!(ty.bit_width, size_of::() * 8); + assert!(ty.signed); - let Type { kind: Uint(ty), size, .. } = (const { Type::of::() }) else { panic!() }; + let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(4)); assert_eq!(ty.bit_width, 32); + assert!(!ty.signed); - let Type { kind: Uint(ty), size, .. } = (const { Type::of::() }) else { panic!() }; + let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(size_of::())); assert_eq!(ty.bit_width, size_of::() * 8); + assert!(!ty.signed); let Type { kind: Float(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(4)); diff --git a/tests/ui/reflection/dump.bit32.run.stdout b/tests/ui/reflection/dump.bit32.run.stdout index c6df7b00bf4a..483efdbbd12a 100644 --- a/tests/ui/reflection/dump.bit32.run.stdout +++ b/tests/ui/reflection/dump.bit32.run.stdout @@ -36,6 +36,7 @@ Type { kind: Int( Int { bit_width: 8, + signed: true, }, ), size: Some( @@ -46,6 +47,7 @@ Type { kind: Int( Int { bit_width: 32, + signed: true, }, ), size: Some( @@ -56,6 +58,7 @@ Type { kind: Int( Int { bit_width: 64, + signed: true, }, ), size: Some( @@ -66,6 +69,7 @@ Type { kind: Int( Int { bit_width: 128, + signed: true, }, ), size: Some( @@ -76,6 +80,7 @@ Type { kind: Int( Int { bit_width: 32, + signed: true, }, ), size: Some( @@ -83,9 +88,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 8, + signed: false, }, ), size: Some( @@ -93,9 +99,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 32, + signed: false, }, ), size: Some( @@ -103,9 +110,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 64, + signed: false, }, ), size: Some( @@ -113,9 +121,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 128, + signed: false, }, ), size: Some( @@ -123,9 +132,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 32, + signed: false, }, ), size: Some( diff --git a/tests/ui/reflection/dump.bit64.run.stdout b/tests/ui/reflection/dump.bit64.run.stdout index 0f39e3e4c6b0..681e81b71d56 100644 --- a/tests/ui/reflection/dump.bit64.run.stdout +++ b/tests/ui/reflection/dump.bit64.run.stdout @@ -36,6 +36,7 @@ Type { kind: Int( Int { bit_width: 8, + signed: true, }, ), size: Some( @@ -46,6 +47,7 @@ Type { kind: Int( Int { bit_width: 32, + signed: true, }, ), size: Some( @@ -56,6 +58,7 @@ Type { kind: Int( Int { bit_width: 64, + signed: true, }, ), size: Some( @@ -66,6 +69,7 @@ Type { kind: Int( Int { bit_width: 128, + signed: true, }, ), size: Some( @@ -76,6 +80,7 @@ Type { kind: Int( Int { bit_width: 64, + signed: true, }, ), size: Some( @@ -83,9 +88,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 8, + signed: false, }, ), size: Some( @@ -93,9 +99,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 32, + signed: false, }, ), size: Some( @@ -103,9 +110,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 64, + signed: false, }, ), size: Some( @@ -113,9 +121,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 128, + signed: false, }, ), size: Some( @@ -123,9 +132,10 @@ Type { ), } Type { - kind: Uint( - Uint { + kind: Int( + Int { bit_width: 64, + signed: false, }, ), size: Some( From 0dc5b52e8eef98e973d9935c45e8dc3d7fbd6a1d Mon Sep 17 00:00:00 2001 From: Usman Akinyemi Date: Fri, 16 Jan 2026 04:25:12 +0530 Subject: [PATCH 056/146] simplify words initialization using Rc::new_zeroed Now that Rc::new_zeroed is stable, remove the cfg(feature = "nightly") branch and the temporary zeroed array on stable. This avoids copying a potentially large [Word; CHUNK_WORDS] into the Rc. Signed-off-by: Usman Akinyemi --- compiler/rustc_index/src/bit_set.rs | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index a9bdf597e128..184fa409d960 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -634,22 +634,12 @@ impl ChunkedBitSet { match *chunk { Zeros => { if chunk_domain_size > 1 { - #[cfg(feature = "nightly")] let mut words = { // We take some effort to avoid copying the words. let words = Rc::<[Word; CHUNK_WORDS]>::new_zeroed(); // SAFETY: `words` can safely be all zeroes. unsafe { words.assume_init() } }; - #[cfg(not(feature = "nightly"))] - let mut words = { - // FIXME: unconditionally use `Rc::new_zeroed` once it is stable (#129396). - let words = mem::MaybeUninit::<[Word; CHUNK_WORDS]>::zeroed(); - // SAFETY: `words` can safely be all zeroes. - let words = unsafe { words.assume_init() }; - // Unfortunate possibly-large copy - Rc::new(words) - }; let words_ref = Rc::get_mut(&mut words).unwrap(); let (word_index, mask) = chunk_word_index_and_mask(elem); @@ -695,22 +685,12 @@ impl ChunkedBitSet { Zeros => false, Ones => { if chunk_domain_size > 1 { - #[cfg(feature = "nightly")] let mut words = { // We take some effort to avoid copying the words. let words = Rc::<[Word; CHUNK_WORDS]>::new_zeroed(); // SAFETY: `words` can safely be all zeroes. unsafe { words.assume_init() } }; - #[cfg(not(feature = "nightly"))] - let mut words = { - // FIXME: unconditionally use `Rc::new_zeroed` once it is stable (#129396). - let words = mem::MaybeUninit::<[Word; CHUNK_WORDS]>::zeroed(); - // SAFETY: `words` can safely be all zeroes. - let words = unsafe { words.assume_init() }; - // Unfortunate possibly-large copy - Rc::new(words) - }; let words_ref = Rc::get_mut(&mut words).unwrap(); // Set only the bits in use. From 02c5f9a5b455ecf4e9eeeb0510c8ba65ff39ce28 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 15 Jan 2026 16:22:18 +1100 Subject: [PATCH 057/146] Add a snapshot test for string patterns in THIR --- tests/ui/thir-print/str-patterns.rs | 17 ++ tests/ui/thir-print/str-patterns.stdout | 310 ++++++++++++++++++++++++ 2 files changed, 327 insertions(+) create mode 100644 tests/ui/thir-print/str-patterns.rs create mode 100644 tests/ui/thir-print/str-patterns.stdout diff --git a/tests/ui/thir-print/str-patterns.rs b/tests/ui/thir-print/str-patterns.rs new file mode 100644 index 000000000000..4ad782f63a50 --- /dev/null +++ b/tests/ui/thir-print/str-patterns.rs @@ -0,0 +1,17 @@ +#![crate_type = "rlib"] +//@ edition: 2024 +//@ compile-flags: -Zunpretty=thir-flat +//@ check-pass + +// Snapshot test capturing the THIR pattern structure produced by +// string-literal and string-constant patterns. + +pub fn hello_world(x: &str) { + match x { + "hello" => {} + CONSTANT => {} + _ => {} + } +} + +const CONSTANT: &str = "constant"; diff --git a/tests/ui/thir-print/str-patterns.stdout b/tests/ui/thir-print/str-patterns.stdout new file mode 100644 index 000000000000..8f8944ad4e09 --- /dev/null +++ b/tests/ui/thir-print/str-patterns.stdout @@ -0,0 +1,310 @@ +DefId(0:3 ~ str_patterns[fc71]::hello_world): +Thir { + body_type: Fn( + fn(&'{erased} str), + ), + arms: [ + Arm { + pattern: Pat { + ty: &'{erased} str, + span: $DIR/str-patterns.rs:11:9: 11:16 (#0), + extra: None, + kind: Constant { + value: Value { + ty: &'{erased} str, + valtree: Branch( + [ + 104_u8, + 101_u8, + 108_u8, + 108_u8, + 111_u8, + ], + ), + }, + }, + }, + guard: None, + body: e3, + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).9), + scope: Node(9), + span: $DIR/str-patterns.rs:11:9: 11:22 (#0), + }, + Arm { + pattern: Pat { + ty: &'{erased} str, + span: $DIR/str-patterns.rs:12:9: 12:17 (#0), + extra: Some( + PatExtra { + expanded_const: Some( + DefId(0:4 ~ str_patterns[fc71]::CONSTANT), + ), + ascriptions: [], + }, + ), + kind: Constant { + value: Value { + ty: &'{erased} str, + valtree: Branch( + [ + 99_u8, + 111_u8, + 110_u8, + 115_u8, + 116_u8, + 97_u8, + 110_u8, + 116_u8, + ], + ), + }, + }, + }, + guard: None, + body: e5, + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).15), + scope: Node(15), + span: $DIR/str-patterns.rs:12:9: 12:23 (#0), + }, + Arm { + pattern: Pat { + ty: &'{erased} str, + span: $DIR/str-patterns.rs:13:9: 13:10 (#0), + extra: None, + kind: Wild, + }, + guard: None, + body: e7, + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).19), + scope: Node(19), + span: $DIR/str-patterns.rs:13:9: 13:16 (#0), + }, + ], + blocks: [ + Block { + targeted_by_break: false, + region_scope: Node(11), + span: $DIR/str-patterns.rs:11:20: 11:22 (#0), + stmts: [], + expr: None, + safety_mode: Safe, + }, + Block { + targeted_by_break: false, + region_scope: Node(17), + span: $DIR/str-patterns.rs:12:21: 12:23 (#0), + stmts: [], + expr: None, + safety_mode: Safe, + }, + Block { + targeted_by_break: false, + region_scope: Node(21), + span: $DIR/str-patterns.rs:13:14: 13:16 (#0), + stmts: [], + expr: None, + safety_mode: Safe, + }, + Block { + targeted_by_break: false, + region_scope: Node(3), + span: $DIR/str-patterns.rs:9:29: 15:2 (#0), + stmts: [], + expr: Some( + e9, + ), + safety_mode: Safe, + }, + ], + exprs: [ + Expr { + kind: VarRef { + id: LocalVarId( + HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).2), + ), + }, + ty: &'{erased} str, + temp_scope_id: 5, + span: $DIR/str-patterns.rs:10:11: 10:12 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(5), + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).5), + value: e0, + }, + ty: &'{erased} str, + temp_scope_id: 5, + span: $DIR/str-patterns.rs:10:11: 10:12 (#0), + }, + Expr { + kind: Block { + block: b0, + }, + ty: (), + temp_scope_id: 10, + span: $DIR/str-patterns.rs:11:20: 11:22 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(10), + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).10), + value: e2, + }, + ty: (), + temp_scope_id: 10, + span: $DIR/str-patterns.rs:11:20: 11:22 (#0), + }, + Expr { + kind: Block { + block: b1, + }, + ty: (), + temp_scope_id: 16, + span: $DIR/str-patterns.rs:12:21: 12:23 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(16), + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).16), + value: e4, + }, + ty: (), + temp_scope_id: 16, + span: $DIR/str-patterns.rs:12:21: 12:23 (#0), + }, + Expr { + kind: Block { + block: b2, + }, + ty: (), + temp_scope_id: 20, + span: $DIR/str-patterns.rs:13:14: 13:16 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(20), + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).20), + value: e6, + }, + ty: (), + temp_scope_id: 20, + span: $DIR/str-patterns.rs:13:14: 13:16 (#0), + }, + Expr { + kind: Match { + scrutinee: e1, + arms: [ + a0, + a1, + a2, + ], + match_source: Normal, + }, + ty: (), + temp_scope_id: 4, + span: $DIR/str-patterns.rs:10:5: 14:6 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(4), + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).4), + value: e8, + }, + ty: (), + temp_scope_id: 4, + span: $DIR/str-patterns.rs:10:5: 14:6 (#0), + }, + Expr { + kind: Block { + block: b3, + }, + ty: (), + temp_scope_id: 22, + span: $DIR/str-patterns.rs:9:29: 15:2 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(22), + hir_id: HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).22), + value: e10, + }, + ty: (), + temp_scope_id: 22, + span: $DIR/str-patterns.rs:9:29: 15:2 (#0), + }, + ], + stmts: [], + params: [ + Param { + pat: Some( + Pat { + ty: &'{erased} str, + span: $DIR/str-patterns.rs:9:20: 9:21 (#0), + extra: None, + kind: Binding { + name: "x", + mode: BindingMode( + No, + Not, + ), + var: LocalVarId( + HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).2), + ), + ty: &'{erased} str, + subpattern: None, + is_primary: true, + is_shorthand: false, + }, + }, + ), + ty: &'{erased} str, + ty_span: Some( + $DIR/str-patterns.rs:9:23: 9:27 (#0), + ), + self_kind: None, + hir_id: Some( + HirId(DefId(0:3 ~ str_patterns[fc71]::hello_world).1), + ), + }, + ], +} + +DefId(0:4 ~ str_patterns[fc71]::CONSTANT): +Thir { + body_type: Const( + &'{erased} str, + ), + arms: [], + blocks: [], + exprs: [ + Expr { + kind: Literal { + lit: Spanned { + node: Str( + "constant", + Cooked, + ), + span: $DIR/str-patterns.rs:17:24: 17:34 (#0), + }, + neg: false, + }, + ty: &'{erased} str, + temp_scope_id: 5, + span: $DIR/str-patterns.rs:17:24: 17:34 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(5), + hir_id: HirId(DefId(0:4 ~ str_patterns[fc71]::CONSTANT).5), + value: e0, + }, + ty: &'{erased} str, + temp_scope_id: 5, + span: $DIR/str-patterns.rs:17:24: 17:34 (#0), + }, + ], + stmts: [], + params: [], +} + From 066eb6d2eaea164d3623df9b2bde383e9c8917f3 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 15 Jan 2026 00:17:06 +1100 Subject: [PATCH 058/146] THIR patterns: Always use type `str` for string-constant-value nodes --- .../src/builder/matches/match_pair.rs | 16 +---- .../src/builder/matches/mod.rs | 6 +- .../src/builder/matches/test.rs | 62 +++++++---------- .../src/thir/pattern/const_to_pat.rs | 45 ++++++------ compiler/rustc_pattern_analysis/src/rustc.rs | 20 ++---- ....constant_eq.SimplifyCfg-initial.after.mir | 37 ++++++---- tests/ui/thir-print/str-patterns.stdout | 68 +++++++++++-------- 7 files changed, 118 insertions(+), 136 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs index 3edd0234b0ad..e80e29415e6f 100644 --- a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -2,7 +2,6 @@ use std::sync::Arc; use rustc_abi::FieldIdx; use rustc_middle::mir::*; -use rustc_middle::span_bug; use rustc_middle::thir::*; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; @@ -160,10 +159,7 @@ impl<'tcx> MatchPairTree<'tcx> { } PatKind::Constant { value } => { - // CAUTION: The type of the pattern node (`pattern.ty`) is - // _often_ the same as the type of the const value (`value.ty`), - // but there are some cases where those types differ - // (e.g. when `deref!(..)` patterns interact with `String`). + assert_eq!(pattern.ty, value.ty); // Classify the constant-pattern into further kinds, to // reduce the number of ad-hoc type tests needed later on. @@ -175,16 +171,6 @@ impl<'tcx> MatchPairTree<'tcx> { } else if pat_ty.is_floating_point() { PatConstKind::Float } else if pat_ty.is_str() { - // Deref-patterns can cause string-literal patterns to have - // type `str` instead of the usual `&str`. - if !cx.tcx.features().deref_patterns() { - span_bug!( - pattern.span, - "const pattern has type `str` but deref_patterns is not enabled" - ); - } - PatConstKind::String - } else if pat_ty.is_imm_ref_str() { PatConstKind::String } else { // FIXME(Zalathar): This still covers several different diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 0463f7c914a4..ddd70a3b597c 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -1339,11 +1339,9 @@ enum TestKind<'tcx> { /// Tests the place against a string constant using string equality. StringEq { - /// Constant `&str` value to test against. + /// Constant string value to test against. + /// Note that this value has type `str` (not `&str`). value: ty::Value<'tcx>, - /// Type of the corresponding pattern node. Usually `&str`, but could - /// be `str` for patterns like `deref!("..."): String`. - pat_ty: Ty<'tcx>, }, /// Tests the place against a constant using scalar equality. diff --git a/compiler/rustc_mir_build/src/builder/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index c2e39d47a92c..bab9f38f084d 100644 --- a/compiler/rustc_mir_build/src/builder/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -9,10 +9,10 @@ use std::sync::Arc; use rustc_data_structures::fx::FxIndexMap; use rustc_hir::{LangItem, RangeEnd}; +use rustc_middle::bug; use rustc_middle::mir::*; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt}; -use rustc_middle::{bug, span_bug}; use rustc_span::def_id::DefId; use rustc_span::source_map::Spanned; use rustc_span::{DUMMY_SP, Span, Symbol, sym}; @@ -39,7 +39,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { TestKind::SwitchInt } TestableCase::Constant { value, kind: PatConstKind::String } => { - TestKind::StringEq { value, pat_ty: match_pair.pattern_ty } + TestKind::StringEq { value } } TestableCase::Constant { value, kind: PatConstKind::Float | PatConstKind::Other } => { TestKind::ScalarEq { value, pat_ty: match_pair.pattern_ty } @@ -141,47 +141,33 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.cfg.terminate(block, self.source_info(match_start_span), terminator); } - TestKind::StringEq { value, pat_ty } => { + TestKind::StringEq { value } => { let tcx = self.tcx; let success_block = target_block(TestBranch::Success); let fail_block = target_block(TestBranch::Failure); - let expected_value_ty = value.ty; + let ref_str_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, tcx.types.str_); + assert!(ref_str_ty.is_imm_ref_str(), "{ref_str_ty:?}"); + + // The string constant we're testing against has type `str`, but + // calling `::eq` requires `&str` operands. + // + // Because `str` and `&str` have the same valtree representation, + // we can "cast" to the desired type by just replacing the type. + assert!(value.ty.is_str(), "unexpected value type for StringEq test: {value:?}"); + let expected_value = ty::Value { ty: ref_str_ty, valtree: value.valtree }; let expected_value_operand = - self.literal_operand(test.span, Const::from_ty_value(tcx, value)); + self.literal_operand(test.span, Const::from_ty_value(tcx, expected_value)); - let mut actual_value_ty = pat_ty; - let mut actual_value_place = place; - - match pat_ty.kind() { - ty::Str => { - // String literal patterns may have type `str` if `deref_patterns` is - // enabled, in order to allow `deref!("..."): String`. In this case, `value` - // is of type `&str`, so we compare it to `&place`. - if !tcx.features().deref_patterns() { - span_bug!( - test.span, - "matching on `str` went through without enabling deref_patterns" - ); - } - let re_erased = tcx.lifetimes.re_erased; - let ref_str_ty = Ty::new_imm_ref(tcx, re_erased, tcx.types.str_); - let ref_place = self.temp(ref_str_ty, test.span); - // `let ref_place: &str = &place;` - self.cfg.push_assign( - block, - self.source_info(test.span), - ref_place, - Rvalue::Ref(re_erased, BorrowKind::Shared, place), - ); - actual_value_place = ref_place; - actual_value_ty = ref_str_ty; - } - _ => {} - } - - assert_eq!(expected_value_ty, actual_value_ty); - assert!(actual_value_ty.is_imm_ref_str()); + // Similarly, the scrutinized place has type `str`, but we need `&str`. + // Get a reference by doing `let actual_value_ref_place: &str = &place`. + let actual_value_ref_place = self.temp(ref_str_ty, test.span); + self.cfg.push_assign( + block, + self.source_info(test.span), + actual_value_ref_place, + Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, place), + ); // Compare two strings using `::eq`. // (Interestingly this means that exhaustiveness analysis relies, for soundness, @@ -192,7 +178,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { fail_block, source_info, expected_value_operand, - Operand::Copy(actual_value_place), + Operand::Copy(actual_value_ref_place), ); } diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 02409d2bae9f..70bc142131e4 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -289,32 +289,29 @@ impl<'tcx> ConstToPat<'tcx> { suffix: Box::new([]), }, ty::Str => { - // String literal patterns may have type `str` if `deref_patterns` is enabled, in - // order to allow `deref!("..."): String`. Since we need a `&str` for the comparison - // when lowering to MIR in `Builder::perform_test`, treat the constant as a `&str`. - // This works because `str` and `&str` have the same valtree representation. - let ref_str_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty); - PatKind::Constant { value: ty::Value { ty: ref_str_ty, valtree: cv } } + // Constant/literal patterns of type `&str` are lowered to a + // `PatKind::Deref` wrapping a `PatKind::Constant` of type `str`. + // This pattern node is the `str` constant part. + // + // Under `feature(deref_patterns)`, string literal patterns can also + // have type `str` directly, without the `&`, in order to allow things + // like `deref!("...")` to work when the scrutinee is `String`. + PatKind::Constant { value: ty::Value { ty, valtree: cv } } } - ty::Ref(_, pointee_ty, ..) => match *pointee_ty.kind() { - // `&str` is represented as a valtree, let's keep using this - // optimization for now. - ty::Str => PatKind::Constant { value: ty::Value { ty, valtree: cv } }, - // All other references are converted into deref patterns and then recursively - // convert the dereferenced constant to a pattern that is the sub-pattern of the - // deref pattern. - _ => { - if !pointee_ty.is_sized(tcx, self.typing_env) && !pointee_ty.is_slice() { - return self.mk_err( - tcx.dcx().create_err(UnsizedPattern { span, non_sm_ty: *pointee_ty }), - ty, - ); - } else { - // References have the same valtree representation as their pointee. - PatKind::Deref { subpattern: self.valtree_to_pat(cv, *pointee_ty) } - } + ty::Ref(_, pointee_ty, ..) => { + if pointee_ty.is_str() + || pointee_ty.is_slice() + || pointee_ty.is_sized(tcx, self.typing_env) + { + // References have the same valtree representation as their pointee. + PatKind::Deref { subpattern: self.valtree_to_pat(cv, *pointee_ty) } + } else { + return self.mk_err( + tcx.dcx().create_err(UnsizedPattern { span, non_sm_ty: *pointee_ty }), + ty, + ); } - }, + } ty::Float(flt) => { let v = cv.to_leaf(); let is_nan = match flt { diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 721635ed48ff..5e75192ff309 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -583,19 +583,13 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { fields = vec![]; arity = 0; } - ty::Ref(_, t, _) if t.is_str() => { - // We want a `&str` constant to behave like a `Deref` pattern, to be compatible - // with other `Deref` patterns. This could have been done in `const_to_pat`, - // but that causes issues with the rest of the matching code. - // So here, the constructor for a `"foo"` pattern is `&` (represented by - // `Ref`), and has one field. That field has constructor `Str(value)` and no - // subfields. - // Note: `t` is `str`, not `&str`. - let ty = self.reveal_opaque_ty(*t); - let subpattern = DeconstructedPat::new(Str(*value), Vec::new(), 0, ty, pat); - ctor = Ref; - fields = vec![subpattern.at_index(0)]; - arity = 1; + ty::Str => { + // For constant/literal patterns of type `&str`, the THIR + // pattern is a `PatKind::Deref` of type `&str` wrapping a + // `PatKind::Const` of type `str`. + ctor = Str(*value); + fields = vec![]; + arity = 0; } // All constants that can be structurally matched have already been expanded // into the corresponding `Pat`s by `const_to_pat`. Constants that remain are diff --git a/tests/mir-opt/building/match/sort_candidates.constant_eq.SimplifyCfg-initial.after.mir b/tests/mir-opt/building/match/sort_candidates.constant_eq.SimplifyCfg-initial.after.mir index b8f54fef0faf..4d13d087586e 100644 --- a/tests/mir-opt/building/match/sort_candidates.constant_eq.SimplifyCfg-initial.after.mir +++ b/tests/mir-opt/building/match/sort_candidates.constant_eq.SimplifyCfg-initial.after.mir @@ -7,11 +7,14 @@ fn constant_eq(_1: &str, _2: bool) -> u32 { let mut _3: (&str, bool); let mut _4: &str; let mut _5: bool; - let mut _6: &&str; - let mut _7: &bool; - let mut _8: bool; - let mut _9: bool; + let mut _6: &str; + let mut _7: &&str; + let mut _8: &bool; + let mut _9: &str; let mut _10: bool; + let mut _11: &str; + let mut _12: bool; + let mut _13: bool; bb0: { StorageLive(_3); @@ -23,7 +26,8 @@ fn constant_eq(_1: &str, _2: bool) -> u32 { StorageDead(_5); StorageDead(_4); PlaceMention(_3); - _9 = ::eq(copy (_3.0: &str), const "a") -> [return: bb9, unwind: bb19]; + _11 = &(*(_3.0: &str)); + _12 = ::eq(copy _11, const "a") -> [return: bb9, unwind: bb19]; } bb1: { @@ -43,7 +47,8 @@ fn constant_eq(_1: &str, _2: bool) -> u32 { } bb5: { - _8 = ::eq(copy (_3.0: &str), const "b") -> [return: bb8, unwind: bb19]; + _9 = &(*(_3.0: &str)); + _10 = ::eq(copy _9, const "b") -> [return: bb8, unwind: bb19]; } bb6: { @@ -55,11 +60,11 @@ fn constant_eq(_1: &str, _2: bool) -> u32 { } bb8: { - switchInt(move _8) -> [0: bb1, otherwise: bb6]; + switchInt(move _10) -> [0: bb1, otherwise: bb6]; } bb9: { - switchInt(move _9) -> [0: bb5, otherwise: bb2]; + switchInt(move _12) -> [0: bb5, otherwise: bb2]; } bb10: { @@ -87,23 +92,25 @@ fn constant_eq(_1: &str, _2: bool) -> u32 { } bb15: { - _6 = &fake shallow (_3.0: &str); - _7 = &fake shallow (_3.1: bool); - StorageLive(_10); - _10 = const true; - switchInt(move _10) -> [0: bb17, otherwise: bb16]; + _6 = &fake shallow (*(_3.0: &str)); + _7 = &fake shallow (_3.0: &str); + _8 = &fake shallow (_3.1: bool); + StorageLive(_13); + _13 = const true; + switchInt(move _13) -> [0: bb17, otherwise: bb16]; } bb16: { - StorageDead(_10); + StorageDead(_13); FakeRead(ForMatchGuard, _6); FakeRead(ForMatchGuard, _7); + FakeRead(ForMatchGuard, _8); _0 = const 1_u32; goto -> bb18; } bb17: { - StorageDead(_10); + StorageDead(_13); falseEdge -> [real: bb3, imaginary: bb5]; } diff --git a/tests/ui/thir-print/str-patterns.stdout b/tests/ui/thir-print/str-patterns.stdout index 8f8944ad4e09..6941ab15130f 100644 --- a/tests/ui/thir-print/str-patterns.stdout +++ b/tests/ui/thir-print/str-patterns.stdout @@ -9,18 +9,25 @@ Thir { ty: &'{erased} str, span: $DIR/str-patterns.rs:11:9: 11:16 (#0), extra: None, - kind: Constant { - value: Value { - ty: &'{erased} str, - valtree: Branch( - [ - 104_u8, - 101_u8, - 108_u8, - 108_u8, - 111_u8, - ], - ), + kind: Deref { + subpattern: Pat { + ty: str, + span: $DIR/str-patterns.rs:11:9: 11:16 (#0), + extra: None, + kind: Constant { + value: Value { + ty: str, + valtree: Branch( + [ + 104_u8, + 101_u8, + 108_u8, + 108_u8, + 111_u8, + ], + ), + }, + }, }, }, }, @@ -42,21 +49,28 @@ Thir { ascriptions: [], }, ), - kind: Constant { - value: Value { - ty: &'{erased} str, - valtree: Branch( - [ - 99_u8, - 111_u8, - 110_u8, - 115_u8, - 116_u8, - 97_u8, - 110_u8, - 116_u8, - ], - ), + kind: Deref { + subpattern: Pat { + ty: str, + span: $DIR/str-patterns.rs:12:9: 12:17 (#0), + extra: None, + kind: Constant { + value: Value { + ty: str, + valtree: Branch( + [ + 99_u8, + 111_u8, + 110_u8, + 115_u8, + 116_u8, + 97_u8, + 110_u8, + 116_u8, + ], + ), + }, + }, }, }, }, From e673bf57c224f2449f810911f94c909a7ffd5f8c Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 15 Jan 2026 16:44:14 +1100 Subject: [PATCH 059/146] Also remove `pat_ty` from `TestKind::ScalarEq` --- compiler/rustc_mir_build/src/builder/matches/mod.rs | 6 +----- compiler/rustc_mir_build/src/builder/matches/test.rs | 12 ++++-------- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index ddd70a3b597c..11a181cfa8ce 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -1345,11 +1345,7 @@ enum TestKind<'tcx> { }, /// Tests the place against a constant using scalar equality. - ScalarEq { - value: ty::Value<'tcx>, - /// Type of the corresponding pattern node. - pat_ty: Ty<'tcx>, - }, + ScalarEq { value: ty::Value<'tcx> }, /// Test whether the value falls within an inclusive or exclusive range. Range(Arc>), diff --git a/compiler/rustc_mir_build/src/builder/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index bab9f38f084d..5c3173a7b148 100644 --- a/compiler/rustc_mir_build/src/builder/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -42,7 +42,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { TestKind::StringEq { value } } TestableCase::Constant { value, kind: PatConstKind::Float | PatConstKind::Other } => { - TestKind::ScalarEq { value, pat_ty: match_pair.pattern_ty } + TestKind::ScalarEq { value } } TestableCase::Range(ref range) => { @@ -182,7 +182,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); } - TestKind::ScalarEq { value, pat_ty } => { + TestKind::ScalarEq { value } => { let tcx = self.tcx; let success_block = target_block(TestBranch::Success); let fail_block = target_block(TestBranch::Failure); @@ -191,12 +191,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let mut expected_value_operand = self.literal_operand(test.span, Const::from_ty_value(tcx, value)); - let mut actual_value_ty = pat_ty; let mut actual_value_place = place; - match pat_ty.kind() { + match value.ty.kind() { &ty::Pat(base, _) => { - assert_eq!(pat_ty, value.ty); assert!(base.is_trivially_pure_clone_copy()); let transmuted_place = self.temp(base, test.span); @@ -220,15 +218,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); actual_value_place = transmuted_place; - actual_value_ty = base; expected_value_operand = Operand::Copy(transmuted_expect); expected_value_ty = base; } _ => {} } - assert_eq!(expected_value_ty, actual_value_ty); - assert!(actual_value_ty.is_scalar()); + assert!(expected_value_ty.is_scalar()); self.compare( block, From 8dfb888812dd3727cb2edca012cfac220db1d061 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Fri, 16 Jan 2026 09:27:45 +0800 Subject: [PATCH 060/146] Disable `dump-ice-to-disk` on `i686-pc-windows-msvc` Sometimes the middle frames of the ICE backtrace becomes `` on `i686-pc-windows-msvc` which then makes this test flaky. --- tests/run-make/dump-ice-to-disk/rmake.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/run-make/dump-ice-to-disk/rmake.rs b/tests/run-make/dump-ice-to-disk/rmake.rs index 09a34cdeb5e7..319cbc6e0ca8 100644 --- a/tests/run-make/dump-ice-to-disk/rmake.rs +++ b/tests/run-make/dump-ice-to-disk/rmake.rs @@ -18,13 +18,16 @@ //! # Test history //! //! The previous rmake.rs iteration of this test was flaky for unknown reason on -//! `i686-pc-windows-gnu` *specifically*, so assertion failures in this test was made extremely -//! verbose to help diagnose why the ICE messages was different. It appears that backtraces on -//! `i686-pc-windows-gnu` specifically are quite unpredictable in how many backtrace frames are -//! involved. +//! `i686-pc-windows-gnu`, so assertion failures in this test was made extremely verbose to help +//! diagnose why the ICE messages was different. It appears that backtraces on `i686-pc-windows-gnu` +//! specifically are quite unpredictable in how many backtrace frames are involved. +//! +//! Disabled on `i686-pc-windows-msvc` as well, because sometimes the middle portion of the ICE +//! backtrace becomes ``. //@ ignore-cross-compile (exercising ICE dump on host) //@ ignore-i686-pc-windows-gnu (unwind mechanism produces unpredictable backtraces) +//@ ignore-i686-pc-windows-msvc (sometimes partial backtrace becomes ``) use std::cell::OnceCell; use std::path::{Path, PathBuf}; From bfd1a9a86f5f344f09a550338eeb08c29458015c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 16 Jan 2026 02:14:01 +0000 Subject: [PATCH 061/146] Use default_field_values more in `Resolver` Provide `const` functions to get around lack of `const Default` for `FxHash*` types. Use default field values in `Resolver` more. --- compiler/rustc_data_structures/src/fx.rs | 15 +++++ compiler/rustc_resolve/src/lib.rs | 77 ++++++++---------------- 2 files changed, 41 insertions(+), 51 deletions(-) diff --git a/compiler/rustc_data_structures/src/fx.rs b/compiler/rustc_data_structures/src/fx.rs index c1a5c8ebc764..026ec5c230ec 100644 --- a/compiler/rustc_data_structures/src/fx.rs +++ b/compiler/rustc_data_structures/src/fx.rs @@ -28,3 +28,18 @@ macro_rules! define_stable_id_collections { pub type $entry_name<'a, T> = $crate::fx::IndexEntry<'a, $key, T>; }; } + +pub mod default { + use super::{FxBuildHasher, FxHashMap, FxHashSet}; + + // FIXME: These two functions will become unnecessary after + // lands and we start using the corresponding + // `rustc-hash` version. After that we can use `Default::default()` instead. + pub const fn fx_hash_map() -> FxHashMap { + FxHashMap::with_hasher(FxBuildHasher) + } + + pub const fn fx_hash_set() -> FxHashSet { + FxHashSet::with_hasher(FxBuildHasher) + } +} diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 2c22aacb3241..b7efff929f70 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -45,7 +45,7 @@ use rustc_ast::{ self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs, NodeId, Path, attr, }; -use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; +use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default}; use rustc_data_structures::intern::Interned; use rustc_data_structures::steal::Steal; use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard}; @@ -1129,7 +1129,7 @@ pub struct Resolver<'ra, 'tcx> { /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax. /// Used for hints during error reporting. - field_visibility_spans: FxHashMap>, + field_visibility_spans: FxHashMap> = default::fx_hash_map(), /// All imports known to succeed or fail. determined_imports: Vec> = Vec::new(), @@ -1146,7 +1146,7 @@ pub struct Resolver<'ra, 'tcx> { /// Resolutions for import nodes, which have multiple resolutions in different namespaces. import_res_map: NodeMap>>, /// An import will be inserted into this map if it has been used. - import_use_map: FxHashMap, Used>, + import_use_map: FxHashMap, Used> = default::fx_hash_map(), /// Resolutions for labels (node IDs of their corresponding blocks or loops). label_res_map: NodeMap, /// Resolutions for lifetimes. @@ -1190,7 +1190,7 @@ pub struct Resolver<'ra, 'tcx> { glob_map: FxIndexMap>, glob_error: Option = None, visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(), - used_imports: FxHashSet, + used_imports: FxHashSet = default::fx_hash_set(), maybe_unused_trait_imports: FxIndexSet, /// Privacy errors are delayed until the end in order to deduplicate them. @@ -1206,30 +1206,30 @@ pub struct Resolver<'ra, 'tcx> { /// When a type is re-exported that has an inaccessible constructor because it has fields that /// are inaccessible from the import's scope, we mark that as the type won't be able to be built /// through the re-export. We use this information to extend the existing diagnostic. - inaccessible_ctor_reexport: FxHashMap, + inaccessible_ctor_reexport: FxHashMap = default::fx_hash_map(), arenas: &'ra ResolverArenas<'ra>, dummy_decl: Decl<'ra>, builtin_type_decls: FxHashMap>, builtin_attr_decls: FxHashMap>, registered_tool_decls: FxHashMap>, - macro_names: FxHashSet, - builtin_macros: FxHashMap, + macro_names: FxHashSet = default::fx_hash_set(), + builtin_macros: FxHashMap = default::fx_hash_map(), registered_tools: &'tcx RegisteredTools, macro_use_prelude: FxIndexMap>, /// Eagerly populated map of all local macro definitions. - local_macro_map: FxHashMap, + local_macro_map: FxHashMap = default::fx_hash_map(), /// Lazily populated cache of macro definitions loaded from external crates. extern_macro_map: CacheRefCell>, dummy_ext_bang: Arc, dummy_ext_derive: Arc, non_macro_attr: &'ra MacroData, - local_macro_def_scopes: FxHashMap>, - ast_transform_scopes: FxHashMap>, + local_macro_def_scopes: FxHashMap> = default::fx_hash_map(), + ast_transform_scopes: FxHashMap> = default::fx_hash_map(), unused_macros: FxIndexMap, /// A map from the macro to all its potentially unused arms. unused_macro_rules: FxIndexMap>, - proc_macro_stubs: FxHashSet, + proc_macro_stubs: FxHashSet = default::fx_hash_set(), /// Traces collected during macro resolution and validated when it's complete. single_segment_macro_resolutions: CmRefCell, Option>, Option)>>, @@ -1239,23 +1239,23 @@ pub struct Resolver<'ra, 'tcx> { /// `derive(Copy)` marks items they are applied to so they are treated specially later. /// Derive macros cannot modify the item themselves and have to store the markers in the global /// context, so they attach the markers to derive container IDs using this resolver table. - containers_deriving_copy: FxHashSet, + containers_deriving_copy: FxHashSet = default::fx_hash_set(), /// Parent scopes in which the macros were invoked. /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere. - invocation_parent_scopes: FxHashMap>, + invocation_parent_scopes: FxHashMap> = default::fx_hash_map(), /// `macro_rules` scopes *produced* by expanding the macro invocations, /// include all the `macro_rules` items and other invocations generated by them. - output_macro_rules_scopes: FxHashMap>, + output_macro_rules_scopes: FxHashMap> = default::fx_hash_map(), /// `macro_rules` scopes produced by `macro_rules` item definitions. - macro_rules_scopes: FxHashMap>, + macro_rules_scopes: FxHashMap> = default::fx_hash_map(), /// Helper attributes that are in scope for the given expansion. - helper_attrs: FxHashMap)>>, + helper_attrs: FxHashMap)>> = default::fx_hash_map(), /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute /// with the given `ExpnId`. - derive_data: FxHashMap, + derive_data: FxHashMap = default::fx_hash_map(), /// Avoid duplicated errors for "name already defined". - name_already_seen: FxHashMap, + name_already_seen: FxHashMap = default::fx_hash_map(), potentially_unused_imports: Vec> = Vec::new(), @@ -1275,14 +1275,14 @@ pub struct Resolver<'ra, 'tcx> { disambiguator: DisambiguatorState, /// Indices of unnamed struct or variant fields with unresolved attributes. - placeholder_field_indices: FxHashMap, + placeholder_field_indices: FxHashMap = default::fx_hash_map(), /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId` /// we know what parent node that fragment should be attached to thanks to this table, /// and how the `impl Trait` fragments were introduced. invocation_parents: FxHashMap, /// Amount of lifetime parameters for each item in the crate. - item_generics_num_lifetimes: FxHashMap, + item_generics_num_lifetimes: FxHashMap = default::fx_hash_map(), delegation_fn_sigs: LocalDefIdMap, delegation_infos: LocalDefIdMap, @@ -1293,7 +1293,7 @@ pub struct Resolver<'ra, 'tcx> { proc_macros: Vec = Vec::new(), confused_type_with_std_module: FxIndexMap, /// Whether lifetime elision was successful. - lifetime_elision_allowed: FxHashSet, + lifetime_elision_allowed: FxHashSet = default::fx_hash_set(), /// Names of items that were stripped out via cfg with their corresponding cfg meta item. stripped_cfg_items: Vec> = Vec::new(), @@ -1304,19 +1304,19 @@ pub struct Resolver<'ra, 'tcx> { all_macro_rules: UnordSet, /// Invocation ids of all glob delegations. - glob_delegation_invoc_ids: FxHashSet, + glob_delegation_invoc_ids: FxHashSet = default::fx_hash_set(), /// Analogue of module `unexpanded_invocations` but in trait impls, excluding glob delegations. /// Needed because glob delegations wait for all other neighboring macros to expand. - impl_unexpanded_invocations: FxHashMap>, + impl_unexpanded_invocations: FxHashMap> = default::fx_hash_map(), /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations. /// Needed because glob delegations exclude explicitly defined names. - impl_binding_keys: FxHashMap>, + impl_binding_keys: FxHashMap> = default::fx_hash_map(), /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo` /// could be a crate that wasn't imported. For diagnostics use only. current_crate_outer_attr_insert_span: Span, - mods_with_parse_errors: FxHashSet, + mods_with_parse_errors: FxHashSet = default::fx_hash_set(), /// Whether `Resolver::register_macros_for_all_crates` has been called once already, as we /// don't need to run it more than once. @@ -1325,7 +1325,7 @@ pub struct Resolver<'ra, 'tcx> { // Stores pre-expansion and pre-placeholder-fragment-insertion names for `impl Trait` types // that were encountered during resolution. These names are used to generate item names // for APITs, so we don't want to leak details of resolution into these names. - impl_trait_names: FxHashMap, + impl_trait_names: FxHashMap = default::fx_hash_map(), } /// This provides memory for the rest of the crate. The `'ra` lifetime that is @@ -1598,12 +1598,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { field_names: Default::default(), field_defaults: Default::default(), - field_visibility_spans: FxHashMap::default(), pat_span_map: Default::default(), partial_res_map: Default::default(), import_res_map: Default::default(), - import_use_map: Default::default(), label_res_map: Default::default(), lifetimes_res_map: Default::default(), extra_lifetime_params_map: Default::default(), @@ -1616,12 +1614,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { local_module_map, extern_module_map: Default::default(), block_map: Default::default(), - ast_transform_scopes: FxHashMap::default(), glob_map: Default::default(), - used_imports: FxHashSet::default(), maybe_unused_trait_imports: Default::default(), - inaccessible_ctor_reexport: Default::default(), arenas, dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT), @@ -1649,52 +1644,32 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { (*ident, decl) }) .collect(), - macro_names: FxHashSet::default(), - builtin_macros: Default::default(), registered_tools, macro_use_prelude: Default::default(), - local_macro_map: Default::default(), extern_macro_map: Default::default(), dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)), dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)), non_macro_attr: arenas .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))), - invocation_parent_scopes: Default::default(), - output_macro_rules_scopes: Default::default(), - macro_rules_scopes: Default::default(), - helper_attrs: Default::default(), - derive_data: Default::default(), - local_macro_def_scopes: FxHashMap::default(), - name_already_seen: FxHashMap::default(), struct_constructors: Default::default(), unused_macros: Default::default(), unused_macro_rules: Default::default(), - proc_macro_stubs: Default::default(), single_segment_macro_resolutions: Default::default(), multi_segment_macro_resolutions: Default::default(), builtin_attrs: Default::default(), - containers_deriving_copy: Default::default(), lint_buffer: LintBuffer::default(), node_id_to_def_id, disambiguator: DisambiguatorState::new(), - placeholder_field_indices: Default::default(), invocation_parents, - item_generics_num_lifetimes: Default::default(), trait_impls: Default::default(), confused_type_with_std_module: Default::default(), - lifetime_elision_allowed: Default::default(), stripped_cfg_items: Default::default(), effective_visibilities: Default::default(), doc_link_resolutions: Default::default(), doc_link_traits_in_scope: Default::default(), all_macro_rules: Default::default(), delegation_fn_sigs: Default::default(), - glob_delegation_invoc_ids: Default::default(), - impl_unexpanded_invocations: Default::default(), - impl_binding_keys: Default::default(), current_crate_outer_attr_insert_span, - mods_with_parse_errors: Default::default(), - impl_trait_names: Default::default(), delegation_infos: Default::default(), .. }; From 2766ccfd4e419bae7d1b30d0f1e80d423bffee83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 16 Jan 2026 02:23:44 +0000 Subject: [PATCH 062/146] Make `UnordSet` and `UnordMap` `const Default` and use it in `Resolver` --- compiler/rustc_data_structures/src/lib.rs | 2 ++ compiler/rustc_data_structures/src/unord.rs | 10 +++--- compiler/rustc_resolve/src/lib.rs | 34 ++++++++------------- 3 files changed, 19 insertions(+), 27 deletions(-) diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index 41f6292e740b..ff1dd41c82cc 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -18,6 +18,8 @@ #![feature(assert_matches)] #![feature(auto_traits)] #![feature(cfg_select)] +#![feature(const_default)] +#![feature(const_trait_impl)] #![feature(core_intrinsics)] #![feature(dropck_eyepatch)] #![feature(extend_one)] diff --git a/compiler/rustc_data_structures/src/unord.rs b/compiler/rustc_data_structures/src/unord.rs index 3d44fb1fd48d..0a9a86d7a43b 100644 --- a/compiler/rustc_data_structures/src/unord.rs +++ b/compiler/rustc_data_structures/src/unord.rs @@ -8,7 +8,7 @@ use std::hash::Hash; use std::iter::{Product, Sum}; use std::ops::Index; -use rustc_hash::{FxHashMap, FxHashSet}; +use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; use rustc_macros::{Decodable_NoContext, Encodable_NoContext}; use crate::fingerprint::Fingerprint; @@ -241,10 +241,10 @@ pub struct UnordSet { impl UnordCollection for UnordSet {} -impl Default for UnordSet { +impl const Default for UnordSet { #[inline] fn default() -> Self { - Self { inner: FxHashSet::default() } + Self { inner: FxHashSet::with_hasher(FxBuildHasher) } } } @@ -438,10 +438,10 @@ pub struct UnordMap { impl UnordCollection for UnordMap {} -impl Default for UnordMap { +impl const Default for UnordMap { #[inline] fn default() -> Self { - Self { inner: FxHashMap::default() } + Self { inner: FxHashMap::with_hasher(FxBuildHasher) } } } diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index b7efff929f70..c31cec482351 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -13,6 +13,8 @@ #![feature(arbitrary_self_types)] #![feature(assert_matches)] #![feature(box_patterns)] +#![feature(const_default)] +#![feature(const_trait_impl)] #![feature(control_flow_into_value)] #![feature(decl_macro)] #![feature(default_field_values)] @@ -1113,7 +1115,7 @@ pub struct Resolver<'ra, 'tcx> { tcx: TyCtxt<'tcx>, /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`. - expn_that_defined: UnordMap, + expn_that_defined: UnordMap = Default::default(), graph_root: Module<'ra>, @@ -1124,8 +1126,8 @@ pub struct Resolver<'ra, 'tcx> { extern_prelude: FxIndexMap>, /// N.B., this is used only for better diagnostics, not name resolution itself. - field_names: LocalDefIdMap>, - field_defaults: LocalDefIdMap>, + field_names: LocalDefIdMap> = Default::default(), + field_defaults: LocalDefIdMap> = Default::default(), /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax. /// Used for hints during error reporting. @@ -1155,9 +1157,9 @@ pub struct Resolver<'ra, 'tcx> { extra_lifetime_params_map: NodeMap>, /// `CrateNum` resolutions of `extern crate` items. - extern_crate_map: UnordMap, - module_children: LocalDefIdMap>, - ambig_module_children: LocalDefIdMap>, + extern_crate_map: UnordMap = Default::default(), + module_children: LocalDefIdMap> = Default::default(), + ambig_module_children: LocalDefIdMap> = Default::default(), trait_map: NodeMap>, /// A map from nodes to anonymous modules. @@ -1264,7 +1266,7 @@ pub struct Resolver<'ra, 'tcx> { /// Table for mapping struct IDs into struct constructor IDs, /// it's not used during normal resolution, only for better error reporting. /// Also includes of list of each fields visibility - struct_constructors: LocalDefIdMap<(Res, Visibility, Vec>)>, + struct_constructors: LocalDefIdMap<(Res, Visibility, Vec>)> = Default::default(), lint_buffer: LintBuffer, @@ -1283,8 +1285,8 @@ pub struct Resolver<'ra, 'tcx> { /// Amount of lifetime parameters for each item in the crate. item_generics_num_lifetimes: FxHashMap = default::fx_hash_map(), - delegation_fn_sigs: LocalDefIdMap, - delegation_infos: LocalDefIdMap, + delegation_fn_sigs: LocalDefIdMap = Default::default(), + delegation_infos: LocalDefIdMap = Default::default(), main_def: Option = None, trait_impls: FxIndexMap>, @@ -1301,7 +1303,7 @@ pub struct Resolver<'ra, 'tcx> { effective_visibilities: EffectiveVisibilities, doc_link_resolutions: FxIndexMap, doc_link_traits_in_scope: FxIndexMap>, - all_macro_rules: UnordSet, + all_macro_rules: UnordSet = Default::default(), /// Invocation ids of all glob delegations. glob_delegation_invoc_ids: FxHashSet = default::fx_hash_set(), @@ -1587,8 +1589,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let mut resolver = Resolver { tcx, - expn_that_defined: Default::default(), - // The outermost module has def ID 0; this is not reflected in the // AST. graph_root, @@ -1596,18 +1596,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { prelude: None, extern_prelude, - field_names: Default::default(), - field_defaults: Default::default(), - pat_span_map: Default::default(), partial_res_map: Default::default(), import_res_map: Default::default(), label_res_map: Default::default(), lifetimes_res_map: Default::default(), extra_lifetime_params_map: Default::default(), - extern_crate_map: Default::default(), - module_children: Default::default(), - ambig_module_children: Default::default(), trait_map: NodeMap::default(), empty_module, local_modules, @@ -1651,7 +1645,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)), non_macro_attr: arenas .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))), - struct_constructors: Default::default(), unused_macros: Default::default(), unused_macro_rules: Default::default(), single_segment_macro_resolutions: Default::default(), @@ -1667,10 +1660,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { effective_visibilities: Default::default(), doc_link_resolutions: Default::default(), doc_link_traits_in_scope: Default::default(), - all_macro_rules: Default::default(), - delegation_fn_sigs: Default::default(), current_crate_outer_attr_insert_span, - delegation_infos: Default::default(), .. }; From dd4d60f701ae8bf43fb10f69260b8ffb07faa6be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 16 Jan 2026 02:28:49 +0000 Subject: [PATCH 063/146] Provide default field in `Resolver` for `NodeMap` fields --- compiler/rustc_resolve/src/lib.rs | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index c31cec482351..cd4d738663d4 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1141,26 +1141,26 @@ pub struct Resolver<'ra, 'tcx> { // Spans for local variables found during pattern resolution. // Used for suggestions during error reporting. - pat_span_map: NodeMap, + pat_span_map: NodeMap = Default::default(), /// Resolutions for nodes that have a single resolution. - partial_res_map: NodeMap, + partial_res_map: NodeMap = Default::default(), /// Resolutions for import nodes, which have multiple resolutions in different namespaces. - import_res_map: NodeMap>>, + import_res_map: NodeMap>> = Default::default(), /// An import will be inserted into this map if it has been used. import_use_map: FxHashMap, Used> = default::fx_hash_map(), /// Resolutions for labels (node IDs of their corresponding blocks or loops). - label_res_map: NodeMap, + label_res_map: NodeMap = Default::default(), /// Resolutions for lifetimes. - lifetimes_res_map: NodeMap, + lifetimes_res_map: NodeMap = Default::default(), /// Lifetime parameters that lowering will have to introduce. - extra_lifetime_params_map: NodeMap>, + extra_lifetime_params_map: NodeMap> = Default::default(), /// `CrateNum` resolutions of `extern crate` items. extern_crate_map: UnordMap = Default::default(), module_children: LocalDefIdMap> = Default::default(), ambig_module_children: LocalDefIdMap> = Default::default(), - trait_map: NodeMap>, + trait_map: NodeMap> = Default::default(), /// A map from nodes to anonymous modules. /// Anonymous modules are pseudo-modules that are implicitly created around items @@ -1176,7 +1176,7 @@ pub struct Resolver<'ra, 'tcx> { /// /// There will be an anonymous module created around `g` with the ID of the /// entry block for `f`. - block_map: NodeMap>, + block_map: NodeMap> = Default::default(), /// A fake module that contains no definition and no prelude. Used so that /// some AST passes can generate identifiers that only resolve to local or /// lang items. @@ -1596,18 +1596,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { prelude: None, extern_prelude, - pat_span_map: Default::default(), - partial_res_map: Default::default(), - import_res_map: Default::default(), - label_res_map: Default::default(), - lifetimes_res_map: Default::default(), - extra_lifetime_params_map: Default::default(), - trait_map: NodeMap::default(), empty_module, local_modules, local_module_map, extern_module_map: Default::default(), - block_map: Default::default(), glob_map: Default::default(), maybe_unused_trait_imports: Default::default(), From 664e19bc3a68c88dfa433fefe39a8e0338315eb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 16 Jan 2026 02:34:19 +0000 Subject: [PATCH 064/146] Make `DisambiguatorState` `const`-buildable --- compiler/rustc_hir/src/definitions.rs | 2 +- compiler/rustc_resolve/src/lib.rs | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index 01f84c90ec7a..5e361891f6d0 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -103,7 +103,7 @@ pub struct DisambiguatorState { } impl DisambiguatorState { - pub fn new() -> Self { + pub const fn new() -> Self { Self { next: Default::default() } } diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index cd4d738663d4..3bee1efba886 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1237,7 +1237,7 @@ pub struct Resolver<'ra, 'tcx> { CmRefCell, Option>, Option)>>, multi_segment_macro_resolutions: CmRefCell, Span, MacroKind, ParentScope<'ra>, Option, Namespace)>>, - builtin_attrs: Vec<(Ident, ParentScope<'ra>)>, + builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(), /// `derive(Copy)` marks items they are applied to so they are treated specially later. /// Derive macros cannot modify the item themselves and have to store the markers in the global /// context, so they attach the markers to derive container IDs using this resolver table. @@ -1274,7 +1274,7 @@ pub struct Resolver<'ra, 'tcx> { node_id_to_def_id: NodeMap>, - disambiguator: DisambiguatorState, + disambiguator: DisambiguatorState = DisambiguatorState::new(), /// Indices of unnamed struct or variant fields with unresolved attributes. placeholder_field_indices: FxHashMap = default::fx_hash_map(), @@ -1641,10 +1641,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { unused_macro_rules: Default::default(), single_segment_macro_resolutions: Default::default(), multi_segment_macro_resolutions: Default::default(), - builtin_attrs: Default::default(), lint_buffer: LintBuffer::default(), node_id_to_def_id, - disambiguator: DisambiguatorState::new(), invocation_parents, trait_impls: Default::default(), confused_type_with_std_module: Default::default(), From 2b139b786ee2bf21b8250f6dfb800a85ad2f8db3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 16 Jan 2026 02:36:07 +0000 Subject: [PATCH 065/146] `prelude` is already defaulted --- compiler/rustc_resolve/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 3bee1efba886..d62635759981 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1593,7 +1593,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { // AST. graph_root, assert_speculative: false, // Only set/cleared in Resolver::resolve_imports for now - prelude: None, extern_prelude, empty_module, From 9f6e7473d6ac3e7e1596bef17cfbfda4e563ffc7 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 16 Jan 2026 14:54:14 +1100 Subject: [PATCH 066/146] Fix a typo. --- compiler/rustc_middle/src/query/plumbing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/query/plumbing.rs b/compiler/rustc_middle/src/query/plumbing.rs index 8d01d9482ed4..9300c942a525 100644 --- a/compiler/rustc_middle/src/query/plumbing.rs +++ b/compiler/rustc_middle/src/query/plumbing.rs @@ -278,7 +278,7 @@ macro_rules! define_callbacks { ($V) ); - /// This function takes `ProvidedValue` and coverts it to an erased `Value` by + /// This function takes `ProvidedValue` and converts it to an erased `Value` by /// allocating it on an arena if the query has the `arena_cache` modifier. The /// value is then erased and returned. This will happen when computing the query /// using a provider or decoding a stored result. From 4c2e447027399f4ebe98563177c68831898c16e6 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 16 Jan 2026 14:54:48 +1100 Subject: [PATCH 067/146] Rename `fatal_cycle` as `cycle_fatal`. To be consistent with the closely related `cycle_stash` and `cycle_delay_bug`. --- compiler/rustc_macros/src/query.rs | 12 ++++----- compiler/rustc_middle/src/query/mod.rs | 28 ++++++++++----------- compiler/rustc_middle/src/query/plumbing.rs | 2 +- compiler/rustc_query_impl/src/plumbing.rs | 2 +- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_macros/src/query.rs b/compiler/rustc_macros/src/query.rs index 5d32950875ad..104e95277a1a 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -93,7 +93,7 @@ struct QueryModifiers { cache: Option<(Option, Block)>, /// A cycle error for this query aborting the compilation with a fatal error. - fatal_cycle: Option, + cycle_fatal: Option, /// A cycle error results in a delay_bug call cycle_delay_bug: Option, @@ -136,7 +136,7 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { let mut arena_cache = None; let mut cache = None; let mut desc = None; - let mut fatal_cycle = None; + let mut cycle_fatal = None; let mut cycle_delay_bug = None; let mut cycle_stash = None; let mut no_hash = None; @@ -189,8 +189,8 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { try_insert!(cache = (args, block)); } else if modifier == "arena_cache" { try_insert!(arena_cache = modifier); - } else if modifier == "fatal_cycle" { - try_insert!(fatal_cycle = modifier); + } else if modifier == "cycle_fatal" { + try_insert!(cycle_fatal = modifier); } else if modifier == "cycle_delay_bug" { try_insert!(cycle_delay_bug = modifier); } else if modifier == "cycle_stash" { @@ -220,7 +220,7 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { arena_cache, cache, desc, - fatal_cycle, + cycle_fatal, cycle_delay_bug, cycle_stash, no_hash, @@ -366,8 +366,8 @@ pub(super) fn rustc_queries(input: TokenStream) -> TokenStream { } passthrough!( - fatal_cycle, arena_cache, + cycle_fatal, cycle_delay_bug, cycle_stash, no_hash, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 5f40c36423b3..fc1bf78c82f3 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -28,7 +28,7 @@ //! - `desc { ... }`: Sets the human-readable description for diagnostics and profiling. Required for every query. //! - `arena_cache`: Use an arena for in-memory caching of the query result. //! - `cache_on_disk_if { ... }`: Cache the query result to disk if the provided block evaluates to true. -//! - `fatal_cycle`: If a dependency cycle is detected, abort compilation with a fatal error. +//! - `cycle_fatal`: If a dependency cycle is detected, abort compilation with a fatal error. //! - `cycle_delay_bug`: If a dependency cycle is detected, emit a delayed bug instead of aborting immediately. //! - `cycle_stash`: If a dependency cycle is detected, stash the error for later handling. //! - `no_hash`: Do not hash the query result for incremental compilation; just mark as dirty if recomputed. @@ -160,7 +160,7 @@ pub mod plumbing; // The result type of each query must implement `Clone`, and additionally // `ty::query::values::Value`, which produces an appropriate placeholder // (error) value if the query resulted in a query cycle. -// Queries marked with `fatal_cycle` do not need the latter implementation, +// Queries marked with `cycle_fatal` do not need the latter implementation, // as they will raise an fatal error on query cycles instead. rustc_queries! { /// This exists purely for testing the interactions between delayed bugs and incremental. @@ -584,7 +584,7 @@ rustc_queries! { } query is_panic_runtime(_: CrateNum) -> bool { - fatal_cycle + cycle_fatal desc { "checking if the crate is_panic_runtime" } separate_provide_extern } @@ -1315,7 +1315,7 @@ rustc_queries! { /// Return the set of (transitive) callees that may result in a recursive call to `key`, /// if we were able to walk all callees. query mir_callgraph_cyclic(key: LocalDefId) -> &'tcx Option> { - fatal_cycle + cycle_fatal arena_cache desc { |tcx| "computing (transitive) callees of `{}` that may recurse", @@ -1326,7 +1326,7 @@ rustc_queries! { /// Obtain all the calls into other local functions query mir_inliner_callees(key: ty::InstanceKind<'tcx>) -> &'tcx [(DefId, GenericArgsRef<'tcx>)] { - fatal_cycle + cycle_fatal desc { |tcx| "computing all local function calls in `{}`", tcx.def_path_str(key.def_id()), @@ -1822,31 +1822,31 @@ rustc_queries! { } query is_compiler_builtins(_: CrateNum) -> bool { - fatal_cycle + cycle_fatal desc { "checking if the crate is_compiler_builtins" } separate_provide_extern } query has_global_allocator(_: CrateNum) -> bool { // This query depends on untracked global state in CStore eval_always - fatal_cycle + cycle_fatal desc { "checking if the crate has_global_allocator" } separate_provide_extern } query has_alloc_error_handler(_: CrateNum) -> bool { // This query depends on untracked global state in CStore eval_always - fatal_cycle + cycle_fatal desc { "checking if the crate has_alloc_error_handler" } separate_provide_extern } query has_panic_handler(_: CrateNum) -> bool { - fatal_cycle + cycle_fatal desc { "checking if the crate has_panic_handler" } separate_provide_extern } query is_profiler_runtime(_: CrateNum) -> bool { - fatal_cycle + cycle_fatal desc { "checking if a crate is `#![profiler_runtime]`" } separate_provide_extern } @@ -1855,22 +1855,22 @@ rustc_queries! { cache_on_disk_if { true } } query required_panic_strategy(_: CrateNum) -> Option { - fatal_cycle + cycle_fatal desc { "getting a crate's required panic strategy" } separate_provide_extern } query panic_in_drop_strategy(_: CrateNum) -> PanicStrategy { - fatal_cycle + cycle_fatal desc { "getting a crate's configured panic-in-drop strategy" } separate_provide_extern } query is_no_builtins(_: CrateNum) -> bool { - fatal_cycle + cycle_fatal desc { "getting whether a crate has `#![no_builtins]`" } separate_provide_extern } query symbol_mangling_version(_: CrateNum) -> SymbolManglingVersion { - fatal_cycle + cycle_fatal desc { "getting a crate's symbol mangling version" } separate_provide_extern } diff --git a/compiler/rustc_middle/src/query/plumbing.rs b/compiler/rustc_middle/src/query/plumbing.rs index 9300c942a525..25c9a0a81ab4 100644 --- a/compiler/rustc_middle/src/query/plumbing.rs +++ b/compiler/rustc_middle/src/query/plumbing.rs @@ -532,7 +532,7 @@ macro_rules! define_feedable { // The result type of each query must implement `Clone`, and additionally // `ty::query::values::Value`, which produces an appropriate placeholder // (error) value if the query resulted in a query cycle. -// Queries marked with `fatal_cycle` do not need the latter implementation, +// Queries marked with `cycle_fatal` do not need the latter implementation, // as they will raise an fatal error on query cycles instead. mod sealed { diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 39b6fac4ebc0..c98affe0cb19 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -219,7 +219,7 @@ macro_rules! handle_cycle_error { ([]) => {{ rustc_query_system::HandleCycleError::Error }}; - ([(fatal_cycle) $($rest:tt)*]) => {{ + ([(cycle_fatal) $($rest:tt)*]) => {{ rustc_query_system::HandleCycleError::Fatal }}; ([(cycle_stash) $($rest:tt)*]) => {{ From 2e58d05a0a40533914aeaf11cf664ba41d070955 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 16 Jan 2026 15:51:13 +1100 Subject: [PATCH 068/146] Add test from #124901. Issue #124901 was an OOM caused by a query cycle. It was fixed by a complex change in PR #138672, but that PR did not add the test case. Let's add it now, because it's the only known reproducer of the OOM. --- tests/ui/resolve/query-cycle-issue-124901.rs | 24 +++++++++++++++++++ .../resolve/query-cycle-issue-124901.stderr | 9 +++++++ 2 files changed, 33 insertions(+) create mode 100644 tests/ui/resolve/query-cycle-issue-124901.rs create mode 100644 tests/ui/resolve/query-cycle-issue-124901.stderr diff --git a/tests/ui/resolve/query-cycle-issue-124901.rs b/tests/ui/resolve/query-cycle-issue-124901.rs new file mode 100644 index 000000000000..6cb1e58b6258 --- /dev/null +++ b/tests/ui/resolve/query-cycle-issue-124901.rs @@ -0,0 +1,24 @@ +//~ ERROR: cycle detected when looking up span for `Default` +trait Default { + type Id; + + fn intu(&self) -> &Self::Id; +} + +impl, U: Copy> Default for U { + default type Id = T; + fn intu(&self) -> &Self::Id { + self + } +} + +fn specialization(t: T) -> U { + *t.intu() +} + +use std::num::NonZero; + +fn main() { + let assert_eq = NonZero::>>(0); + assert_eq!(specialization, None); +} diff --git a/tests/ui/resolve/query-cycle-issue-124901.stderr b/tests/ui/resolve/query-cycle-issue-124901.stderr new file mode 100644 index 000000000000..9c1d7b1de33a --- /dev/null +++ b/tests/ui/resolve/query-cycle-issue-124901.stderr @@ -0,0 +1,9 @@ +error[E0391]: cycle detected when looking up span for `Default` + | + = note: ...which immediately requires looking up span for `Default` again + = note: cycle used when perform lints prior to AST lowering + = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0391`. From 8fa2f693bb566cd99aae6c057c890b1f2e42c773 Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Wed, 13 Aug 2025 13:05:07 +0200 Subject: [PATCH 069/146] Implement incremental caching for derive macro expansions --- Cargo.lock | 2 + compiler/rustc_ast/src/ast.rs | 3 +- compiler/rustc_ast/src/token.rs | 16 +- compiler/rustc_ast/src/tokenstream.rs | 20 +-- compiler/rustc_expand/Cargo.toml | 2 + compiler/rustc_expand/src/lib.rs | 4 + compiler/rustc_expand/src/proc_macro.rs | 168 ++++++++++++++---- .../src/persist/dirty_clean.rs | 36 ++-- compiler/rustc_interface/src/passes.rs | 1 + compiler/rustc_middle/src/arena.rs | 1 + .../rustc_middle/src/dep_graph/dep_node.rs | 6 + compiler/rustc_middle/src/dep_graph/mod.rs | 2 +- compiler/rustc_middle/src/query/erase.rs | 5 + compiler/rustc_middle/src/query/keys.rs | 16 +- compiler/rustc_middle/src/query/mod.rs | 14 +- .../rustc_middle/src/query/on_disk_cache.rs | 7 + .../rustc_query_system/src/dep_graph/graph.rs | 12 ++ compiler/rustc_session/src/options.rs | 2 + compiler/rustc_span/src/hygiene.rs | 6 + .../auxiliary/derive_nothing.rs | 15 ++ .../proc_macro_unchanged.rs | 18 ++ 21 files changed, 284 insertions(+), 72 deletions(-) create mode 100644 tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs create mode 100644 tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs diff --git a/Cargo.lock b/Cargo.lock index bf28939ac87b..d83bdf767e5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3887,11 +3887,13 @@ dependencies = [ "rustc_lexer", "rustc_lint_defs", "rustc_macros", + "rustc_middle", "rustc_parse", "rustc_proc_macro", "rustc_serialize", "rustc_session", "rustc_span", + "scoped-tls", "smallvec", "thin-vec", "tracing", diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 079238b12bfd..b2b1f997ac54 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -3348,7 +3348,8 @@ impl UseTree { /// Distinguishes between `Attribute`s that decorate items and Attributes that /// are contained as statements within items. These two cases need to be /// distinguished for pretty-printing. -#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic, Walkable)] +#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy)] +#[derive(Encodable, Decodable, HashStable_Generic, Walkable)] pub enum AttrStyle { Outer, Inner, diff --git a/compiler/rustc_ast/src/token.rs b/compiler/rustc_ast/src/token.rs index accf4d181632..453e7443d324 100644 --- a/compiler/rustc_ast/src/token.rs +++ b/compiler/rustc_ast/src/token.rs @@ -40,13 +40,13 @@ impl DocFragmentKind { } } -#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, Debug, HashStable_Generic)] pub enum CommentKind { Line, Block, } -#[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)] pub enum InvisibleOrigin { // From the expansion of a metavariable in a declarative macro. MetaVar(MetaVarKind), @@ -123,7 +123,7 @@ impl fmt::Display for MetaVarKind { /// Describes how a sequence of token trees is delimited. /// Cannot use `proc_macro::Delimiter` directly because this /// structure should implement some additional traits. -#[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)] pub enum Delimiter { /// `( ... )` Parenthesis, @@ -186,7 +186,7 @@ impl Delimiter { // type. This means that float literals like `1f32` are classified by this type // as `Int`. Only upon conversion to `ast::LitKind` will such a literal be // given the `Float` kind. -#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, Debug, HashStable_Generic)] pub enum LitKind { Bool, // AST only, must never appear in a `Token` Byte, @@ -203,7 +203,7 @@ pub enum LitKind { } /// A literal token. -#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, Debug, HashStable_Generic)] pub struct Lit { pub kind: LitKind, pub symbol: Symbol, @@ -349,7 +349,7 @@ fn ident_can_begin_type(name: Symbol, span: Span, is_raw: IdentIsRaw) -> bool { .contains(&name) } -#[derive(PartialEq, Encodable, Decodable, Debug, Copy, Clone, HashStable_Generic)] +#[derive(PartialEq, Eq, Encodable, Decodable, Hash, Debug, Copy, Clone, HashStable_Generic)] pub enum IdentIsRaw { No, Yes, @@ -376,7 +376,7 @@ impl From for IdentIsRaw { } } -#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, Debug, HashStable_Generic)] pub enum TokenKind { /* Expression-operator symbols. */ /// `=` @@ -526,7 +526,7 @@ pub enum TokenKind { Eof, } -#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, Debug, HashStable_Generic)] pub struct Token { pub kind: TokenKind, pub span: Span, diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index 4111182c3b7d..e346a56bcf40 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -5,6 +5,7 @@ //! which are themselves a single [`Token`] or a `Delimited` subsequence of tokens. use std::borrow::Cow; +use std::hash::Hash; use std::ops::Range; use std::sync::Arc; use std::{cmp, fmt, iter, mem}; @@ -22,7 +23,7 @@ use crate::token::{self, Delimiter, Token, TokenKind}; use crate::{AttrVec, Attribute}; /// Part of a `TokenStream`. -#[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)] pub enum TokenTree { /// A single token. Should never be `OpenDelim` or `CloseDelim`, because /// delimiters are implicitly represented by `Delimited`. @@ -538,7 +539,7 @@ pub struct AttrsTarget { /// compound token. Used for conversions to `proc_macro::Spacing`. Also used to /// guide pretty-printing, which is where the `JointHidden` value (which isn't /// part of `proc_macro::Spacing`) comes in useful. -#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)] pub enum Spacing { /// The token cannot join with the following token to form a compound /// token. @@ -595,7 +596,7 @@ pub enum Spacing { } /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s. -#[derive(Clone, Debug, Default, Encodable, Decodable)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Encodable, Decodable)] pub struct TokenStream(pub(crate) Arc>); impl TokenStream { @@ -811,14 +812,6 @@ impl TokenStream { } } -impl PartialEq for TokenStream { - fn eq(&self, other: &TokenStream) -> bool { - self.iter().eq(other.iter()) - } -} - -impl Eq for TokenStream {} - impl FromIterator for TokenStream { fn from_iter>(iter: I) -> Self { TokenStream::new(iter.into_iter().collect::>()) @@ -970,7 +963,8 @@ impl TokenCursor { } } -#[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic, Walkable)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +#[derive(Encodable, Decodable, HashStable_Generic, Walkable)] pub struct DelimSpan { pub open: Span, pub close: Span, @@ -994,7 +988,7 @@ impl DelimSpan { } } -#[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)] pub struct DelimSpacing { pub open: Spacing, pub close: Spacing, diff --git a/compiler/rustc_expand/Cargo.toml b/compiler/rustc_expand/Cargo.toml index f897833d85c0..a18506c42afc 100644 --- a/compiler/rustc_expand/Cargo.toml +++ b/compiler/rustc_expand/Cargo.toml @@ -21,6 +21,7 @@ rustc_hir = { path = "../rustc_hir" } rustc_lexer = { path = "../rustc_lexer" } rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_macros = { path = "../rustc_macros" } +rustc_middle = { path = "../rustc_middle" } rustc_parse = { path = "../rustc_parse" } # We must use the proc_macro version that we will compile proc-macros against, # not the one from our own sysroot. @@ -28,6 +29,7 @@ rustc_proc_macro = { path = "../rustc_proc_macro" } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } +scoped-tls = "1.0" smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } thin-vec = "0.2.12" tracing = "0.1" diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index 5eefa4bcdf6b..5ac7ec0cd035 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -29,4 +29,8 @@ pub mod module; #[allow(rustc::untranslatable_diagnostic)] pub mod proc_macro; +pub fn provide(providers: &mut rustc_middle::query::Providers) { + providers.derive_macro_expansion = proc_macro::provide_derive_macro_expansion; +} + rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 9bfda8764f55..5e7a272bcba4 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -1,9 +1,11 @@ use rustc_ast::tokenstream::TokenStream; use rustc_errors::ErrorGuaranteed; +use rustc_middle::ty::{self, TyCtxt}; use rustc_parse::parser::{ForceCollect, Parser}; +use rustc_session::Session; use rustc_session::config::ProcMacroExecutionStrategy; -use rustc_span::Span; use rustc_span::profiling::SpannedEventArgRecorder; +use rustc_span::{LocalExpnId, Span}; use {rustc_ast as ast, rustc_proc_macro as pm}; use crate::base::{self, *}; @@ -30,9 +32,9 @@ impl pm::bridge::server::MessagePipe for MessagePipe { } } -fn exec_strategy(ecx: &ExtCtxt<'_>) -> impl pm::bridge::server::ExecutionStrategy + 'static { +fn exec_strategy(sess: &Session) -> impl pm::bridge::server::ExecutionStrategy + 'static { pm::bridge::server::MaybeCrossThread::>::new( - ecx.sess.opts.unstable_opts.proc_macro_execution_strategy + sess.opts.unstable_opts.proc_macro_execution_strategy == ProcMacroExecutionStrategy::CrossThread, ) } @@ -54,7 +56,7 @@ impl base::BangProcMacro for BangProcMacro { }); let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; - let strategy = exec_strategy(ecx); + let strategy = exec_strategy(ecx.sess); let server = proc_macro_server::Rustc::new(ecx); self.client.run(&strategy, server, input, proc_macro_backtrace).map_err(|e| { ecx.dcx().emit_err(errors::ProcMacroPanicked { @@ -85,7 +87,7 @@ impl base::AttrProcMacro for AttrProcMacro { }); let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; - let strategy = exec_strategy(ecx); + let strategy = exec_strategy(ecx.sess); let server = proc_macro_server::Rustc::new(ecx); self.client.run(&strategy, server, annotation, annotated, proc_macro_backtrace).map_err( |e| { @@ -101,7 +103,7 @@ impl base::AttrProcMacro for AttrProcMacro { } pub struct DeriveProcMacro { - pub client: pm::bridge::client::Client, + pub client: DeriveClient, } impl MultiItemModifier for DeriveProcMacro { @@ -113,6 +115,13 @@ impl MultiItemModifier for DeriveProcMacro { item: Annotatable, _is_derive_const: bool, ) -> ExpandResult, Annotatable> { + let _timer = ecx.sess.prof.generic_activity_with_arg_recorder( + "expand_derive_proc_macro_outer", + |recorder| { + recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span); + }, + ); + // We need special handling for statement items // (e.g. `fn foo() { #[derive(Debug)] struct Bar; }`) let is_stmt = matches!(item, Annotatable::Stmt(..)); @@ -123,36 +132,31 @@ impl MultiItemModifier for DeriveProcMacro { // altogether. See #73345. crate::base::ann_pretty_printing_compatibility_hack(&item, &ecx.sess.psess); let input = item.to_tokens(); - let stream = { - let _timer = - ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| { - recorder.record_arg_with_span( - ecx.sess.source_map(), - ecx.expansion_descr(), - span, - ); - }); - let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; - let strategy = exec_strategy(ecx); - let server = proc_macro_server::Rustc::new(ecx); - match self.client.run(&strategy, server, input, proc_macro_backtrace) { - Ok(stream) => stream, - Err(e) => { - ecx.dcx().emit_err({ - errors::ProcMacroDerivePanicked { - span, - message: e.as_str().map(|message| { - errors::ProcMacroDerivePanickedHelp { message: message.into() } - }), - } - }); - return ExpandResult::Ready(vec![]); - } - } + + let invoc_id = ecx.current_expansion.id; + + let res = if ecx.sess.opts.incremental.is_some() + && ecx.sess.opts.unstable_opts.cache_proc_macros + { + ty::tls::with(|tcx| { + let input = &*tcx.arena.alloc(input); + let key: (LocalExpnId, &TokenStream) = (invoc_id, input); + + QueryDeriveExpandCtx::enter(ecx, self.client, move || { + tcx.derive_macro_expansion(key).cloned() + }) + }) + } else { + expand_derive_macro(invoc_id, input, ecx, self.client) + }; + + let Ok(output) = res else { + // error will already have been emitted + return ExpandResult::Ready(vec![]); }; let error_count_before = ecx.dcx().err_count(); - let mut parser = Parser::new(&ecx.sess.psess, stream, Some("proc-macro derive")); + let mut parser = Parser::new(&ecx.sess.psess, output, Some("proc-macro derive")); let mut items = vec![]; loop { @@ -180,3 +184,101 @@ impl MultiItemModifier for DeriveProcMacro { ExpandResult::Ready(items) } } + +/// Provide a query for computing the output of a derive macro. +pub(super) fn provide_derive_macro_expansion<'tcx>( + tcx: TyCtxt<'tcx>, + key: (LocalExpnId, &'tcx TokenStream), +) -> Result<&'tcx TokenStream, ()> { + let (invoc_id, input) = key; + + // Make sure that we invalidate the query when the crate defining the proc macro changes + let _ = tcx.crate_hash(invoc_id.expn_data().macro_def_id.unwrap().krate); + + QueryDeriveExpandCtx::with(|ecx, client| { + expand_derive_macro(invoc_id, input.clone(), ecx, client).map(|ts| &*tcx.arena.alloc(ts)) + }) +} + +type DeriveClient = pm::bridge::client::Client; + +fn expand_derive_macro( + invoc_id: LocalExpnId, + input: TokenStream, + ecx: &mut ExtCtxt<'_>, + client: DeriveClient, +) -> Result { + let _timer = + ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| { + let invoc_expn_data = invoc_id.expn_data(); + let span = invoc_expn_data.call_site; + let event_arg = invoc_expn_data.kind.descr(); + recorder.record_arg_with_span(ecx.sess.source_map(), event_arg.clone(), span); + }); + + let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; + let strategy = exec_strategy(ecx.sess); + let server = proc_macro_server::Rustc::new(ecx); + + match client.run(&strategy, server, input, proc_macro_backtrace) { + Ok(stream) => Ok(stream), + Err(e) => { + let invoc_expn_data = invoc_id.expn_data(); + let span = invoc_expn_data.call_site; + ecx.dcx().emit_err({ + errors::ProcMacroDerivePanicked { + span, + message: e.as_str().map(|message| errors::ProcMacroDerivePanickedHelp { + message: message.into(), + }), + } + }); + Err(()) + } + } +} + +/// Stores the context necessary to expand a derive proc macro via a query. +struct QueryDeriveExpandCtx { + /// Type-erased version of `&mut ExtCtxt` + expansion_ctx: *mut (), + client: DeriveClient, +} + +impl QueryDeriveExpandCtx { + /// Store the extension context and the client into the thread local value. + /// It will be accessible via the `with` method while `f` is active. + fn enter(ecx: &mut ExtCtxt<'_>, client: DeriveClient, f: F) -> R + where + F: FnOnce() -> R, + { + // We need erasure to get rid of the lifetime + let ctx = Self { expansion_ctx: ecx as *mut _ as *mut (), client }; + DERIVE_EXPAND_CTX.set(&ctx, || f()) + } + + /// Accesses the thread local value of the derive expansion context. + /// Must be called while the `enter` function is active. + fn with(f: F) -> R + where + F: for<'a, 'b> FnOnce(&'b mut ExtCtxt<'a>, DeriveClient) -> R, + { + DERIVE_EXPAND_CTX.with(|ctx| { + let ectx = { + let casted = ctx.expansion_ctx.cast::>(); + // SAFETY: We can only get the value from `with` while the `enter` function + // is active (on the callstack), and that function's signature ensures that the + // lifetime is valid. + // If `with` is called at some other time, it will panic due to usage of + // `scoped_tls::with`. + unsafe { casted.as_mut().unwrap() } + }; + + f(ectx, ctx.client) + }) + } +} + +// When we invoke a query to expand a derive proc macro, we need to provide it with the expansion +// context and derive Client. We do that using a thread-local. +scoped_tls::scoped_thread_local!(static DERIVE_EXPAND_CTX: QueryDeriveExpandCtx); diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 64166255fa48..71fb18895246 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -26,7 +26,7 @@ use rustc_hir::def_id::LocalDefId; use rustc_hir::{ Attribute, ImplItemKind, ItemKind as HirItem, Node as HirNode, TraitItemKind, intravisit, }; -use rustc_middle::dep_graph::{DepNode, DepNodeExt, label_strs}; +use rustc_middle::dep_graph::{DepNode, DepNodeExt, dep_kind_from_label, label_strs}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_span::{Span, Symbol, sym}; @@ -357,17 +357,6 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { } } - fn assert_loaded_from_disk(&self, item_span: Span, dep_node: DepNode) { - debug!("assert_loaded_from_disk({:?})", dep_node); - - if !self.tcx.dep_graph.debug_was_loaded_from_disk(dep_node) { - let dep_node_str = self.dep_node_str(&dep_node); - self.tcx - .dcx() - .emit_err(errors::NotLoaded { span: item_span, dep_node_str: &dep_node_str }); - } - } - fn check_item(&mut self, item_id: LocalDefId) { let item_span = self.tcx.def_span(item_id.to_def_id()); let def_path_hash = self.tcx.def_path_hash(item_id.to_def_id()); @@ -385,8 +374,27 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { self.assert_dirty(item_span, dep_node); } for label in assertion.loaded_from_disk.items().into_sorted_stable_ord() { - let dep_node = DepNode::from_label_string(self.tcx, label, def_path_hash).unwrap(); - self.assert_loaded_from_disk(item_span, dep_node); + match DepNode::from_label_string(self.tcx, label, def_path_hash) { + Ok(dep_node) => { + if !self.tcx.dep_graph.debug_was_loaded_from_disk(dep_node) { + let dep_node_str = self.dep_node_str(&dep_node); + self.tcx.dcx().emit_err(errors::NotLoaded { + span: item_span, + dep_node_str: &dep_node_str, + }); + } + } + // Opaque/unit hash, we only know the dep kind + Err(()) => { + let dep_kind = dep_kind_from_label(label); + if !self.tcx.dep_graph.debug_dep_kind_was_loaded_from_disk(dep_kind) { + self.tcx.dcx().emit_err(errors::NotLoaded { + span: item_span, + dep_node_str: &label, + }); + } + } + } } } } diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 35ab202d4c27..12a6a616d64f 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -889,6 +889,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock = LazyLock::new(|| { providers.queries.env_var_os = env_var_os; limits::provide(&mut providers.queries); proc_macro_decls::provide(&mut providers.queries); + rustc_expand::provide(&mut providers.queries); rustc_const_eval::provide(providers); rustc_middle::hir::provide(&mut providers.queries); rustc_borrowck::provide(&mut providers.queries); diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index 4fa39eb83e9e..0bdc1bfd45ee 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -119,6 +119,7 @@ macro_rules! arena_types { [decode] specialization_graph: rustc_middle::traits::specialization_graph::Graph, [] crate_inherent_impls: rustc_middle::ty::CrateInherentImpls, [] hir_owner_nodes: rustc_hir::OwnerNodes<'tcx>, + [decode] token_stream: rustc_ast::tokenstream::TokenStream, ]); ) } diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 0c757a390ca0..3ee1db67911f 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -176,6 +176,12 @@ impl DepNodeExt for DepNode { } } +/// Maps a query label to its DepKind. Panics if a query with the given label does not exist. +pub fn dep_kind_from_label(label: &str) -> DepKind { + dep_kind_from_label_string(label) + .unwrap_or_else(|_| panic!("Query label {label} does not exist")) +} + impl<'tcx> DepNodeParams> for () { #[inline(always)] fn fingerprint_style() -> FingerprintStyle { diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index 781e3e442e64..b24ea4acc6b7 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -8,7 +8,7 @@ use crate::ty::{self, TyCtxt}; #[macro_use] mod dep_node; -pub use dep_node::{DepKind, DepNode, DepNodeExt, dep_kinds, label_strs}; +pub use dep_node::{DepKind, DepNode, DepNodeExt, dep_kind_from_label, dep_kinds, label_strs}; pub(crate) use dep_node::{make_compile_codegen_unit, make_compile_mono_item, make_metadata}; pub use rustc_query_system::dep_graph::debug::{DepNodeFilter, EdgeFilter}; pub use rustc_query_system::dep_graph::{ diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index 711a597d4603..940cc30c17e6 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -2,6 +2,7 @@ use std::ffi::OsStr; use std::intrinsics::transmute_unchecked; use std::mem::MaybeUninit; +use rustc_ast::tokenstream::TokenStream; use rustc_span::ErrorGuaranteed; use rustc_span::source_map::Spanned; @@ -188,6 +189,10 @@ impl EraseType >()]; } +impl EraseType for Result<&'_ TokenStream, ()> { + type Result = [u8; size_of::>()]; +} + impl EraseType for Option<&'_ T> { type Result = [u8; size_of::>()]; } diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 4d914c42cfc6..dd9ba4325545 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -2,11 +2,12 @@ use std::ffi::OsStr; +use rustc_ast::tokenstream::TokenStream; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModDefId, ModDefId}; use rustc_hir::hir_id::{HirId, OwnerId}; use rustc_query_system::dep_graph::DepNodeIndex; use rustc_query_system::query::{DefIdCache, DefaultCache, SingleCache, VecCache}; -use rustc_span::{DUMMY_SP, Ident, Span, Symbol}; +use rustc_span::{DUMMY_SP, Ident, LocalExpnId, Span, Symbol}; use crate::infer::canonical::CanonicalQueryInput; use crate::mir::mono::CollectionMode; @@ -616,6 +617,19 @@ impl Key for (LocalDefId, HirId) { } } +impl<'tcx> Key for (LocalExpnId, &'tcx TokenStream) { + type Cache = DefaultCache; + + fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { + self.0.expn_data().call_site + } + + #[inline(always)] + fn key_as_def_id(&self) -> Option { + None + } +} + impl<'tcx> Key for (ValidityRequirement, ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) { type Cache = DefaultCache; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 5f40c36423b3..9335afe760ae 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -70,6 +70,7 @@ use std::sync::Arc; use rustc_abi::Align; use rustc_arena::TypedArena; use rustc_ast::expand::allocator::AllocatorKind; +use rustc_ast::tokenstream::TokenStream; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::steal::Steal; @@ -96,7 +97,7 @@ use rustc_session::cstore::{ use rustc_session::lint::LintExpectationId; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::source_map::Spanned; -use rustc_span::{DUMMY_SP, Span, Symbol}; +use rustc_span::{DUMMY_SP, LocalExpnId, Span, Symbol}; use rustc_target::spec::PanicStrategy; use {rustc_abi as abi, rustc_ast as ast, rustc_hir as hir}; @@ -163,6 +164,17 @@ pub mod plumbing; // Queries marked with `fatal_cycle` do not need the latter implementation, // as they will raise an fatal error on query cycles instead. rustc_queries! { + /// Caches the expansion of a derive proc macro, e.g. `#[derive(Serialize)]`. + /// The key is: + /// - A unique key corresponding to the invocation of a macro. + /// - Token stream which serves as an input to the macro. + /// + /// The output is the token stream generated by the proc macro. + query derive_macro_expansion(key: (LocalExpnId, &'tcx TokenStream)) -> Result<&'tcx TokenStream, ()> { + desc { "expanding a derive (proc) macro" } + cache_on_disk_if { true } + } + /// This exists purely for testing the interactions between delayed bugs and incremental. query trigger_delayed_bug(key: DefId) { desc { "triggering a delayed bug for testing incremental" } diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index 29cceb708850..5ef0c2500e7a 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -785,6 +785,13 @@ impl<'a, 'tcx> Decodable> } } +impl<'a, 'tcx> Decodable> for &'tcx rustc_ast::tokenstream::TokenStream { + #[inline] + fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self { + RefDecodable::decode(d) + } +} + macro_rules! impl_ref_decoder { (<$tcx:tt> $($ty:ty,)*) => { $(impl<'a, $tcx> Decodable> for &$tcx [$ty] { diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 8634274c3a75..0b50d376b552 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -795,6 +795,18 @@ impl DepGraph { self.data.as_ref().unwrap().debug_loaded_from_disk.lock().contains(&dep_node) } + pub fn debug_dep_kind_was_loaded_from_disk(&self, dep_kind: DepKind) -> bool { + // We only check if we have a dep node corresponding to the given dep kind. + #[allow(rustc::potential_query_instability)] + self.data + .as_ref() + .unwrap() + .debug_loaded_from_disk + .lock() + .iter() + .any(|node| node.kind == dep_kind) + } + #[cfg(debug_assertions)] #[inline(always)] pub(crate) fn register_dep_node_debug_str(&self, dep_node: DepNode, debug_str_gen: F) diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 99ab13403812..96bdcf8beffb 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -2278,6 +2278,8 @@ options! { "set options for branch target identification and pointer authentication on AArch64"), build_sdylib_interface: bool = (false, parse_bool, [UNTRACKED], "whether the stable interface is being built"), + cache_proc_macros: bool = (false, parse_bool, [TRACKED], + "cache the results of derive proc macro invocations (potentially unsound!) (default: no"), cf_protection: CFProtection = (CFProtection::None, parse_cfprotection, [TRACKED], "instrument control-flow architecture protection"), check_cfg_all_expected: bool = (false, parse_bool, [UNTRACKED], diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 51da538de94d..d94d82835d65 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -1571,3 +1571,9 @@ impl HashStable for ExpnId { hash.hash_stable(ctx, hasher); } } + +impl HashStable for LocalExpnId { + fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { + self.to_expn_id().hash_stable(hcx, hasher); + } +} diff --git a/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs b/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs new file mode 100644 index 000000000000..24957b052856 --- /dev/null +++ b/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs @@ -0,0 +1,15 @@ +extern crate proc_macro; +use proc_macro::TokenStream; + +#[proc_macro_derive(Nothing)] +pub fn derive(_input: TokenStream) -> TokenStream { + return r#" + pub mod nothing_mod { + pub fn nothing() { + eprintln!("nothing"); + } + } + "# + .parse() + .unwrap(); +} diff --git a/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs b/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs new file mode 100644 index 000000000000..64364e31bc45 --- /dev/null +++ b/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs @@ -0,0 +1,18 @@ +// This test tests that derive proc macro execution is cached. + +//@ proc-macro:derive_nothing.rs +//@ revisions:rpass1 rpass2 +//@ compile-flags: -Zquery-dep-graph -Zcache-proc-macros +//@ ignore-backends: gcc + +#![feature(rustc_attrs)] + +#[macro_use] +extern crate derive_nothing; + +#[cfg(any(rpass1, rpass2))] +#[rustc_clean(cfg = "rpass2", loaded_from_disk = "derive_macro_expansion")] +#[derive(Nothing)] +pub struct Foo; + +fn main() {} From 48bcaf7ed1795ceb8b1e4ad4822e7e85e2cb5de5 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 16 Jan 2026 18:34:46 +1100 Subject: [PATCH 070/146] Revert the `QueryStackFrameExtra`/`QueryStackDeferred` split. PR #138672 introduced a complex and invasive split of `QueryStackFrame` to avoid a query cycle. This commit reverts that change because there is a much simpler change that fixes the problem, which will be in the next commit. --- compiler/rustc_middle/src/query/mod.rs | 2 +- compiler/rustc_middle/src/query/plumbing.rs | 2 +- compiler/rustc_middle/src/values.rs | 4 +- compiler/rustc_query_impl/src/lib.rs | 11 +- compiler/rustc_query_impl/src/plumbing.rs | 86 ++++-------- .../rustc_query_system/src/query/config.rs | 5 +- compiler/rustc_query_system/src/query/job.rs | 131 ++++++++---------- compiler/rustc_query_system/src/query/mod.rs | 129 ++++------------- .../rustc_query_system/src/query/plumbing.rs | 61 ++++---- 9 files changed, 145 insertions(+), 286 deletions(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index fc1bf78c82f3..285097832ba9 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -87,7 +87,7 @@ use rustc_index::IndexVec; use rustc_lint_defs::LintId; use rustc_macros::rustc_queries; use rustc_query_system::ich::StableHashingContext; -use rustc_query_system::query::{QueryMode, QueryStackDeferred, QueryState}; +use rustc_query_system::query::{QueryMode, QueryState}; use rustc_session::Limits; use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion}; use rustc_session::cstore::{ diff --git a/compiler/rustc_middle/src/query/plumbing.rs b/compiler/rustc_middle/src/query/plumbing.rs index 25c9a0a81ab4..df333e68add1 100644 --- a/compiler/rustc_middle/src/query/plumbing.rs +++ b/compiler/rustc_middle/src/query/plumbing.rs @@ -431,7 +431,7 @@ macro_rules! define_callbacks { #[derive(Default)] pub struct QueryStates<'tcx> { $( - pub $name: QueryState<$($K)*, QueryStackDeferred<'tcx>>, + pub $name: QueryState<$($K)*>, )* } diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/values.rs index bc73d36216ef..8d614a535498 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/values.rs @@ -88,7 +88,7 @@ impl<'tcx> Value> for Representability { if info.query.dep_kind == dep_kinds::representability && let Some(field_id) = info.query.def_id && let Some(field_id) = field_id.as_local() - && let Some(DefKind::Field) = info.query.info.def_kind + && let Some(DefKind::Field) = info.query.def_kind { let parent_id = tcx.parent(field_id.to_def_id()); let item_id = match tcx.def_kind(parent_id) { @@ -224,7 +224,7 @@ impl<'tcx, T> Value> for Result> continue; }; let frame_span = - frame.query.info.default_span(cycle[(i + 1) % cycle.len()].span); + frame.query.default_span(cycle[(i + 1) % cycle.len()].span); if frame_span.is_dummy() { continue; } diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index 6904af771f0c..f763b707aa23 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -21,8 +21,8 @@ use rustc_middle::ty::TyCtxt; use rustc_query_system::dep_graph::SerializedDepNodeIndex; use rustc_query_system::ich::StableHashingContext; use rustc_query_system::query::{ - CycleError, HashResult, QueryCache, QueryConfig, QueryMap, QueryMode, QueryStackDeferred, - QueryState, get_query_incr, get_query_non_incr, + CycleError, HashResult, QueryCache, QueryConfig, QueryMap, QueryMode, QueryState, + get_query_incr, get_query_non_incr, }; use rustc_query_system::{HandleCycleError, Value}; use rustc_span::{ErrorGuaranteed, Span}; @@ -79,10 +79,7 @@ where } #[inline(always)] - fn query_state<'a>( - self, - qcx: QueryCtxt<'tcx>, - ) -> &'a QueryState> + fn query_state<'a>(self, qcx: QueryCtxt<'tcx>) -> &'a QueryState where QueryCtxt<'tcx>: 'a, { @@ -91,7 +88,7 @@ where unsafe { &*(&qcx.tcx.query_system.states as *const QueryStates<'tcx>) .byte_add(self.dynamic.query_state) - .cast::>>() + .cast::>() } } diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index c98affe0cb19..ba1a358d2415 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -6,7 +6,6 @@ use std::num::NonZero; use rustc_data_structures::jobserver::Proxy; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_data_structures::sync::{DynSend, DynSync}; use rustc_data_structures::unord::UnordMap; use rustc_hashes::Hash64; use rustc_hir::limit::Limit; @@ -27,8 +26,8 @@ use rustc_middle::ty::{self, TyCtxt}; use rustc_query_system::dep_graph::{DepNodeParams, HasDepContext}; use rustc_query_system::ich::StableHashingContext; use rustc_query_system::query::{ - QueryCache, QueryConfig, QueryContext, QueryJobId, QueryMap, QuerySideEffect, - QueryStackDeferred, QueryStackFrame, QueryStackFrameExtra, force_query, + QueryCache, QueryConfig, QueryContext, QueryJobId, QueryMap, QuerySideEffect, QueryStackFrame, + force_query, }; use rustc_query_system::{QueryOverflow, QueryOverflowNote}; use rustc_serialize::{Decodable, Encodable}; @@ -67,9 +66,7 @@ impl<'tcx> HasDepContext for QueryCtxt<'tcx> { } } -impl<'tcx> QueryContext for QueryCtxt<'tcx> { - type QueryInfo = QueryStackDeferred<'tcx>; - +impl QueryContext for QueryCtxt<'_> { #[inline] fn jobserver_proxy(&self) -> &Proxy { &*self.jobserver_proxy @@ -98,10 +95,7 @@ impl<'tcx> QueryContext for QueryCtxt<'tcx> { /// Prefer passing `false` to `require_complete` to avoid potential deadlocks, /// especially when called from within a deadlock handler, unless a /// complete map is needed and no deadlock is possible at this call site. - fn collect_active_jobs( - self, - require_complete: bool, - ) -> Result>, QueryMap>> { + fn collect_active_jobs(self, require_complete: bool) -> Result { let mut jobs = QueryMap::default(); let mut complete = true; @@ -114,13 +108,6 @@ impl<'tcx> QueryContext for QueryCtxt<'tcx> { if complete { Ok(jobs) } else { Err(jobs) } } - fn lift_query_info( - self, - info: &QueryStackDeferred<'tcx>, - ) -> rustc_query_system::query::QueryStackFrameExtra { - info.extract() - } - // Interactions with on_disk_cache fn load_side_effect( self, @@ -181,10 +168,7 @@ impl<'tcx> QueryContext for QueryCtxt<'tcx> { self.sess.dcx().emit_fatal(QueryOverflow { span: info.job.span, - note: QueryOverflowNote { - desc: self.lift_query_info(&info.query.info).description, - depth, - }, + note: QueryOverflowNote { desc: info.query.description, depth }, suggested_limit, crate_name: self.crate_name(LOCAL_CRATE), }); @@ -321,17 +305,16 @@ macro_rules! should_ever_cache_on_disk { }; } -fn create_query_frame_extra<'tcx, K: Key + Copy + 'tcx>( - (tcx, key, kind, name, do_describe): ( - TyCtxt<'tcx>, - K, - DepKind, - &'static str, - fn(TyCtxt<'tcx>, K) -> String, - ), -) -> QueryStackFrameExtra { - let def_id = key.key_as_def_id(); - +pub(crate) fn create_query_frame< + 'tcx, + K: Copy + Key + for<'a> HashStable>, +>( + tcx: TyCtxt<'tcx>, + do_describe: fn(TyCtxt<'tcx>, K) -> String, + key: K, + kind: DepKind, + name: &'static str, +) -> QueryStackFrame { // If reduced queries are requested, we may be printing a query stack due // to a panic. Avoid using `default_span` and `def_kind` in that case. let reduce_queries = with_reduced_queries(); @@ -343,6 +326,7 @@ fn create_query_frame_extra<'tcx, K: Key + Copy + 'tcx>( } else { description }; + let span = if kind == dep_graph::dep_kinds::def_span || reduce_queries { // The `def_span` query is used to calculate `default_span`, // so exit to avoid infinite recursion. @@ -351,41 +335,25 @@ fn create_query_frame_extra<'tcx, K: Key + Copy + 'tcx>( Some(key.default_span(tcx)) }; + let def_id = key.key_as_def_id(); + let def_kind = if kind == dep_graph::dep_kinds::def_kind || reduce_queries { // Try to avoid infinite recursion. None } else { def_id.and_then(|def_id| def_id.as_local()).map(|def_id| tcx.def_kind(def_id)) }; - QueryStackFrameExtra::new(description, span, def_kind) -} -pub(crate) fn create_query_frame< - 'tcx, - K: Copy + DynSend + DynSync + Key + for<'a> HashStable> + 'tcx, ->( - tcx: TyCtxt<'tcx>, - do_describe: fn(TyCtxt<'tcx>, K) -> String, - key: K, - kind: DepKind, - name: &'static str, -) -> QueryStackFrame> { - let def_id = key.key_as_def_id(); - - let hash = || { - tcx.with_stable_hashing_context(|mut hcx| { - let mut hasher = StableHasher::new(); - kind.as_usize().hash_stable(&mut hcx, &mut hasher); - key.hash_stable(&mut hcx, &mut hasher); - hasher.finish::() - }) - }; let def_id_for_ty_in_cycle = key.def_id_for_ty_in_cycle(); - let info = - QueryStackDeferred::new((tcx, key, kind, name, do_describe), create_query_frame_extra); + let hash = tcx.with_stable_hashing_context(|mut hcx| { + let mut hasher = StableHasher::new(); + kind.as_usize().hash_stable(&mut hcx, &mut hasher); + key.hash_stable(&mut hcx, &mut hasher); + hasher.finish::() + }); - QueryStackFrame::new(info, kind, hash, def_id, def_id_for_ty_in_cycle) + QueryStackFrame::new(description, span, def_id, def_kind, kind, def_id_for_ty_in_cycle, hash) } pub(crate) fn encode_query_results<'a, 'tcx, Q>( @@ -737,7 +705,7 @@ macro_rules! define_queries { pub(crate) fn collect_active_jobs<'tcx>( tcx: TyCtxt<'tcx>, - qmap: &mut QueryMap>, + qmap: &mut QueryMap, require_complete: bool, ) -> Option<()> { let make_query = |tcx, key| { @@ -821,7 +789,7 @@ macro_rules! define_queries { // These arrays are used for iteration and can't be indexed by `DepKind`. const COLLECT_ACTIVE_JOBS: &[ - for<'tcx> fn(TyCtxt<'tcx>, &mut QueryMap>, bool) -> Option<()> + for<'tcx> fn(TyCtxt<'tcx>, &mut QueryMap, bool) -> Option<()> ] = &[$(query_impl::$name::collect_active_jobs),*]; diff --git a/compiler/rustc_query_system/src/query/config.rs b/compiler/rustc_query_system/src/query/config.rs index e508eadb73b0..371b896400a5 100644 --- a/compiler/rustc_query_system/src/query/config.rs +++ b/compiler/rustc_query_system/src/query/config.rs @@ -6,7 +6,6 @@ use std::hash::Hash; use rustc_data_structures::fingerprint::Fingerprint; use rustc_span::ErrorGuaranteed; -use super::QueryStackFrameExtra; use crate::dep_graph::{DepKind, DepNode, DepNodeParams, SerializedDepNodeIndex}; use crate::error::HandleCycleError; use crate::ich::StableHashingContext; @@ -28,7 +27,7 @@ pub trait QueryConfig: Copy { fn format_value(self) -> fn(&Self::Value) -> String; // Don't use this method to access query results, instead use the methods on TyCtxt - fn query_state<'a>(self, tcx: Qcx) -> &'a QueryState + fn query_state<'a>(self, tcx: Qcx) -> &'a QueryState where Qcx: 'a; @@ -58,7 +57,7 @@ pub trait QueryConfig: Copy { fn value_from_cycle_error( self, tcx: Qcx::DepContext, - cycle_error: &CycleError, + cycle_error: &CycleError, guar: ErrorGuaranteed, ) -> Self::Value; diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 7d9b594d501f..4a9b6a0d557c 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -1,4 +1,3 @@ -use std::fmt::Debug; use std::hash::Hash; use std::io::Write; use std::iter; @@ -12,7 +11,6 @@ use rustc_hir::def::DefKind; use rustc_session::Session; use rustc_span::{DUMMY_SP, Span}; -use super::QueryStackFrameExtra; use crate::dep_graph::DepContext; use crate::error::CycleStack; use crate::query::plumbing::CycleError; @@ -20,54 +18,45 @@ use crate::query::{QueryContext, QueryStackFrame}; /// Represents a span and a query key. #[derive(Clone, Debug)] -pub struct QueryInfo { +pub struct QueryInfo { /// The span corresponding to the reason for which this query was required. pub span: Span, - pub query: QueryStackFrame, + pub query: QueryStackFrame, } -impl QueryInfo { - pub(crate) fn lift>( - &self, - qcx: Qcx, - ) -> QueryInfo { - QueryInfo { span: self.span, query: self.query.lift(qcx) } - } -} - -pub type QueryMap = FxHashMap>; +pub type QueryMap = FxHashMap; /// A value uniquely identifying an active query job. #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct QueryJobId(pub NonZero); impl QueryJobId { - fn query(self, map: &QueryMap) -> QueryStackFrame { + fn query(self, map: &QueryMap) -> QueryStackFrame { map.get(&self).unwrap().query.clone() } - fn span(self, map: &QueryMap) -> Span { + fn span(self, map: &QueryMap) -> Span { map.get(&self).unwrap().job.span } - fn parent(self, map: &QueryMap) -> Option { + fn parent(self, map: &QueryMap) -> Option { map.get(&self).unwrap().job.parent } - fn latch(self, map: &QueryMap) -> Option<&QueryLatch> { + fn latch(self, map: &QueryMap) -> Option<&QueryLatch> { map.get(&self).unwrap().job.latch.as_ref() } } #[derive(Clone, Debug)] -pub struct QueryJobInfo { - pub query: QueryStackFrame, - pub job: QueryJob, +pub struct QueryJobInfo { + pub query: QueryStackFrame, + pub job: QueryJob, } /// Represents an active query job. #[derive(Debug)] -pub struct QueryJob { +pub struct QueryJob { pub id: QueryJobId, /// The span corresponding to the reason for which this query was required. @@ -77,23 +66,23 @@ pub struct QueryJob { pub parent: Option, /// The latch that is used to wait on this job. - latch: Option>, + latch: Option, } -impl Clone for QueryJob { +impl Clone for QueryJob { fn clone(&self) -> Self { Self { id: self.id, span: self.span, parent: self.parent, latch: self.latch.clone() } } } -impl QueryJob { +impl QueryJob { /// Creates a new query job. #[inline] pub fn new(id: QueryJobId, span: Span, parent: Option) -> Self { QueryJob { id, span, parent, latch: None } } - pub(super) fn latch(&mut self) -> QueryLatch { + pub(super) fn latch(&mut self) -> QueryLatch { if self.latch.is_none() { self.latch = Some(QueryLatch::new()); } @@ -113,12 +102,12 @@ impl QueryJob { } impl QueryJobId { - pub(super) fn find_cycle_in_stack( + pub(super) fn find_cycle_in_stack( &self, - query_map: QueryMap, + query_map: QueryMap, current_job: &Option, span: Span, - ) -> CycleError { + ) -> CycleError { // Find the waitee amongst `current_job` parents let mut cycle = Vec::new(); let mut current_job = Option::clone(current_job); @@ -152,7 +141,7 @@ impl QueryJobId { #[cold] #[inline(never)] - pub fn find_dep_kind_root(&self, query_map: QueryMap) -> (QueryJobInfo, usize) { + pub fn find_dep_kind_root(&self, query_map: QueryMap) -> (QueryJobInfo, usize) { let mut depth = 1; let info = query_map.get(&self).unwrap(); let dep_kind = info.query.dep_kind; @@ -172,31 +161,31 @@ impl QueryJobId { } #[derive(Debug)] -struct QueryWaiter { +struct QueryWaiter { query: Option, condvar: Condvar, span: Span, - cycle: Mutex>>, + cycle: Mutex>, } #[derive(Debug)] -struct QueryLatchInfo { +struct QueryLatchInfo { complete: bool, - waiters: Vec>>, + waiters: Vec>, } #[derive(Debug)] -pub(super) struct QueryLatch { - info: Arc>>, +pub(super) struct QueryLatch { + info: Arc>, } -impl Clone for QueryLatch { +impl Clone for QueryLatch { fn clone(&self) -> Self { Self { info: Arc::clone(&self.info) } } } -impl QueryLatch { +impl QueryLatch { fn new() -> Self { QueryLatch { info: Arc::new(Mutex::new(QueryLatchInfo { complete: false, waiters: Vec::new() })), @@ -209,7 +198,7 @@ impl QueryLatch { qcx: impl QueryContext, query: Option, span: Span, - ) -> Result<(), CycleError> { + ) -> Result<(), CycleError> { let waiter = Arc::new(QueryWaiter { query, span, cycle: Mutex::new(None), condvar: Condvar::new() }); self.wait_on_inner(qcx, &waiter); @@ -224,7 +213,7 @@ impl QueryLatch { } /// Awaits the caller on this latch by blocking the current thread. - fn wait_on_inner(&self, qcx: impl QueryContext, waiter: &Arc>) { + fn wait_on_inner(&self, qcx: impl QueryContext, waiter: &Arc) { let mut info = self.info.lock(); if !info.complete { // We push the waiter on to the `waiters` list. It can be accessed inside @@ -260,7 +249,7 @@ impl QueryLatch { /// Removes a single waiter from the list of waiters. /// This is used to break query cycles. - fn extract_waiter(&self, waiter: usize) -> Arc> { + fn extract_waiter(&self, waiter: usize) -> Arc { let mut info = self.info.lock(); debug_assert!(!info.complete); // Remove the waiter from the list of waiters @@ -280,11 +269,7 @@ type Waiter = (QueryJobId, usize); /// For visits of resumable waiters it returns Some(Some(Waiter)) which has the /// required information to resume the waiter. /// If all `visit` calls returns None, this function also returns None. -fn visit_waiters( - query_map: &QueryMap, - query: QueryJobId, - mut visit: F, -) -> Option> +fn visit_waiters(query_map: &QueryMap, query: QueryJobId, mut visit: F) -> Option> where F: FnMut(Span, QueryJobId) -> Option>, { @@ -314,8 +299,8 @@ where /// `span` is the reason for the `query` to execute. This is initially DUMMY_SP. /// If a cycle is detected, this initial value is replaced with the span causing /// the cycle. -fn cycle_check( - query_map: &QueryMap, +fn cycle_check( + query_map: &QueryMap, query: QueryJobId, span: Span, stack: &mut Vec<(Span, QueryJobId)>, @@ -354,8 +339,8 @@ fn cycle_check( /// Finds out if there's a path to the compiler root (aka. code which isn't in a query) /// from `query` without going through any of the queries in `visited`. /// This is achieved with a depth first search. -fn connected_to_root( - query_map: &QueryMap, +fn connected_to_root( + query_map: &QueryMap, query: QueryJobId, visited: &mut FxHashSet, ) -> bool { @@ -376,7 +361,7 @@ fn connected_to_root( } // Deterministically pick an query from a list -fn pick_query<'a, I: Clone, T, F>(query_map: &QueryMap, queries: &'a [T], f: F) -> &'a T +fn pick_query<'a, T, F>(query_map: &QueryMap, queries: &'a [T], f: F) -> &'a T where F: Fn(&T) -> (Span, QueryJobId), { @@ -401,10 +386,10 @@ where /// the function return true. /// If a cycle was not found, the starting query is removed from `jobs` and /// the function returns false. -fn remove_cycle( - query_map: &QueryMap, +fn remove_cycle( + query_map: &QueryMap, jobs: &mut Vec, - wakelist: &mut Vec>>, + wakelist: &mut Vec>, ) -> bool { let mut visited = FxHashSet::default(); let mut stack = Vec::new(); @@ -505,10 +490,7 @@ fn remove_cycle( /// uses a query latch and then resuming that waiter. /// There may be multiple cycles involved in a deadlock, so this searches /// all active queries for cycles before finally resuming all the waiters at once. -pub fn break_query_cycles( - query_map: QueryMap, - registry: &rustc_thread_pool::Registry, -) { +pub fn break_query_cycles(query_map: QueryMap, registry: &rustc_thread_pool::Registry) { let mut wakelist = Vec::new(); // It is OK per the comments: // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798854932 @@ -559,7 +541,7 @@ pub fn report_cycle<'a>( ) -> Diag<'a> { assert!(!stack.is_empty()); - let span = stack[0].query.info.default_span(stack[1 % stack.len()].span); + let span = stack[0].query.default_span(stack[1 % stack.len()].span); let mut cycle_stack = Vec::new(); @@ -568,31 +550,31 @@ pub fn report_cycle<'a>( for i in 1..stack.len() { let query = &stack[i].query; - let span = query.info.default_span(stack[(i + 1) % stack.len()].span); - cycle_stack.push(CycleStack { span, desc: query.info.description.to_owned() }); + let span = query.default_span(stack[(i + 1) % stack.len()].span); + cycle_stack.push(CycleStack { span, desc: query.description.to_owned() }); } let mut cycle_usage = None; if let Some((span, ref query)) = *usage { cycle_usage = Some(crate::error::CycleUsage { - span: query.info.default_span(span), - usage: query.info.description.to_string(), + span: query.default_span(span), + usage: query.description.to_string(), }); } - let alias = - if stack.iter().all(|entry| matches!(entry.query.info.def_kind, Some(DefKind::TyAlias))) { - Some(crate::error::Alias::Ty) - } else if stack.iter().all(|entry| entry.query.info.def_kind == Some(DefKind::TraitAlias)) { - Some(crate::error::Alias::Trait) - } else { - None - }; + let alias = if stack.iter().all(|entry| matches!(entry.query.def_kind, Some(DefKind::TyAlias))) + { + Some(crate::error::Alias::Ty) + } else if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TraitAlias)) { + Some(crate::error::Alias::Trait) + } else { + None + }; let cycle_diag = crate::error::Cycle { span, cycle_stack, - stack_bottom: stack[0].query.info.description.to_owned(), + stack_bottom: stack[0].query.description.to_owned(), alias, cycle_usage, stack_count, @@ -628,7 +610,6 @@ pub fn print_query_stack( let Some(query_info) = query_map.get(&query) else { break; }; - let query_extra = qcx.lift_query_info(&query_info.query.info); if Some(count_printed) < limit_frames || limit_frames.is_none() { // Only print to stderr as many stack frames as `num_frames` when present. // FIXME: needs translation @@ -636,7 +617,7 @@ pub fn print_query_stack( #[allow(rustc::untranslatable_diagnostic)] dcx.struct_failure_note(format!( "#{} [{:?}] {}", - count_printed, query_info.query.dep_kind, query_extra.description + count_printed, query_info.query.dep_kind, query_info.query.description )) .with_span(query_info.job.span) .emit(); @@ -649,7 +630,7 @@ pub fn print_query_stack( "#{} [{}] {}", count_total, qcx.dep_context().dep_kind_info(query_info.query.dep_kind).name, - query_extra.description + query_info.query.description ); } diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index ce3456d532e6..b524756d81b6 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -1,23 +1,4 @@ -mod plumbing; -use std::fmt::Debug; -use std::marker::PhantomData; -use std::mem::transmute; -use std::sync::Arc; - -pub use self::plumbing::*; - -mod job; -pub use self::job::{ - QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryMap, break_query_cycles, print_query_stack, - report_cycle, -}; - -mod caches; -pub use self::caches::{DefIdCache, DefaultCache, QueryCache, SingleCache, VecCache}; - -mod config; use rustc_data_structures::jobserver::Proxy; -use rustc_data_structures::sync::{DynSend, DynSync}; use rustc_errors::DiagInner; use rustc_hashes::Hash64; use rustc_hir::def::DefKind; @@ -25,66 +6,49 @@ use rustc_macros::{Decodable, Encodable}; use rustc_span::Span; use rustc_span::def_id::DefId; +pub use self::caches::{DefIdCache, DefaultCache, QueryCache, SingleCache, VecCache}; pub use self::config::{HashResult, QueryConfig}; +pub use self::job::{ + QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryMap, break_query_cycles, print_query_stack, + report_cycle, +}; +pub use self::plumbing::*; use crate::dep_graph::{DepKind, DepNodeIndex, HasDepContext, SerializedDepNodeIndex}; +mod caches; +mod config; +mod job; +mod plumbing; + /// Description of a frame in the query stack. /// /// This is mostly used in case of cycles for error reporting. #[derive(Clone, Debug)] -pub struct QueryStackFrame { - /// This field initially stores a `QueryStackDeferred` during collection, - /// but can later be changed to `QueryStackFrameExtra` containing concrete information - /// by calling `lift`. This is done so that collecting query does not need to invoke - /// queries, instead `lift` will call queries in a more appropriate location. - pub info: I, - +pub struct QueryStackFrame { + pub description: String, + span: Option, + pub def_id: Option, + pub def_kind: Option, + /// A def-id that is extracted from a `Ty` in a query key + pub def_id_for_ty_in_cycle: Option, pub dep_kind: DepKind, /// This hash is used to deterministically pick /// a query to remove cycles in the parallel compiler. hash: Hash64, - pub def_id: Option, - /// A def-id that is extracted from a `Ty` in a query key - pub def_id_for_ty_in_cycle: Option, } -impl QueryStackFrame { +impl QueryStackFrame { #[inline] pub fn new( - info: I, - dep_kind: DepKind, - hash: impl FnOnce() -> Hash64, + description: String, + span: Option, def_id: Option, + def_kind: Option, + dep_kind: DepKind, def_id_for_ty_in_cycle: Option, + hash: Hash64, ) -> Self { - Self { info, def_id, dep_kind, hash: hash(), def_id_for_ty_in_cycle } - } - - fn lift>( - &self, - qcx: Qcx, - ) -> QueryStackFrame { - QueryStackFrame { - info: qcx.lift_query_info(&self.info), - dep_kind: self.dep_kind, - hash: self.hash, - def_id: self.def_id, - def_id_for_ty_in_cycle: self.def_id_for_ty_in_cycle, - } - } -} - -#[derive(Clone, Debug)] -pub struct QueryStackFrameExtra { - pub description: String, - span: Option, - pub def_kind: Option, -} - -impl QueryStackFrameExtra { - #[inline] - pub fn new(description: String, span: Option, def_kind: Option) -> Self { - Self { description, span, def_kind } + Self { description, span, def_id, def_kind, def_id_for_ty_in_cycle, dep_kind, hash } } // FIXME(eddyb) Get more valid `Span`s on queries. @@ -97,40 +61,6 @@ impl QueryStackFrameExtra { } } -/// Track a 'side effect' for a particular query. -/// This is used to hold a closure which can create `QueryStackFrameExtra`. -#[derive(Clone)] -pub struct QueryStackDeferred<'tcx> { - _dummy: PhantomData<&'tcx ()>, - - // `extract` may contain references to 'tcx, but we can't tell drop checking that it won't - // access it in the destructor. - extract: Arc QueryStackFrameExtra + DynSync + DynSend>, -} - -impl<'tcx> QueryStackDeferred<'tcx> { - pub fn new( - context: C, - extract: fn(C) -> QueryStackFrameExtra, - ) -> Self { - let extract: Arc QueryStackFrameExtra + DynSync + DynSend + 'tcx> = - Arc::new(move || extract(context)); - // SAFETY: The `extract` closure does not access 'tcx in its destructor as the only - // captured variable is `context` which is Copy and cannot have a destructor. - Self { _dummy: PhantomData, extract: unsafe { transmute(extract) } } - } - - pub fn extract(&self) -> QueryStackFrameExtra { - (self.extract)() - } -} - -impl<'tcx> Debug for QueryStackDeferred<'tcx> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("QueryStackDeferred") - } -} - /// Tracks 'side effects' for a particular query. /// This struct is saved to disk along with the query result, /// and loaded from disk if we mark the query as green. @@ -150,8 +80,6 @@ pub enum QuerySideEffect { } pub trait QueryContext: HasDepContext { - type QueryInfo: Clone; - /// Gets a jobserver reference which is used to release then acquire /// a token while waiting on a query. fn jobserver_proxy(&self) -> &Proxy; @@ -161,12 +89,7 @@ pub trait QueryContext: HasDepContext { /// Get the query information from the TLS context. fn current_query_job(self) -> Option; - fn collect_active_jobs( - self, - require_complete: bool, - ) -> Result, QueryMap>; - - fn lift_query_info(self, info: &Self::QueryInfo) -> QueryStackFrameExtra; + fn collect_active_jobs(self, require_complete: bool) -> Result; /// Load a side effect associated to the node in the previous session. fn load_side_effect( diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index dea47c8fa787..fa5a94d65188 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -18,7 +18,7 @@ use rustc_errors::{Diag, FatalError, StashKey}; use rustc_span::{DUMMY_SP, Span}; use tracing::instrument; -use super::{QueryConfig, QueryStackFrameExtra}; +use super::QueryConfig; use crate::HandleCycleError; use crate::dep_graph::{DepContext, DepGraphData, DepNode, DepNodeIndex, DepNodeParams}; use crate::ich::StableHashingContext; @@ -31,23 +31,23 @@ fn equivalent_key(k: &K) -> impl Fn(&(K, V)) -> bool + '_ { move |x| x.0 == *k } -pub struct QueryState { - active: Sharded)>>, +pub struct QueryState { + active: Sharded>, } /// Indicates the state of a query for a given key in a query map. -enum QueryResult { +enum QueryResult { /// An already executing query. The query job can be used to await for its completion. - Started(QueryJob), + Started(QueryJob), /// The query panicked. Queries trying to wait on this will raise a fatal error which will /// silently panic. Poisoned, } -impl QueryResult { +impl QueryResult { /// Unwraps the query job expecting that it has started. - fn expect_job(self) -> QueryJob { + fn expect_job(self) -> QueryJob { match self { Self::Started(job) => job, Self::Poisoned => { @@ -57,7 +57,7 @@ impl QueryResult { } } -impl QueryState +impl QueryState where K: Eq + Hash + Copy + Debug, { @@ -68,13 +68,13 @@ where pub fn collect_active_jobs( &self, qcx: Qcx, - make_query: fn(Qcx, K) -> QueryStackFrame, - jobs: &mut QueryMap, + make_query: fn(Qcx, K) -> QueryStackFrame, + jobs: &mut QueryMap, require_complete: bool, ) -> Option<()> { let mut active = Vec::new(); - let mut collect = |iter: LockGuard<'_, HashTable<(K, QueryResult)>>| { + let mut collect = |iter: LockGuard<'_, HashTable<(K, QueryResult)>>| { for (k, v) in iter.iter() { if let QueryResult::Started(ref job) = *v { active.push((*k, job.clone())); @@ -105,19 +105,19 @@ where } } -impl Default for QueryState { - fn default() -> QueryState { +impl Default for QueryState { + fn default() -> QueryState { QueryState { active: Default::default() } } } /// A type representing the responsibility to execute the job in the `job` field. /// This will poison the relevant query if dropped. -struct JobOwner<'tcx, K, I> +struct JobOwner<'tcx, K> where K: Eq + Hash + Copy, { - state: &'tcx QueryState, + state: &'tcx QueryState, key: K, } @@ -159,7 +159,7 @@ where } Stash => { let guar = if let Some(root) = cycle_error.cycle.first() - && let Some(span) = root.query.info.span + && let Some(span) = root.query.span { error.stash(span, StashKey::Cycle).unwrap() } else { @@ -170,7 +170,7 @@ where } } -impl<'tcx, K, I> JobOwner<'tcx, K, I> +impl<'tcx, K> JobOwner<'tcx, K> where K: Eq + Hash + Copy, { @@ -207,7 +207,7 @@ where } } -impl<'tcx, K, I> Drop for JobOwner<'tcx, K, I> +impl<'tcx, K> Drop for JobOwner<'tcx, K> where K: Eq + Hash + Copy, { @@ -235,19 +235,10 @@ where } #[derive(Clone, Debug)] -pub struct CycleError { +pub struct CycleError { /// The query and related span that uses the cycle. - pub usage: Option<(Span, QueryStackFrame)>, - pub cycle: Vec>, -} - -impl CycleError { - fn lift>(&self, qcx: Qcx) -> CycleError { - CycleError { - usage: self.usage.as_ref().map(|(span, frame)| (*span, frame.lift(qcx))), - cycle: self.cycle.iter().map(|info| info.lift(qcx)).collect(), - } - } + pub usage: Option<(Span, QueryStackFrame)>, + pub cycle: Vec, } /// Checks whether there is already a value for this key in the in-memory @@ -284,10 +275,10 @@ where { // Ensure there was no errors collecting all active jobs. // We need the complete map to ensure we find a cycle to break. - let query_map = qcx.collect_active_jobs(false).ok().expect("failed to collect active queries"); + let query_map = qcx.collect_active_jobs(false).expect("failed to collect active queries"); let error = try_execute.find_cycle_in_stack(query_map, &qcx.current_query_job(), span); - (mk_cycle(query, qcx, error.lift(qcx)), None) + (mk_cycle(query, qcx, error), None) } #[inline(always)] @@ -296,7 +287,7 @@ fn wait_for_query( qcx: Qcx, span: Span, key: Q::Key, - latch: QueryLatch, + latch: QueryLatch, current: Option, ) -> (Q::Value, Option) where @@ -336,7 +327,7 @@ where (v, Some(index)) } - Err(cycle) => (mk_cycle(query, qcx, cycle.lift(qcx)), None), + Err(cycle) => (mk_cycle(query, qcx, cycle), None), } } @@ -414,7 +405,7 @@ where fn execute_job( query: Q, qcx: Qcx, - state: &QueryState, + state: &QueryState, key: Q::Key, key_hash: u64, id: QueryJobId, From 90e4a421623ed4e9f8e1985795456f734ec822a1 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 16 Jan 2026 19:18:16 +1100 Subject: [PATCH 071/146] Use `with_reduced_queries` to avoid query cycles. This changes the error message of `query-cycle-issue-124901.rs`, which doesn't matter much. --- compiler/rustc_query_impl/src/plumbing.rs | 10 ++++++---- tests/ui/resolve/query-cycle-issue-124901.rs | 2 +- tests/ui/resolve/query-cycle-issue-124901.stderr | 9 ++++++--- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index ba1a358d2415..67ab1114af62 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -327,21 +327,23 @@ pub(crate) fn create_query_frame< description }; - let span = if kind == dep_graph::dep_kinds::def_span || reduce_queries { + let span = if reduce_queries { // The `def_span` query is used to calculate `default_span`, // so exit to avoid infinite recursion. None } else { - Some(key.default_span(tcx)) + Some(tcx.with_reduced_queries(|| key.default_span(tcx))) }; let def_id = key.key_as_def_id(); - let def_kind = if kind == dep_graph::dep_kinds::def_kind || reduce_queries { + let def_kind = if reduce_queries { // Try to avoid infinite recursion. None } else { - def_id.and_then(|def_id| def_id.as_local()).map(|def_id| tcx.def_kind(def_id)) + def_id + .and_then(|def_id| def_id.as_local()) + .map(|def_id| tcx.with_reduced_queries(|| tcx.def_kind(def_id))) }; let def_id_for_ty_in_cycle = key.def_id_for_ty_in_cycle(); diff --git a/tests/ui/resolve/query-cycle-issue-124901.rs b/tests/ui/resolve/query-cycle-issue-124901.rs index 6cb1e58b6258..ccaee0e6bc6f 100644 --- a/tests/ui/resolve/query-cycle-issue-124901.rs +++ b/tests/ui/resolve/query-cycle-issue-124901.rs @@ -1,4 +1,4 @@ -//~ ERROR: cycle detected when looking up span for `Default` +//~ ERROR: cycle detected when getting HIR ID of `Default` trait Default { type Id; diff --git a/tests/ui/resolve/query-cycle-issue-124901.stderr b/tests/ui/resolve/query-cycle-issue-124901.stderr index 9c1d7b1de33a..3679925c6db4 100644 --- a/tests/ui/resolve/query-cycle-issue-124901.stderr +++ b/tests/ui/resolve/query-cycle-issue-124901.stderr @@ -1,7 +1,10 @@ -error[E0391]: cycle detected when looking up span for `Default` +error[E0391]: cycle detected when getting HIR ID of `Default` | - = note: ...which immediately requires looking up span for `Default` again - = note: cycle used when perform lints prior to AST lowering + = note: ...which requires getting the crate HIR... + = note: ...which requires perform lints prior to AST lowering... + = note: ...which requires looking up span for `Default`... + = note: ...which again requires getting HIR ID of `Default`, completing the cycle + = note: cycle used when getting the resolver for lowering = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error: aborting due to 1 previous error From db36c093ca556bc711c167f508c54bda6d3ba5af Mon Sep 17 00:00:00 2001 From: lcnr Date: Fri, 16 Jan 2026 10:21:06 +0100 Subject: [PATCH 072/146] remove lcnr from compiler review rotation --- triagebot.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/triagebot.toml b/triagebot.toml index 456fd696af43..e51622f1e5a9 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1458,7 +1458,6 @@ compiler = [ "@jieyouxu", "@jdonszelmann", "@JonathanBrouwer", - "@lcnr", "@madsmtm", "@mati865", "@Nadrieril", From 75445635784ebf4683a6d22aa8b9563469bd0e0c Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 15 Jan 2026 16:48:30 +0100 Subject: [PATCH 073/146] Only enable rustdoc `--generate-macro-expansion` option for stage builds higher than 1 --- src/bootstrap/src/core/build_steps/doc.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/doc.rs b/src/bootstrap/src/core/build_steps/doc.rs index fa36a6471cae..d8e8f65caa98 100644 --- a/src/bootstrap/src/core/build_steps/doc.rs +++ b/src/bootstrap/src/core/build_steps/doc.rs @@ -932,7 +932,13 @@ impl Step for Rustc { // see https://github.com/rust-lang/rust/pull/122066#issuecomment-1983049222 // If there is any bug, please comment out the next line. cargo.rustdocflag("--generate-link-to-definition"); - cargo.rustdocflag("--generate-macro-expansion"); + // FIXME: Currently, `--generate-macro-expansion` option is buggy in `beta` rustdoc. To + // allow CI to pass, we only enable the option in stage 2 and higher. + // cfg(bootstrap) + // ^ Adding this so it's not forgotten when the new release is done. + if builder.top_stage > 1 { + cargo.rustdocflag("--generate-macro-expansion"); + } compile::rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates); cargo.arg("-Zskip-rustdoc-fingerprint"); From 567b569e2bb131abcbf77eef7d98b7f50d47465a Mon Sep 17 00:00:00 2001 From: Clara Engler Date: Fri, 16 Jan 2026 10:39:35 +0100 Subject: [PATCH 074/146] time: Add saturating arithmetic for `SystemTime` This commit implements the following methods: * `SystemTime::saturating_add` * `SystemTime::saturating_sub` * `SystemTime::saturating_duration_since` The implementation of these methods is rather trivial, as the main logic lies behind the constants `SystemTime::MIN` and `SystemTime::MAX`. --- library/std/src/time.rs | 50 +++++++++++++++++++++++++++++++++++++++ library/std/tests/time.rs | 39 ++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+) diff --git a/library/std/src/time.rs b/library/std/src/time.rs index 3d09824019e3..1805d8926098 100644 --- a/library/std/src/time.rs +++ b/library/std/src/time.rs @@ -682,6 +682,56 @@ impl SystemTime { pub fn checked_sub(&self, duration: Duration) -> Option { self.0.checked_sub_duration(&duration).map(SystemTime) } + + /// Saturating [`SystemTime`] addition, computing `self + duration`, + /// returning [`SystemTime::MAX`] if overflow occurred. + /// + /// In the case that the `duration` is smaller than the time precision of + /// the operating system, `self` will be returned. + #[unstable(feature = "time_saturating_systemtime", issue = "151199")] + pub fn saturating_add(&self, duration: Duration) -> SystemTime { + self.checked_add(duration).unwrap_or(SystemTime::MAX) + } + + /// Saturating [`SystemTime`] subtraction, computing `self - duration`, + /// returning [`SystemTime::MIN`] if overflow occurred. + /// + /// In the case that the `duration` is smaller than the time precision of + /// the operating system, `self` will be returned. + #[unstable(feature = "time_saturating_systemtime", issue = "151199")] + pub fn saturating_sub(&self, duration: Duration) -> SystemTime { + self.checked_sub(duration).unwrap_or(SystemTime::MIN) + } + + /// Saturating computation of time elapsed from an earlier point in time, + /// returning [`Duration::ZERO`] in the case that `earlier` is later or + /// equal to `self`. + /// + /// # Examples + /// + /// ```no_run + /// #![feature(time_saturating_systemtime)] + /// use std::time::{Duration, SystemTime}; + /// + /// let now = SystemTime::now(); + /// let prev = now.saturating_sub(Duration::new(1, 0)); + /// + /// // now - prev should return non-zero. + /// assert_eq!(now.saturating_duration_since(prev), Duration::new(1, 0)); + /// assert!(now.duration_since(prev).is_ok()); + /// + /// // prev - now should return zero (and fail with the non-saturating). + /// assert_eq!(prev.saturating_duration_since(now), Duration::ZERO); + /// assert!(prev.duration_since(now).is_err()); + /// + /// // now - now should return zero (and work with the non-saturating). + /// assert_eq!(now.saturating_duration_since(now), Duration::ZERO); + /// assert!(now.duration_since(now).is_ok()); + /// ``` + #[unstable(feature = "time_saturating_systemtime", issue = "151199")] + pub fn saturating_duration_since(&self, earlier: SystemTime) -> Duration { + self.duration_since(earlier).unwrap_or(Duration::ZERO) + } } #[stable(feature = "time2", since = "1.8.0")] diff --git a/library/std/tests/time.rs b/library/std/tests/time.rs index 0ef89bb09c63..b73e7bc3962e 100644 --- a/library/std/tests/time.rs +++ b/library/std/tests/time.rs @@ -1,5 +1,6 @@ #![feature(duration_constants)] #![feature(time_systemtime_limits)] +#![feature(time_saturating_systemtime)] use std::fmt::Debug; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -269,3 +270,41 @@ fn system_time_max_min() { assert!(SystemTime::MIN.checked_add(MIN_INTERVAL).is_some()); assert!(SystemTime::MIN.checked_sub(MIN_INTERVAL).is_none()); } + +#[test] +fn system_time_saturating() { + // Perform saturating addition on SystemTime::MAX to see how it behaves. + assert_eq!(SystemTime::MAX.saturating_add(Duration::ZERO), SystemTime::MAX); + assert_eq!(SystemTime::MAX.saturating_add(Duration::new(1, 0)), SystemTime::MAX); + assert!(SystemTime::MAX.checked_add(Duration::new(1, 0)).is_none()); + assert_eq!( + SystemTime::MAX.saturating_sub(Duration::new(1, 0)), + SystemTime::MAX.checked_sub(Duration::new(1, 0)).unwrap() + ); + + // Perform saturating subtraction on SystemTime::MIn to see how it behaves. + assert_eq!(SystemTime::MIN.saturating_sub(Duration::ZERO), SystemTime::MIN); + assert_eq!(SystemTime::MIN.saturating_sub(Duration::new(1, 0)), SystemTime::MIN); + assert!(SystemTime::MIN.checked_sub(Duration::new(1, 0)).is_none()); + assert_eq!( + SystemTime::MIN.saturating_add(Duration::new(1, 0)), + SystemTime::MIN.checked_add(Duration::new(1, 0)).unwrap() + ); + + // Check saturating_duration_since with various constant values. + assert!(SystemTime::MAX.saturating_duration_since(SystemTime::MIN) >= Duration::ZERO); + assert_eq!(SystemTime::MAX.saturating_duration_since(SystemTime::MAX), Duration::ZERO); + assert!(SystemTime::MAX.duration_since(SystemTime::MAX).is_ok()); + assert_eq!(SystemTime::MIN.saturating_duration_since(SystemTime::MAX), Duration::ZERO); + assert!(SystemTime::MIN.duration_since(SystemTime::MAX).is_err()); + assert_eq!( + (SystemTime::UNIX_EPOCH + Duration::new(1, 0)) + .saturating_duration_since(SystemTime::UNIX_EPOCH), + Duration::new(1, 0) + ); + assert_eq!( + SystemTime::UNIX_EPOCH + .saturating_duration_since(SystemTime::UNIX_EPOCH + Duration::new(1, 0)), + Duration::ZERO + ); +} From d028956f11c85206f6d02c5dd38ccf5f4ce24b91 Mon Sep 17 00:00:00 2001 From: Georg Semmler Date: Fri, 16 Jan 2026 10:22:43 +0100 Subject: [PATCH 075/146] Add an additional help note to the ambiguity lint error This PR adds an additional help note to the ambiguity lint error output to ask users updating their dependencies. This hopefully helps with cases like https://github.com/rust-lang/rust/issues/149845 where newer crate versions are fixed. --- compiler/rustc_resolve/src/diagnostics.rs | 15 +++++++++++++++ compiler/rustc_resolve/src/errors.rs | 6 ++++++ tests/ui/imports/ambiguous-2.stderr | 4 ++++ tests/ui/imports/ambiguous-4.stderr | 4 ++++ .../ui/imports/glob-conflict-cross-crate-1.stderr | 8 ++++++++ .../ui/imports/glob-conflict-cross-crate-2.stderr | 4 ++++ .../ui/imports/glob-conflict-cross-crate-3.stderr | 4 ++++ tests/ui/imports/issue-114682-2.stderr | 8 ++++++++ tests/ui/imports/issue-114682-4.stderr | 4 ++++ tests/ui/imports/issue-114682-5.stderr | 4 ++++ tests/ui/imports/issue-114682-6.stderr | 4 ++++ 11 files changed, 65 insertions(+) diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index e9f94dedf522..4f371643ed24 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -2064,9 +2064,24 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { }; let (b1_note, b1_help_msgs) = could_refer_to(b1, scope1, ""); let (b2_note, b2_help_msgs) = could_refer_to(b2, scope2, " also"); + let help = if kind == AmbiguityKind::GlobVsGlob + && b1 + .parent_module + .and_then(|m| m.opt_def_id()) + .map(|d| !d.is_local()) + .unwrap_or_default() + { + Some(&[ + "consider updating this dependency to resolve this error", + "if updating the dependency does not resolve the problem report the problem to the author of the relevant crate", + ] as &[_]) + } else { + None + }; errors::Ambiguity { ident, + help, kind: kind.descr(), b1_note, b1_help_msgs, diff --git a/compiler/rustc_resolve/src/errors.rs b/compiler/rustc_resolve/src/errors.rs index 8880c2ba2666..d614219e8eab 100644 --- a/compiler/rustc_resolve/src/errors.rs +++ b/compiler/rustc_resolve/src/errors.rs @@ -1464,6 +1464,7 @@ pub(crate) struct UnknownDiagnosticAttributeTypoSugg { pub(crate) struct Ambiguity { pub ident: Ident, pub kind: &'static str, + pub help: Option<&'static [&'static str]>, pub b1_note: Spanned, pub b1_help_msgs: Vec, pub b2_note: Spanned, @@ -1476,6 +1477,11 @@ impl Ambiguity { diag.span_label(self.ident.span, "ambiguous name"); diag.note(format!("ambiguous because of {}", self.kind)); diag.span_note(self.b1_note.span, self.b1_note.node); + if let Some(help) = self.help { + for help in help { + diag.help(*help); + } + } for help_msg in self.b1_help_msgs { diag.help(help_msg); } diff --git a/tests/ui/imports/ambiguous-2.stderr b/tests/ui/imports/ambiguous-2.stderr index a0222099239a..5b12491af19d 100644 --- a/tests/ui/imports/ambiguous-2.stderr +++ b/tests/ui/imports/ambiguous-2.stderr @@ -12,6 +12,8 @@ note: `id` could refer to the function defined here | LL | pub use self::evp::*; | ^^^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `id` could also refer to the function defined here --> $DIR/auxiliary/../ambiguous-1.rs:15:13 | @@ -36,6 +38,8 @@ note: `id` could refer to the function defined here | LL | pub use self::evp::*; | ^^^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `id` could also refer to the function defined here --> $DIR/auxiliary/../ambiguous-1.rs:15:13 | diff --git a/tests/ui/imports/ambiguous-4.stderr b/tests/ui/imports/ambiguous-4.stderr index 6c1a2679fcae..691dd33a398a 100644 --- a/tests/ui/imports/ambiguous-4.stderr +++ b/tests/ui/imports/ambiguous-4.stderr @@ -12,6 +12,8 @@ note: `id` could refer to the function defined here | LL | pub use evp::*; | ^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `id` could also refer to the function defined here --> $DIR/auxiliary/../ambiguous-4-extern.rs:14:9 | @@ -36,6 +38,8 @@ note: `id` could refer to the function defined here | LL | pub use evp::*; | ^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `id` could also refer to the function defined here --> $DIR/auxiliary/../ambiguous-4-extern.rs:14:9 | diff --git a/tests/ui/imports/glob-conflict-cross-crate-1.stderr b/tests/ui/imports/glob-conflict-cross-crate-1.stderr index 440113653675..4eb27729b41a 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-1.stderr +++ b/tests/ui/imports/glob-conflict-cross-crate-1.stderr @@ -12,6 +12,8 @@ note: `f` could refer to the function defined here | LL | pub use m1::*; | ^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `f` could also refer to the function defined here --> $DIR/auxiliary/glob-conflict.rs:13:9 | @@ -33,6 +35,8 @@ note: `f` could refer to the function defined here | LL | pub use m1::*; | ^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `f` could also refer to the function defined here --> $DIR/auxiliary/glob-conflict.rs:13:9 | @@ -56,6 +60,8 @@ note: `f` could refer to the function defined here | LL | pub use m1::*; | ^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `f` could also refer to the function defined here --> $DIR/auxiliary/glob-conflict.rs:13:9 | @@ -78,6 +84,8 @@ note: `f` could refer to the function defined here | LL | pub use m1::*; | ^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `f` could also refer to the function defined here --> $DIR/auxiliary/glob-conflict.rs:13:9 | diff --git a/tests/ui/imports/glob-conflict-cross-crate-2.stderr b/tests/ui/imports/glob-conflict-cross-crate-2.stderr index 2ee519a364b3..6ff36477e45f 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-2.stderr +++ b/tests/ui/imports/glob-conflict-cross-crate-2.stderr @@ -12,6 +12,8 @@ note: `C` could refer to the type alias defined here | LL | pub use a::*; | ^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `C` could also refer to the type alias defined here --> $DIR/auxiliary/glob-conflict-cross-crate-2-extern.rs:10:9 | @@ -36,6 +38,8 @@ note: `C` could refer to the type alias defined here | LL | pub use a::*; | ^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `C` could also refer to the type alias defined here --> $DIR/auxiliary/glob-conflict-cross-crate-2-extern.rs:10:9 | diff --git a/tests/ui/imports/glob-conflict-cross-crate-3.stderr b/tests/ui/imports/glob-conflict-cross-crate-3.stderr index c7457efe866e..9b6867774ebe 100644 --- a/tests/ui/imports/glob-conflict-cross-crate-3.stderr +++ b/tests/ui/imports/glob-conflict-cross-crate-3.stderr @@ -12,6 +12,8 @@ note: `C` could refer to the type alias defined here | LL | pub use a::*; | ^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `C` could also refer to the type alias defined here --> $DIR/auxiliary/glob-conflict-cross-crate-2-extern.rs:10:9 | @@ -58,6 +60,8 @@ note: `C` could refer to the type alias defined here | LL | pub use a::*; | ^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `C` could also refer to the type alias defined here --> $DIR/auxiliary/glob-conflict-cross-crate-2-extern.rs:10:9 | diff --git a/tests/ui/imports/issue-114682-2.stderr b/tests/ui/imports/issue-114682-2.stderr index f93e4409f0c4..92fac9f0a424 100644 --- a/tests/ui/imports/issue-114682-2.stderr +++ b/tests/ui/imports/issue-114682-2.stderr @@ -12,6 +12,8 @@ note: `max` could refer to the type alias defined here | LL | pub use self::e::*; | ^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `max` could also refer to the module defined here --> $DIR/auxiliary/issue-114682-2-extern.rs:16:9 | @@ -33,6 +35,8 @@ note: `max` could refer to the type alias defined here | LL | pub use self::e::*; | ^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `max` could also refer to the module defined here --> $DIR/auxiliary/issue-114682-2-extern.rs:16:9 | @@ -56,6 +60,8 @@ note: `max` could refer to the type alias defined here | LL | pub use self::e::*; | ^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `max` could also refer to the module defined here --> $DIR/auxiliary/issue-114682-2-extern.rs:16:9 | @@ -78,6 +84,8 @@ note: `max` could refer to the type alias defined here | LL | pub use self::e::*; | ^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `max` could also refer to the module defined here --> $DIR/auxiliary/issue-114682-2-extern.rs:16:9 | diff --git a/tests/ui/imports/issue-114682-4.stderr b/tests/ui/imports/issue-114682-4.stderr index 12cb9ae95a42..5b012e21ea81 100644 --- a/tests/ui/imports/issue-114682-4.stderr +++ b/tests/ui/imports/issue-114682-4.stderr @@ -12,6 +12,8 @@ note: `Result` could refer to the type alias defined here | LL | pub use a::*; | ^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `Result` could also refer to the type alias defined here --> $DIR/auxiliary/issue-114682-4-extern.rs:10:9 | @@ -51,6 +53,8 @@ note: `Result` could refer to the type alias defined here | LL | pub use a::*; | ^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `Result` could also refer to the type alias defined here --> $DIR/auxiliary/issue-114682-4-extern.rs:10:9 | diff --git a/tests/ui/imports/issue-114682-5.stderr b/tests/ui/imports/issue-114682-5.stderr index 74b42e0990b7..5937f6f33117 100644 --- a/tests/ui/imports/issue-114682-5.stderr +++ b/tests/ui/imports/issue-114682-5.stderr @@ -40,6 +40,8 @@ note: `issue_114682_5_extern_1` could refer to the module defined here | LL | pub use crate::types::*; | ^^^^^^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `issue_114682_5_extern_1` could also refer to the crate defined here --> $DIR/auxiliary/issue-114682-5-extern-2.rs:7:13 | @@ -67,6 +69,8 @@ note: `issue_114682_5_extern_1` could refer to the module defined here | LL | pub use crate::types::*; | ^^^^^^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `issue_114682_5_extern_1` could also refer to the crate defined here --> $DIR/auxiliary/issue-114682-5-extern-2.rs:7:13 | diff --git a/tests/ui/imports/issue-114682-6.stderr b/tests/ui/imports/issue-114682-6.stderr index 37f8f6c16ff2..a2e9afb6eedb 100644 --- a/tests/ui/imports/issue-114682-6.stderr +++ b/tests/ui/imports/issue-114682-6.stderr @@ -12,6 +12,8 @@ note: `log` could refer to the function defined here | LL | pub use self::a::*; | ^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `log` could also refer to the function defined here --> $DIR/auxiliary/issue-114682-6-extern.rs:9:9 | @@ -36,6 +38,8 @@ note: `log` could refer to the function defined here | LL | pub use self::a::*; | ^^^^^^^ + = help: consider updating this dependency to resolve this error + = help: if updating the dependency does not resolve the problem report the problem to the author of the relevant crate note: `log` could also refer to the function defined here --> $DIR/auxiliary/issue-114682-6-extern.rs:9:9 | From e45e4a7cc65242f5dd2a750ec8860952b0f69949 Mon Sep 17 00:00:00 2001 From: cyrgani Date: Fri, 16 Jan 2026 13:31:38 +0000 Subject: [PATCH 076/146] delete weird `fd_read` feature --- library/std/src/sys/net/connection/socket/windows.rs | 1 - src/doc/unstable-book/src/library-features/fd-read.md | 5 ----- 2 files changed, 6 deletions(-) delete mode 100644 src/doc/unstable-book/src/library-features/fd-read.md diff --git a/library/std/src/sys/net/connection/socket/windows.rs b/library/std/src/sys/net/connection/socket/windows.rs index 3f99249efc47..b23fb9c09f87 100644 --- a/library/std/src/sys/net/connection/socket/windows.rs +++ b/library/std/src/sys/net/connection/socket/windows.rs @@ -451,7 +451,6 @@ impl Socket { } } -#[unstable(reason = "not public", issue = "none", feature = "fd_read")] impl<'a> Read for &'a Socket { fn read(&mut self, buf: &mut [u8]) -> io::Result { (**self).read(buf) diff --git a/src/doc/unstable-book/src/library-features/fd-read.md b/src/doc/unstable-book/src/library-features/fd-read.md deleted file mode 100644 index e78d4330abfc..000000000000 --- a/src/doc/unstable-book/src/library-features/fd-read.md +++ /dev/null @@ -1,5 +0,0 @@ -# `fd_read` - -This feature is internal to the Rust compiler and is not intended for general use. - ------------------------- From f13b1549cee9d2c7e47084f9e8d57f8fbec45382 Mon Sep 17 00:00:00 2001 From: cyrgani Date: Fri, 16 Jan 2026 13:32:24 +0000 Subject: [PATCH 077/146] remove `reason = "recently added"` from `#[unstable(...)]` --- library/core/src/iter/adapters/array_chunks.rs | 12 ++++++------ library/core/src/iter/adapters/intersperse.rs | 16 ++++++++-------- library/core/src/iter/adapters/map_windows.rs | 12 ++++++------ library/core/src/iter/adapters/mod.rs | 6 +++--- library/core/src/iter/mod.rs | 6 +++--- library/core/src/iter/traits/double_ended.rs | 2 +- library/core/src/iter/traits/iterator.rs | 12 ++++++------ library/std/src/io/mod.rs | 2 +- library/std/src/os/unix/io/mod.rs | 6 +++--- 9 files changed, 37 insertions(+), 37 deletions(-) diff --git a/library/core/src/iter/adapters/array_chunks.rs b/library/core/src/iter/adapters/array_chunks.rs index 21f46ab8b6a4..7c003cff10c7 100644 --- a/library/core/src/iter/adapters/array_chunks.rs +++ b/library/core/src/iter/adapters/array_chunks.rs @@ -15,7 +15,7 @@ use crate::ops::{ControlFlow, NeverShortCircuit, Try}; /// method on [`Iterator`]. See its documentation for more. #[derive(Debug, Clone)] #[must_use = "iterators are lazy and do nothing unless consumed"] -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +#[unstable(feature = "iter_array_chunks", issue = "100450")] pub struct ArrayChunks { iter: I, remainder: Option>, @@ -44,7 +44,7 @@ where /// assert_eq!(rem.next(), Some(5)); /// assert_eq!(rem.next(), None); /// ``` - #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] + #[unstable(feature = "iter_array_chunks", issue = "100450")] #[inline] pub fn into_remainder(mut self) -> array::IntoIter { if self.remainder.is_none() { @@ -54,7 +54,7 @@ where } } -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +#[unstable(feature = "iter_array_chunks", issue = "100450")] impl Iterator for ArrayChunks where I: Iterator, @@ -108,7 +108,7 @@ where } } -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +#[unstable(feature = "iter_array_chunks", issue = "100450")] impl DoubleEndedIterator for ArrayChunks where I: DoubleEndedIterator + ExactSizeIterator, @@ -173,13 +173,13 @@ where } } -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +#[unstable(feature = "iter_array_chunks", issue = "100450")] impl FusedIterator for ArrayChunks where I: FusedIterator {} #[unstable(issue = "none", feature = "trusted_fused")] unsafe impl TrustedFused for ArrayChunks where I: TrustedFused + Iterator {} -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +#[unstable(feature = "iter_array_chunks", issue = "100450")] impl ExactSizeIterator for ArrayChunks where I: ExactSizeIterator, diff --git a/library/core/src/iter/adapters/intersperse.rs b/library/core/src/iter/adapters/intersperse.rs index 843479e2a27a..bb94ed0a0a17 100644 --- a/library/core/src/iter/adapters/intersperse.rs +++ b/library/core/src/iter/adapters/intersperse.rs @@ -5,7 +5,7 @@ use crate::iter::{Fuse, FusedIterator}; /// /// This `struct` is created by [`Iterator::intersperse`]. See its documentation /// for more information. -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] #[derive(Debug, Clone)] pub struct Intersperse where @@ -17,7 +17,7 @@ where iter: Fuse, } -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] impl FusedIterator for Intersperse where I: FusedIterator, @@ -34,7 +34,7 @@ where } } -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] impl Iterator for Intersperse where I: Iterator, @@ -87,7 +87,7 @@ where /// /// This `struct` is created by [`Iterator::intersperse_with`]. See its /// documentation for more information. -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] pub struct IntersperseWith where I: Iterator, @@ -98,7 +98,7 @@ where iter: Fuse, } -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] impl FusedIterator for IntersperseWith where I: FusedIterator, @@ -106,7 +106,7 @@ where { } -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] impl fmt::Debug for IntersperseWith where I: Iterator + fmt::Debug, @@ -123,7 +123,7 @@ where } } -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] impl Clone for IntersperseWith where I: Iterator + Clone, @@ -150,7 +150,7 @@ where } } -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] impl Iterator for IntersperseWith where I: Iterator, diff --git a/library/core/src/iter/adapters/map_windows.rs b/library/core/src/iter/adapters/map_windows.rs index 0dada9eb6aac..cef556319143 100644 --- a/library/core/src/iter/adapters/map_windows.rs +++ b/library/core/src/iter/adapters/map_windows.rs @@ -7,7 +7,7 @@ use crate::{fmt, ptr}; /// This `struct` is created by the [`Iterator::map_windows`]. See its /// documentation for more information. #[must_use = "iterators are lazy and do nothing unless consumed"] -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +#[unstable(feature = "iter_map_windows", issue = "87155")] pub struct MapWindows { f: F, inner: MapWindowsInner, @@ -234,7 +234,7 @@ impl Drop for Buffer { } } -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +#[unstable(feature = "iter_map_windows", issue = "87155")] impl Iterator for MapWindows where I: Iterator, @@ -255,7 +255,7 @@ where // Note that even if the inner iterator not fused, the `MapWindows` is still fused, // because we don't allow "holes" in the mapping window. -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +#[unstable(feature = "iter_map_windows", issue = "87155")] impl FusedIterator for MapWindows where I: Iterator, @@ -263,7 +263,7 @@ where { } -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +#[unstable(feature = "iter_map_windows", issue = "87155")] impl ExactSizeIterator for MapWindows where I: ExactSizeIterator, @@ -271,14 +271,14 @@ where { } -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +#[unstable(feature = "iter_map_windows", issue = "87155")] impl fmt::Debug for MapWindows { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("MapWindows").field("iter", &self.inner.iter).finish() } } -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +#[unstable(feature = "iter_map_windows", issue = "87155")] impl Clone for MapWindows where I: Iterator + Clone, diff --git a/library/core/src/iter/adapters/mod.rs b/library/core/src/iter/adapters/mod.rs index 1ff5093922b6..d0b89fdbb584 100644 --- a/library/core/src/iter/adapters/mod.rs +++ b/library/core/src/iter/adapters/mod.rs @@ -28,7 +28,7 @@ mod take; mod take_while; mod zip; -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +#[unstable(feature = "iter_array_chunks", issue = "100450")] pub use self::array_chunks::ArrayChunks; #[unstable(feature = "std_internals", issue = "none")] pub use self::by_ref_sized::ByRefSized; @@ -40,11 +40,11 @@ pub use self::cloned::Cloned; pub use self::copied::Copied; #[stable(feature = "iterator_flatten", since = "1.29.0")] pub use self::flatten::Flatten; -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] pub use self::intersperse::{Intersperse, IntersperseWith}; #[stable(feature = "iter_map_while", since = "1.57.0")] pub use self::map_while::MapWhile; -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +#[unstable(feature = "iter_map_windows", issue = "87155")] pub use self::map_windows::MapWindows; #[stable(feature = "iterator_step_by", since = "1.28.0")] pub use self::step_by::StepBy; diff --git a/library/core/src/iter/mod.rs b/library/core/src/iter/mod.rs index c7e1c4ef767b..d532f1e56807 100644 --- a/library/core/src/iter/mod.rs +++ b/library/core/src/iter/mod.rs @@ -382,7 +382,7 @@ macro_rules! impl_fold_via_try_fold { }; } -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +#[unstable(feature = "iter_array_chunks", issue = "100450")] pub use self::adapters::ArrayChunks; #[unstable(feature = "std_internals", issue = "none")] pub use self::adapters::ByRefSized; @@ -394,7 +394,7 @@ pub use self::adapters::Copied; pub use self::adapters::Flatten; #[stable(feature = "iter_map_while", since = "1.57.0")] pub use self::adapters::MapWhile; -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +#[unstable(feature = "iter_map_windows", issue = "87155")] pub use self::adapters::MapWindows; #[unstable(feature = "inplace_iteration", issue = "none")] pub use self::adapters::SourceIter; @@ -414,7 +414,7 @@ pub use self::adapters::{ Chain, Cycle, Enumerate, Filter, FilterMap, FlatMap, Fuse, Inspect, Map, Peekable, Rev, Scan, Skip, SkipWhile, Take, TakeWhile, Zip, }; -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +#[unstable(feature = "iter_intersperse", issue = "79524")] pub use self::adapters::{Intersperse, IntersperseWith}; #[unstable( feature = "step_trait", diff --git a/library/core/src/iter/traits/double_ended.rs b/library/core/src/iter/traits/double_ended.rs index da0b05063657..9f7ac7da2dbd 100644 --- a/library/core/src/iter/traits/double_ended.rs +++ b/library/core/src/iter/traits/double_ended.rs @@ -134,7 +134,7 @@ pub trait DoubleEndedIterator: Iterator { /// [`Ok(())`]: Ok /// [`Err(k)`]: Err #[inline] - #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")] + #[unstable(feature = "iter_advance_by", issue = "77404")] fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero> { for i in 0..n { if self.next_back().is_none() { diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 419f66089b10..81901fc011be 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -106,7 +106,7 @@ pub trait Iterator { /// assert_eq!(third, "those"); /// ``` #[inline] - #[unstable(feature = "iter_next_chunk", reason = "recently added", issue = "98326")] + #[unstable(feature = "iter_next_chunk", issue = "98326")] fn next_chunk( &mut self, ) -> Result<[Self::Item; N], array::IntoIter> @@ -297,7 +297,7 @@ pub trait Iterator { /// assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `4` was skipped /// ``` #[inline] - #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")] + #[unstable(feature = "iter_advance_by", issue = "77404")] fn advance_by(&mut self, n: usize) -> Result<(), NonZero> { /// Helper trait to specialize `advance_by` via `try_fold` for `Sized` iterators. trait SpecAdvanceBy { @@ -656,7 +656,7 @@ pub trait Iterator { /// [`Clone`]: crate::clone::Clone /// [`intersperse_with`]: Iterator::intersperse_with #[inline] - #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] + #[unstable(feature = "iter_intersperse", issue = "79524")] fn intersperse(self, separator: Self::Item) -> Intersperse where Self: Sized, @@ -714,7 +714,7 @@ pub trait Iterator { /// [`Clone`]: crate::clone::Clone /// [`intersperse`]: Iterator::intersperse #[inline] - #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] + #[unstable(feature = "iter_intersperse", issue = "79524")] fn intersperse_with(self, separator: G) -> IntersperseWith where Self: Sized, @@ -1713,7 +1713,7 @@ pub trait Iterator { /// assert_eq!(iter.next(), None); /// ``` #[inline] - #[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] + #[unstable(feature = "iter_map_windows", issue = "87155")] fn map_windows(self, f: F) -> MapWindows where Self: Sized, @@ -3554,7 +3554,7 @@ pub trait Iterator { /// } /// ``` #[track_caller] - #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] + #[unstable(feature = "iter_array_chunks", issue = "100450")] fn array_chunks(self) -> ArrayChunks where Self: Sized, diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index b7756befa11e..623c34c6d291 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -2431,7 +2431,7 @@ pub trait BufRead: Read { /// } /// # std::io::Result::Ok(()) /// ``` - #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")] + #[unstable(feature = "buf_read_has_data_left", issue = "86423")] fn has_data_left(&mut self) -> Result { self.fill_buf().map(|b| !b.is_empty()) } diff --git a/library/std/src/os/unix/io/mod.rs b/library/std/src/os/unix/io/mod.rs index 708ebaec362e..18b0f70c0687 100644 --- a/library/std/src/os/unix/io/mod.rs +++ b/library/std/src/os/unix/io/mod.rs @@ -102,7 +102,7 @@ use crate::sys::cvt; #[cfg(test)] mod tests; -#[unstable(feature = "stdio_swap", issue = "150667", reason = "recently added")] +#[unstable(feature = "stdio_swap", issue = "150667")] pub trait StdioExt: crate::sealed::Sealed { /// Redirects the stdio file descriptor to point to the file description underpinning `fd`. /// @@ -159,7 +159,7 @@ pub trait StdioExt: crate::sealed::Sealed { } macro io_ext_impl($stdio_ty:ty, $stdio_lock_ty:ty, $writer:literal) { - #[unstable(feature = "stdio_swap", issue = "150667", reason = "recently added")] + #[unstable(feature = "stdio_swap", issue = "150667")] impl StdioExt for $stdio_ty { fn set_fd>(&mut self, fd: T) -> io::Result<()> { self.lock().set_fd(fd) @@ -174,7 +174,7 @@ macro io_ext_impl($stdio_ty:ty, $stdio_lock_ty:ty, $writer:literal) { } } - #[unstable(feature = "stdio_swap", issue = "150667", reason = "recently added")] + #[unstable(feature = "stdio_swap", issue = "150667")] impl StdioExt for $stdio_lock_ty { fn set_fd>(&mut self, fd: T) -> io::Result<()> { #[cfg($writer)] From 69da4016aaa085c185aa7f6251555ac226d35f51 Mon Sep 17 00:00:00 2001 From: cyrgani Date: Fri, 16 Jan 2026 13:34:34 +0000 Subject: [PATCH 078/146] remove `reason = "new API"` from `#[unstable(...)]` --- library/alloc/src/boxed.rs | 8 ++++---- library/alloc/src/collections/mod.rs | 2 +- library/alloc/src/string.rs | 2 +- library/alloc/src/vec/mod.rs | 14 +++++++------- library/core/src/iter/traits/iterator.rs | 10 +++++----- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 60758551cc04..de9c92db11d3 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -1313,7 +1313,7 @@ impl Box { /// ``` /// /// [memory layout]: self#memory-layout - #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] + #[unstable(feature = "box_vec_non_null", issue = "130364")] #[inline] #[must_use = "call `drop(Box::from_non_null(ptr))` if you intend to drop the `Box`"] pub unsafe fn from_non_null(ptr: NonNull) -> Self { @@ -1431,7 +1431,7 @@ impl Box { /// /// [memory layout]: self#memory-layout #[must_use = "losing the pointer will leak memory"] - #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] + #[unstable(feature = "box_vec_non_null", issue = "130364")] #[inline] pub fn into_non_null(b: Self) -> NonNull { // SAFETY: `Box` is guaranteed to be non-null. @@ -1540,7 +1540,7 @@ impl Box { /// /// [memory layout]: self#memory-layout #[unstable(feature = "allocator_api", issue = "32838")] - // #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] + // #[unstable(feature = "box_vec_non_null", issue = "130364")] #[inline] pub unsafe fn from_non_null_in(raw: NonNull, alloc: A) -> Self { // SAFETY: guaranteed by the caller. @@ -1655,7 +1655,7 @@ impl Box { /// [memory layout]: self#memory-layout #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] - // #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] + // #[unstable(feature = "box_vec_non_null", issue = "130364")] #[inline] pub fn into_non_null_with_allocator(b: Self) -> (NonNull, A) { let (ptr, alloc) = Box::into_raw_with_allocator(b); diff --git a/library/alloc/src/collections/mod.rs b/library/alloc/src/collections/mod.rs index e09326759fd1..d306d2016ea2 100644 --- a/library/alloc/src/collections/mod.rs +++ b/library/alloc/src/collections/mod.rs @@ -156,7 +156,7 @@ impl const From for TryReserveError { } } -#[unstable(feature = "try_reserve_kind", reason = "new API", issue = "48043")] +#[unstable(feature = "try_reserve_kind", issue = "48043")] #[rustc_const_unstable(feature = "const_convert", issue = "143773")] #[cfg(not(test))] impl const From for TryReserveErrorKind { diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 1e7f4f208a7f..4100ee55a4c7 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1563,7 +1563,7 @@ impl String { /// assert_eq!("bna", s); /// ``` #[cfg(not(no_global_oom_handling))] - #[unstable(feature = "string_remove_matches", reason = "new API", issue = "72826")] + #[unstable(feature = "string_remove_matches", issue = "72826")] pub fn remove_matches(&mut self, pat: P) { use core::str::pattern::Searcher; diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 379e964f0a0c..93432f3e049e 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -743,7 +743,7 @@ impl Vec { /// } /// ``` #[inline] - #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] + #[unstable(feature = "box_vec_non_null", issue = "130364")] pub unsafe fn from_parts(ptr: NonNull, length: usize, capacity: usize) -> Self { unsafe { Self::from_parts_in(ptr, length, capacity, Global) } } @@ -793,7 +793,7 @@ impl Vec { /// ``` #[cfg(not(no_global_oom_handling))] #[inline] - #[unstable(feature = "vec_from_fn", reason = "new API", issue = "149698")] + #[unstable(feature = "vec_from_fn", issue = "149698")] pub fn from_fn(length: usize, f: F) -> Self where F: FnMut(usize) -> T, @@ -878,7 +878,7 @@ impl Vec { /// assert_eq!(rebuilt, [4294967295, 0, 1]); /// ``` #[must_use = "losing the pointer will leak memory"] - #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] + #[unstable(feature = "box_vec_non_null", issue = "130364")] pub fn into_parts(self) -> (NonNull, usize, usize) { let (ptr, len, capacity) = self.into_raw_parts(); // SAFETY: A `Vec` always has a non-null pointer. @@ -1291,7 +1291,7 @@ impl Vec { /// } /// ``` #[inline] - #[unstable(feature = "allocator_api", reason = "new API", issue = "32838")] + #[unstable(feature = "allocator_api", issue = "32838")] // #[unstable(feature = "box_vec_non_null", issue = "130364")] pub unsafe fn from_parts_in(ptr: NonNull, length: usize, capacity: usize, alloc: A) -> Self { ub_checks::assert_unsafe_precondition!( @@ -1390,7 +1390,7 @@ impl Vec { /// ``` #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] - // #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] + // #[unstable(feature = "box_vec_non_null", issue = "130364")] pub fn into_parts_with_alloc(self) -> (NonNull, usize, usize, A) { let (ptr, len, capacity, alloc) = self.into_raw_parts_with_alloc(); // SAFETY: A `Vec` always has a non-null pointer. @@ -1994,8 +1994,8 @@ impl Vec { /// [`as_mut_ptr`]: Vec::as_mut_ptr /// [`as_ptr`]: Vec::as_ptr /// [`as_non_null`]: Vec::as_non_null - #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] - #[rustc_const_unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] + #[unstable(feature = "box_vec_non_null", issue = "130364")] + #[rustc_const_unstable(feature = "box_vec_non_null", issue = "130364")] #[inline] pub const fn as_non_null(&mut self) -> NonNull { self.buf.non_null() diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 81901fc011be..dc484e2a27f6 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -2177,7 +2177,7 @@ pub trait Iterator { /// assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]); /// ``` #[inline] - #[unstable(feature = "iter_collect_into", reason = "new API", issue = "94780")] + #[unstable(feature = "iter_collect_into", issue = "94780")] fn collect_into>(self, collection: &mut E) -> &mut E where Self: Sized, @@ -2271,7 +2271,7 @@ pub trait Iterator { /// assert!(a[..i].iter().all(|n| n % 2 == 0)); // evens /// assert!(a[i..].iter().all(|n| n % 2 == 1)); // odds /// ``` - #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")] + #[unstable(feature = "iter_partition_in_place", issue = "62543")] fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize where Self: Sized + DoubleEndedIterator, @@ -2328,7 +2328,7 @@ pub trait Iterator { /// assert!("Iterator".chars().is_partitioned(char::is_uppercase)); /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase)); /// ``` - #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")] + #[unstable(feature = "iter_is_partitioned", issue = "62544")] fn is_partitioned

(mut self, mut predicate: P) -> bool where Self: Sized, @@ -2707,7 +2707,7 @@ pub trait Iterator { /// assert_eq!(max, Ok(Some("5"))); /// ``` #[inline] - #[unstable(feature = "iterator_try_reduce", reason = "new API", issue = "87053")] + #[unstable(feature = "iterator_try_reduce", issue = "87053")] fn try_reduce( &mut self, f: impl FnMut(Self::Item, Self::Item) -> R, @@ -2980,7 +2980,7 @@ pub trait Iterator { /// assert_eq!(result, None); /// ``` #[inline] - #[unstable(feature = "try_find", reason = "new API", issue = "63178")] + #[unstable(feature = "try_find", issue = "63178")] fn try_find( &mut self, f: impl FnMut(&Self::Item) -> R, From 8cb5da3aadbc086fc464d06dc5bd0b5db80d8eb6 Mon Sep 17 00:00:00 2001 From: cyrgani Date: Fri, 16 Jan 2026 13:35:40 +0000 Subject: [PATCH 079/146] remove `reason = "recently redesigned"` from `#[unstable(...)]` --- library/core/src/iter/range.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/library/core/src/iter/range.rs b/library/core/src/iter/range.rs index 9e43d5688cec..9d4015ac8c37 100644 --- a/library/core/src/iter/range.rs +++ b/library/core/src/iter/range.rs @@ -254,7 +254,7 @@ macro_rules! step_integer_impls { } => { $( #[allow(unreachable_patterns)] - #[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] + #[unstable(feature = "step_trait", issue = "42168")] impl Step for $u_narrower { step_identical_methods!(); step_unsigned_methods!(); @@ -288,7 +288,7 @@ macro_rules! step_integer_impls { } #[allow(unreachable_patterns)] - #[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] + #[unstable(feature = "step_trait", issue = "42168")] impl Step for $i_narrower { step_identical_methods!(); step_signed_methods!($u_narrower); @@ -354,7 +354,7 @@ macro_rules! step_integer_impls { $( #[allow(unreachable_patterns)] - #[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] + #[unstable(feature = "step_trait", issue = "42168")] impl Step for $u_wider { step_identical_methods!(); step_unsigned_methods!(); @@ -384,7 +384,7 @@ macro_rules! step_integer_impls { } #[allow(unreachable_patterns)] - #[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] + #[unstable(feature = "step_trait", issue = "42168")] impl Step for $i_wider { step_identical_methods!(); step_signed_methods!($u_wider); @@ -441,7 +441,7 @@ step_integer_impls! { wider than usize: [u32 i32], [u64 i64], [u128 i128]; } -#[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] +#[unstable(feature = "step_trait", issue = "42168")] impl Step for char { #[inline] fn steps_between(&start: &char, &end: &char) -> (usize, Option) { @@ -528,7 +528,7 @@ impl Step for char { } } -#[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] +#[unstable(feature = "step_trait", issue = "42168")] impl Step for AsciiChar { #[inline] fn steps_between(&start: &AsciiChar, &end: &AsciiChar) -> (usize, Option) { @@ -570,7 +570,7 @@ impl Step for AsciiChar { } } -#[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] +#[unstable(feature = "step_trait", issue = "42168")] impl Step for Ipv4Addr { #[inline] fn steps_between(&start: &Ipv4Addr, &end: &Ipv4Addr) -> (usize, Option) { @@ -602,7 +602,7 @@ impl Step for Ipv4Addr { } } -#[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] +#[unstable(feature = "step_trait", issue = "42168")] impl Step for Ipv6Addr { #[inline] fn steps_between(&start: &Ipv6Addr, &end: &Ipv6Addr) -> (usize, Option) { From 41daada3bbc5d5fb10119218c3b737854a27ce61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 16 Jan 2026 09:23:00 +0100 Subject: [PATCH 080/146] Ship LLVM (`rust-dev`) in fast try builds again --- src/tools/opt-dist/src/main.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/opt-dist/src/main.rs b/src/tools/opt-dist/src/main.rs index b52dab001ef5..cdbeee63d6c2 100644 --- a/src/tools/opt-dist/src/main.rs +++ b/src/tools/opt-dist/src/main.rs @@ -442,11 +442,12 @@ fn main() -> anyhow::Result<()> { // Skip components that are not needed for fast try builds to speed them up if is_fast_try_build() { log::info!("Skipping building of unimportant components for a fast try build"); + // Note for future onlookers: do not ignore rust-dev here. We need it for try builds when + // a PR makes a change to how LLVM is built. for target in [ "rust-docs", "rustc-docs", "rustc-dev", - "rust-dev", "rust-docs-json", "rust-analyzer", "rustc-src", From 035bcfa46d2892f873b59f9981999bb17f2df4a7 Mon Sep 17 00:00:00 2001 From: cyrgani Date: Fri, 16 Jan 2026 13:54:40 +0000 Subject: [PATCH 081/146] remove `reason = "unstable"` from `#[unstable(...)]` --- library/std/src/os/unix/net/mod.rs | 2 +- library/std/src/os/unix/net/stream.rs | 2 +- library/std/src/os/unix/net/ucred.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/library/std/src/os/unix/net/mod.rs b/library/std/src/os/unix/net/mod.rs index 94523d7d1e45..a44b23a77d2d 100644 --- a/library/std/src/os/unix/net/mod.rs +++ b/library/std/src/os/unix/net/mod.rs @@ -47,5 +47,5 @@ pub use self::stream::*; target_vendor = "apple", target_os = "cygwin", ))] -#[unstable(feature = "peer_credentials_unix_socket", issue = "42839", reason = "unstable")] +#[unstable(feature = "peer_credentials_unix_socket", issue = "42839")] pub use self::ucred::*; diff --git a/library/std/src/os/unix/net/stream.rs b/library/std/src/os/unix/net/stream.rs index c0a8045884a5..30124d96951e 100644 --- a/library/std/src/os/unix/net/stream.rs +++ b/library/std/src/os/unix/net/stream.rs @@ -251,7 +251,7 @@ impl UnixStream { /// Ok(()) /// } /// ``` - #[unstable(feature = "peer_credentials_unix_socket", issue = "42839", reason = "unstable")] + #[unstable(feature = "peer_credentials_unix_socket", issue = "42839")] #[cfg(any( target_os = "android", target_os = "linux", diff --git a/library/std/src/os/unix/net/ucred.rs b/library/std/src/os/unix/net/ucred.rs index 36fb9c46b4ab..1395d2ef4be3 100644 --- a/library/std/src/os/unix/net/ucred.rs +++ b/library/std/src/os/unix/net/ucred.rs @@ -7,7 +7,7 @@ use libc::{gid_t, pid_t, uid_t}; /// Credentials for a UNIX process for credentials passing. -#[unstable(feature = "peer_credentials_unix_socket", issue = "42839", reason = "unstable")] +#[unstable(feature = "peer_credentials_unix_socket", issue = "42839")] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct UCred { /// The UID part of the peer credential. This is the effective UID of the process at the domain From 1f691f7dbd8fce50a265d43baf004d7bf2247828 Mon Sep 17 00:00:00 2001 From: Alex Celeste Date: Fri, 16 Jan 2026 12:34:51 +0000 Subject: [PATCH 082/146] Add missing closing brackets to THIR output. Closing brackets were missing on AdtDef, the field_types list in FruInfo, and InlineAsmExpr, breaking folding in some editors; Fields were incorrectly (?) indexed in the list for functional update syntax, showing the (implicit, irrelevant) iteration index instead of the field index; also spurious colon after Pat. --- compiler/rustc_mir_build/src/thir/print.rs | 10 +- tests/ui/thir-print/c-variadic.stdout | 4 +- tests/ui/thir-print/offset_of.stdout | 18 +- .../thir-print/thir-tree-field-expr-index.rs | 25 + .../thir-tree-field-expr-index.stdout | 921 ++++++++++++++++++ .../ui/thir-print/thir-tree-loop-match.stdout | 6 +- tests/ui/thir-print/thir-tree-match.stdout | 16 +- tests/ui/unpretty/box.stdout | 2 +- 8 files changed, 978 insertions(+), 24 deletions(-) create mode 100644 tests/ui/thir-print/thir-tree-field-expr-index.rs create mode 100644 tests/ui/thir-print/thir-tree-field-expr-index.stdout diff --git a/compiler/rustc_mir_build/src/thir/print.rs b/compiler/rustc_mir_build/src/thir/print.rs index 2cafb73a74a4..a87257fa79bf 100644 --- a/compiler/rustc_mir_build/src/thir/print.rs +++ b/compiler/rustc_mir_build/src/thir/print.rs @@ -618,8 +618,8 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { print_indented!(self, format!("args: {:?}", adt_expr.args), depth_lvl + 1); print_indented!(self, format!("user_ty: {:?}", adt_expr.user_ty), depth_lvl + 1); - for (i, field_expr) in adt_expr.fields.iter().enumerate() { - print_indented!(self, format!("field {}:", i), depth_lvl + 1); + for field_expr in adt_expr.fields.iter() { + print_indented!(self, format!("field {}:", field_expr.name.as_u32()), depth_lvl + 1); self.print_expr(field_expr.expr, depth_lvl + 2); } @@ -643,6 +643,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { print_indented!(self, format!("variants: {:?}", adt_def.variants()), depth_lvl + 1); print_indented!(self, format!("flags: {:?}", adt_def.flags()), depth_lvl + 1); print_indented!(self, format!("repr: {:?}", adt_def.repr()), depth_lvl + 1); + print_indented!(self, "}", depth_lvl); } fn print_fru_info(&mut self, fru_info: &FruInfo<'tcx>, depth_lvl: usize) { @@ -653,6 +654,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { for ty in fru_info.field_types.iter() { print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 2); } + print_indented!(self, "]", depth_lvl + 1); print_indented!(self, "}", depth_lvl); } @@ -683,7 +685,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { fn print_pat(&mut self, pat: &Pat<'tcx>, depth_lvl: usize) { let &Pat { ty, span, ref kind, ref extra } = pat; - print_indented!(self, "Pat: {", depth_lvl); + print_indented!(self, "Pat {", depth_lvl); print_indented!(self, format!("ty: {:?}", ty), depth_lvl + 1); print_indented!(self, format!("span: {:?}", span), depth_lvl + 1); self.print_pat_extra(extra.as_deref(), depth_lvl + 1); @@ -913,6 +915,8 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { print_indented!(self, format!("options: {:?}", options), depth_lvl + 1); print_indented!(self, format!("line_spans: {:?}", line_spans), depth_lvl + 1); + + print_indented!(self, "}", depth_lvl); } fn print_inline_operand(&mut self, operand: &InlineAsmOperand<'tcx>, depth_lvl: usize) { diff --git a/tests/ui/thir-print/c-variadic.stdout b/tests/ui/thir-print/c-variadic.stdout index a3e3fa5e0008..a426902b2deb 100644 --- a/tests/ui/thir-print/c-variadic.stdout +++ b/tests/ui/thir-print/c-variadic.stdout @@ -6,7 +6,7 @@ params: [ self_kind: None hir_id: Some(HirId(DefId(0:3 ~ c_variadic[a5de]::foo).1)) param: Some( - Pat: { + Pat { ty: i32 span: $DIR/c-variadic.rs:7:26: 7:27 (#0) kind: PatKind { @@ -21,7 +21,7 @@ params: [ self_kind: None hir_id: Some(HirId(DefId(0:3 ~ c_variadic[a5de]::foo).3)) param: Some( - Pat: { + Pat { ty: std::ffi::VaList<'{erased}> span: $DIR/c-variadic.rs:7:34: 7:37 (#0) kind: PatKind { diff --git a/tests/ui/thir-print/offset_of.stdout b/tests/ui/thir-print/offset_of.stdout index 29399bb98e32..b3791a2446cb 100644 --- a/tests/ui/thir-print/offset_of.stdout +++ b/tests/ui/thir-print/offset_of.stdout @@ -27,7 +27,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 0} init_scope: Node(2) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:37:9: 37:10 (#0) kind: PatKind { @@ -76,7 +76,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 1} init_scope: Node(12) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:38:9: 38:10 (#0) kind: PatKind { @@ -125,7 +125,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 2} init_scope: Node(22) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:39:9: 39:10 (#0) kind: PatKind { @@ -174,7 +174,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 3} init_scope: Node(32) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:40:9: 40:11 (#0) kind: PatKind { @@ -223,7 +223,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 4} init_scope: Node(42) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:41:9: 41:11 (#0) kind: PatKind { @@ -823,7 +823,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 0} init_scope: Node(2) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:45:9: 45:11 (#0) kind: PatKind { @@ -872,7 +872,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 1} init_scope: Node(14) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:46:9: 46:11 (#0) kind: PatKind { @@ -921,7 +921,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 2} init_scope: Node(26) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:47:9: 47:11 (#0) kind: PatKind { @@ -970,7 +970,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 3} init_scope: Node(38) pattern: - Pat: { + Pat { ty: usize span: $DIR/offset_of.rs:48:9: 48:11 (#0) kind: PatKind { diff --git a/tests/ui/thir-print/thir-tree-field-expr-index.rs b/tests/ui/thir-print/thir-tree-field-expr-index.rs new file mode 100644 index 000000000000..399b78528289 --- /dev/null +++ b/tests/ui/thir-print/thir-tree-field-expr-index.rs @@ -0,0 +1,25 @@ +//@ check-pass +//@ compile-flags: -Zunpretty=thir-tree + +struct S { + a: u32, + b: u32, + c: u32, + d: u32, + e: u32, +} + +fn update(x: u32) { + let s = S { a: x, b: x, c: x, d: x, e: x }; + + S { a: x , ..s }; + S { b: x , ..s }; + S { c: x , ..s }; + S { d: x , ..s }; + S { e: x , ..s }; + + S { b: x, d: x, ..s }; + S { a: x, c: x, e: x, ..s }; +} + +fn main() {} diff --git a/tests/ui/thir-print/thir-tree-field-expr-index.stdout b/tests/ui/thir-print/thir-tree-field-expr-index.stdout new file mode 100644 index 000000000000..5bf97a185290 --- /dev/null +++ b/tests/ui/thir-print/thir-tree-field-expr-index.stdout @@ -0,0 +1,921 @@ +DefId(0:9 ~ thir_tree_field_expr_index[5059]::update): +params: [ + Param { + ty: u32 + ty_span: Some($DIR/thir-tree-field-expr-index.rs:12:14: 12:17 (#0)) + self_kind: None + hir_id: Some(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).1)) + param: Some( + Pat { + ty: u32 + span: $DIR/thir-tree-field-expr-index.rs:12:11: 12:12 (#0) + kind: PatKind { + Binding { + name: "x" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ) + } +] +body: + Expr { + ty: () + temp_scope_id: 89 + span: $DIR/thir-tree-field-expr-index.rs:12:19: 23:2 (#0) + kind: + Scope { + region_scope: Node(89) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).89) + value: + Expr { + ty: () + temp_scope_id: 89 + span: $DIR/thir-tree-field-expr-index.rs:12:19: 23:2 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-field-expr-index.rs:12:19: 23:2 (#0) + region_scope: Node(3) + safety_mode: Safe + stmts: [ + Stmt { + kind: Let { + remainder_scope: Remainder { block: 3, first_statement_index: 0} + init_scope: Node(4) + pattern: + Pat { + ty: S + span: $DIR/thir-tree-field-expr-index.rs:13:7: 13:8 (#0) + kind: PatKind { + Binding { + name: "s" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).23)) + ty: S + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + , + initializer: Some( + Expr { + ty: S + temp_scope_id: 5 + span: $DIR/thir-tree-field-expr-index.rs:13:11: 13:45 (#0) + kind: + Scope { + region_scope: Node(5) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).5) + value: + Expr { + ty: S + temp_scope_id: 5 + span: $DIR/thir-tree-field-expr-index.rs:13:11: 13:45 (#0) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S) + variants: [VariantDef { def_id: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S), ctor: None, name: "S", discr: Relative(0), fields: [FieldDef { did: DefId(0:4 ~ thir_tree_field_expr_index[5059]::S::a), name: "a", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:5 ~ thir_tree_field_expr_index[5059]::S::b), name: "b", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:6 ~ thir_tree_field_expr_index[5059]::S::c), name: "c", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:7 ~ thir_tree_field_expr_index[5059]::S::d), name: "d", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:8 ~ thir_tree_field_expr_index[5059]::S::e), name: "e", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7076349371981215213 } + } + variant_index: 0 + args: [] + user_ty: None + field 0: + Expr { + ty: u32 + temp_scope_id: 8 + span: $DIR/thir-tree-field-expr-index.rs:13:18: 13:19 (#0) + kind: + Scope { + region_scope: Node(8) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).8) + value: + Expr { + ty: u32 + temp_scope_id: 8 + span: $DIR/thir-tree-field-expr-index.rs:13:18: 13:19 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + field 1: + Expr { + ty: u32 + temp_scope_id: 11 + span: $DIR/thir-tree-field-expr-index.rs:13:24: 13:25 (#0) + kind: + Scope { + region_scope: Node(11) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).11) + value: + Expr { + ty: u32 + temp_scope_id: 11 + span: $DIR/thir-tree-field-expr-index.rs:13:24: 13:25 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + field 2: + Expr { + ty: u32 + temp_scope_id: 14 + span: $DIR/thir-tree-field-expr-index.rs:13:30: 13:31 (#0) + kind: + Scope { + region_scope: Node(14) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).14) + value: + Expr { + ty: u32 + temp_scope_id: 14 + span: $DIR/thir-tree-field-expr-index.rs:13:30: 13:31 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + field 3: + Expr { + ty: u32 + temp_scope_id: 17 + span: $DIR/thir-tree-field-expr-index.rs:13:36: 13:37 (#0) + kind: + Scope { + region_scope: Node(17) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).17) + value: + Expr { + ty: u32 + temp_scope_id: 17 + span: $DIR/thir-tree-field-expr-index.rs:13:36: 13:37 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + field 4: + Expr { + ty: u32 + temp_scope_id: 20 + span: $DIR/thir-tree-field-expr-index.rs:13:42: 13:43 (#0) + kind: + Scope { + region_scope: Node(20) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).20) + value: + Expr { + ty: u32 + temp_scope_id: 20 + span: $DIR/thir-tree-field-expr-index.rs:13:42: 13:43 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + base: None + } + } + } + } + ) + else_block: None + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).22) + span: $DIR/thir-tree-field-expr-index.rs:13:3: 13:45 (#0) + } + } + Stmt { + kind: Expr { + scope: Node(31) + expr: + Expr { + ty: S + temp_scope_id: 24 + span: $DIR/thir-tree-field-expr-index.rs:15:3: 15:19 (#0) + kind: + Scope { + region_scope: Node(24) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).24) + value: + Expr { + ty: S + temp_scope_id: 24 + span: $DIR/thir-tree-field-expr-index.rs:15:3: 15:19 (#0) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S) + variants: [VariantDef { def_id: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S), ctor: None, name: "S", discr: Relative(0), fields: [FieldDef { did: DefId(0:4 ~ thir_tree_field_expr_index[5059]::S::a), name: "a", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:5 ~ thir_tree_field_expr_index[5059]::S::b), name: "b", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:6 ~ thir_tree_field_expr_index[5059]::S::c), name: "c", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:7 ~ thir_tree_field_expr_index[5059]::S::d), name: "d", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:8 ~ thir_tree_field_expr_index[5059]::S::e), name: "e", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7076349371981215213 } + } + variant_index: 0 + args: [] + user_ty: None + field 0: + Expr { + ty: u32 + temp_scope_id: 29 + span: $DIR/thir-tree-field-expr-index.rs:15:10: 15:11 (#0) + kind: + Scope { + region_scope: Node(29) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).29) + value: + Expr { + ty: u32 + temp_scope_id: 29 + span: $DIR/thir-tree-field-expr-index.rs:15:10: 15:11 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + base: + FruInfo { + base: + Expr { + ty: S + temp_scope_id: 25 + span: $DIR/thir-tree-field-expr-index.rs:15:16: 15:17 (#0) + kind: + Scope { + region_scope: Node(25) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).25) + value: + Expr { + ty: S + temp_scope_id: 25 + span: $DIR/thir-tree-field-expr-index.rs:15:16: 15:17 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).23)) + } + } + } + } + field_types: [ + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ] + } + } + } + } + } + } + } + Stmt { + kind: Expr { + scope: Node(39) + expr: + Expr { + ty: S + temp_scope_id: 32 + span: $DIR/thir-tree-field-expr-index.rs:16:3: 16:19 (#0) + kind: + Scope { + region_scope: Node(32) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).32) + value: + Expr { + ty: S + temp_scope_id: 32 + span: $DIR/thir-tree-field-expr-index.rs:16:3: 16:19 (#0) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S) + variants: [VariantDef { def_id: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S), ctor: None, name: "S", discr: Relative(0), fields: [FieldDef { did: DefId(0:4 ~ thir_tree_field_expr_index[5059]::S::a), name: "a", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:5 ~ thir_tree_field_expr_index[5059]::S::b), name: "b", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:6 ~ thir_tree_field_expr_index[5059]::S::c), name: "c", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:7 ~ thir_tree_field_expr_index[5059]::S::d), name: "d", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:8 ~ thir_tree_field_expr_index[5059]::S::e), name: "e", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7076349371981215213 } + } + variant_index: 0 + args: [] + user_ty: None + field 1: + Expr { + ty: u32 + temp_scope_id: 37 + span: $DIR/thir-tree-field-expr-index.rs:16:10: 16:11 (#0) + kind: + Scope { + region_scope: Node(37) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).37) + value: + Expr { + ty: u32 + temp_scope_id: 37 + span: $DIR/thir-tree-field-expr-index.rs:16:10: 16:11 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + base: + FruInfo { + base: + Expr { + ty: S + temp_scope_id: 33 + span: $DIR/thir-tree-field-expr-index.rs:16:16: 16:17 (#0) + kind: + Scope { + region_scope: Node(33) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).33) + value: + Expr { + ty: S + temp_scope_id: 33 + span: $DIR/thir-tree-field-expr-index.rs:16:16: 16:17 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).23)) + } + } + } + } + field_types: [ + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ] + } + } + } + } + } + } + } + Stmt { + kind: Expr { + scope: Node(47) + expr: + Expr { + ty: S + temp_scope_id: 40 + span: $DIR/thir-tree-field-expr-index.rs:17:3: 17:19 (#0) + kind: + Scope { + region_scope: Node(40) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).40) + value: + Expr { + ty: S + temp_scope_id: 40 + span: $DIR/thir-tree-field-expr-index.rs:17:3: 17:19 (#0) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S) + variants: [VariantDef { def_id: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S), ctor: None, name: "S", discr: Relative(0), fields: [FieldDef { did: DefId(0:4 ~ thir_tree_field_expr_index[5059]::S::a), name: "a", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:5 ~ thir_tree_field_expr_index[5059]::S::b), name: "b", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:6 ~ thir_tree_field_expr_index[5059]::S::c), name: "c", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:7 ~ thir_tree_field_expr_index[5059]::S::d), name: "d", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:8 ~ thir_tree_field_expr_index[5059]::S::e), name: "e", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7076349371981215213 } + } + variant_index: 0 + args: [] + user_ty: None + field 2: + Expr { + ty: u32 + temp_scope_id: 45 + span: $DIR/thir-tree-field-expr-index.rs:17:10: 17:11 (#0) + kind: + Scope { + region_scope: Node(45) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).45) + value: + Expr { + ty: u32 + temp_scope_id: 45 + span: $DIR/thir-tree-field-expr-index.rs:17:10: 17:11 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + base: + FruInfo { + base: + Expr { + ty: S + temp_scope_id: 41 + span: $DIR/thir-tree-field-expr-index.rs:17:16: 17:17 (#0) + kind: + Scope { + region_scope: Node(41) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).41) + value: + Expr { + ty: S + temp_scope_id: 41 + span: $DIR/thir-tree-field-expr-index.rs:17:16: 17:17 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).23)) + } + } + } + } + field_types: [ + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ] + } + } + } + } + } + } + } + Stmt { + kind: Expr { + scope: Node(55) + expr: + Expr { + ty: S + temp_scope_id: 48 + span: $DIR/thir-tree-field-expr-index.rs:18:3: 18:19 (#0) + kind: + Scope { + region_scope: Node(48) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).48) + value: + Expr { + ty: S + temp_scope_id: 48 + span: $DIR/thir-tree-field-expr-index.rs:18:3: 18:19 (#0) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S) + variants: [VariantDef { def_id: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S), ctor: None, name: "S", discr: Relative(0), fields: [FieldDef { did: DefId(0:4 ~ thir_tree_field_expr_index[5059]::S::a), name: "a", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:5 ~ thir_tree_field_expr_index[5059]::S::b), name: "b", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:6 ~ thir_tree_field_expr_index[5059]::S::c), name: "c", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:7 ~ thir_tree_field_expr_index[5059]::S::d), name: "d", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:8 ~ thir_tree_field_expr_index[5059]::S::e), name: "e", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7076349371981215213 } + } + variant_index: 0 + args: [] + user_ty: None + field 3: + Expr { + ty: u32 + temp_scope_id: 53 + span: $DIR/thir-tree-field-expr-index.rs:18:10: 18:11 (#0) + kind: + Scope { + region_scope: Node(53) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).53) + value: + Expr { + ty: u32 + temp_scope_id: 53 + span: $DIR/thir-tree-field-expr-index.rs:18:10: 18:11 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + base: + FruInfo { + base: + Expr { + ty: S + temp_scope_id: 49 + span: $DIR/thir-tree-field-expr-index.rs:18:16: 18:17 (#0) + kind: + Scope { + region_scope: Node(49) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).49) + value: + Expr { + ty: S + temp_scope_id: 49 + span: $DIR/thir-tree-field-expr-index.rs:18:16: 18:17 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).23)) + } + } + } + } + field_types: [ + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ] + } + } + } + } + } + } + } + Stmt { + kind: Expr { + scope: Node(63) + expr: + Expr { + ty: S + temp_scope_id: 56 + span: $DIR/thir-tree-field-expr-index.rs:19:3: 19:19 (#0) + kind: + Scope { + region_scope: Node(56) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).56) + value: + Expr { + ty: S + temp_scope_id: 56 + span: $DIR/thir-tree-field-expr-index.rs:19:3: 19:19 (#0) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S) + variants: [VariantDef { def_id: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S), ctor: None, name: "S", discr: Relative(0), fields: [FieldDef { did: DefId(0:4 ~ thir_tree_field_expr_index[5059]::S::a), name: "a", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:5 ~ thir_tree_field_expr_index[5059]::S::b), name: "b", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:6 ~ thir_tree_field_expr_index[5059]::S::c), name: "c", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:7 ~ thir_tree_field_expr_index[5059]::S::d), name: "d", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:8 ~ thir_tree_field_expr_index[5059]::S::e), name: "e", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7076349371981215213 } + } + variant_index: 0 + args: [] + user_ty: None + field 4: + Expr { + ty: u32 + temp_scope_id: 61 + span: $DIR/thir-tree-field-expr-index.rs:19:10: 19:11 (#0) + kind: + Scope { + region_scope: Node(61) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).61) + value: + Expr { + ty: u32 + temp_scope_id: 61 + span: $DIR/thir-tree-field-expr-index.rs:19:10: 19:11 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + base: + FruInfo { + base: + Expr { + ty: S + temp_scope_id: 57 + span: $DIR/thir-tree-field-expr-index.rs:19:16: 19:17 (#0) + kind: + Scope { + region_scope: Node(57) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).57) + value: + Expr { + ty: S + temp_scope_id: 57 + span: $DIR/thir-tree-field-expr-index.rs:19:16: 19:17 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).23)) + } + } + } + } + field_types: [ + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ] + } + } + } + } + } + } + } + Stmt { + kind: Expr { + scope: Node(74) + expr: + Expr { + ty: S + temp_scope_id: 64 + span: $DIR/thir-tree-field-expr-index.rs:21:3: 21:24 (#0) + kind: + Scope { + region_scope: Node(64) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).64) + value: + Expr { + ty: S + temp_scope_id: 64 + span: $DIR/thir-tree-field-expr-index.rs:21:3: 21:24 (#0) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S) + variants: [VariantDef { def_id: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S), ctor: None, name: "S", discr: Relative(0), fields: [FieldDef { did: DefId(0:4 ~ thir_tree_field_expr_index[5059]::S::a), name: "a", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:5 ~ thir_tree_field_expr_index[5059]::S::b), name: "b", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:6 ~ thir_tree_field_expr_index[5059]::S::c), name: "c", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:7 ~ thir_tree_field_expr_index[5059]::S::d), name: "d", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:8 ~ thir_tree_field_expr_index[5059]::S::e), name: "e", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7076349371981215213 } + } + variant_index: 0 + args: [] + user_ty: None + field 1: + Expr { + ty: u32 + temp_scope_id: 69 + span: $DIR/thir-tree-field-expr-index.rs:21:10: 21:11 (#0) + kind: + Scope { + region_scope: Node(69) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).69) + value: + Expr { + ty: u32 + temp_scope_id: 69 + span: $DIR/thir-tree-field-expr-index.rs:21:10: 21:11 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + field 3: + Expr { + ty: u32 + temp_scope_id: 72 + span: $DIR/thir-tree-field-expr-index.rs:21:16: 21:17 (#0) + kind: + Scope { + region_scope: Node(72) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).72) + value: + Expr { + ty: u32 + temp_scope_id: 72 + span: $DIR/thir-tree-field-expr-index.rs:21:16: 21:17 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + base: + FruInfo { + base: + Expr { + ty: S + temp_scope_id: 65 + span: $DIR/thir-tree-field-expr-index.rs:21:21: 21:22 (#0) + kind: + Scope { + region_scope: Node(65) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).65) + value: + Expr { + ty: S + temp_scope_id: 65 + span: $DIR/thir-tree-field-expr-index.rs:21:21: 21:22 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).23)) + } + } + } + } + field_types: [ + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ] + } + } + } + } + } + } + } + Stmt { + kind: Expr { + scope: Node(88) + expr: + Expr { + ty: S + temp_scope_id: 75 + span: $DIR/thir-tree-field-expr-index.rs:22:3: 22:30 (#0) + kind: + Scope { + region_scope: Node(75) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).75) + value: + Expr { + ty: S + temp_scope_id: 75 + span: $DIR/thir-tree-field-expr-index.rs:22:3: 22:30 (#0) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S) + variants: [VariantDef { def_id: DefId(0:3 ~ thir_tree_field_expr_index[5059]::S), ctor: None, name: "S", discr: Relative(0), fields: [FieldDef { did: DefId(0:4 ~ thir_tree_field_expr_index[5059]::S::a), name: "a", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:5 ~ thir_tree_field_expr_index[5059]::S::b), name: "b", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:6 ~ thir_tree_field_expr_index[5059]::S::c), name: "c", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:7 ~ thir_tree_field_expr_index[5059]::S::d), name: "d", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }, FieldDef { did: DefId(0:8 ~ thir_tree_field_expr_index[5059]::S::e), name: "e", vis: Restricted(DefId(0:0 ~ thir_tree_field_expr_index[5059])), safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7076349371981215213 } + } + variant_index: 0 + args: [] + user_ty: None + field 0: + Expr { + ty: u32 + temp_scope_id: 80 + span: $DIR/thir-tree-field-expr-index.rs:22:10: 22:11 (#0) + kind: + Scope { + region_scope: Node(80) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).80) + value: + Expr { + ty: u32 + temp_scope_id: 80 + span: $DIR/thir-tree-field-expr-index.rs:22:10: 22:11 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + field 2: + Expr { + ty: u32 + temp_scope_id: 83 + span: $DIR/thir-tree-field-expr-index.rs:22:16: 22:17 (#0) + kind: + Scope { + region_scope: Node(83) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).83) + value: + Expr { + ty: u32 + temp_scope_id: 83 + span: $DIR/thir-tree-field-expr-index.rs:22:16: 22:17 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + field 4: + Expr { + ty: u32 + temp_scope_id: 86 + span: $DIR/thir-tree-field-expr-index.rs:22:22: 22:23 (#0) + kind: + Scope { + region_scope: Node(86) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).86) + value: + Expr { + ty: u32 + temp_scope_id: 86 + span: $DIR/thir-tree-field-expr-index.rs:22:22: 22:23 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).2)) + } + } + } + } + base: + FruInfo { + base: + Expr { + ty: S + temp_scope_id: 76 + span: $DIR/thir-tree-field-expr-index.rs:22:27: 22:28 (#0) + kind: + Scope { + region_scope: Node(76) + hir_id: HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).76) + value: + Expr { + ty: S + temp_scope_id: 76 + span: $DIR/thir-tree-field-expr-index.rs:22:27: 22:28 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(0:9 ~ thir_tree_field_expr_index[5059]::update).23)) + } + } + } + } + field_types: [ + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ty: u32 + ] + } + } + } + } + } + } + } + ] + expr: [] + } + } + } + } + + +DefId(0:10 ~ thir_tree_field_expr_index[5059]::main): +params: [ +] +body: + Expr { + ty: () + temp_scope_id: 2 + span: $DIR/thir-tree-field-expr-index.rs:25:11: 25:13 (#0) + kind: + Scope { + region_scope: Node(2) + hir_id: HirId(DefId(0:10 ~ thir_tree_field_expr_index[5059]::main).2) + value: + Expr { + ty: () + temp_scope_id: 2 + span: $DIR/thir-tree-field-expr-index.rs:25:11: 25:13 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-field-expr-index.rs:25:11: 25:13 (#0) + region_scope: Node(1) + safety_mode: Safe + stmts: [] + expr: [] + } + } + } + } + + diff --git a/tests/ui/thir-print/thir-tree-loop-match.stdout b/tests/ui/thir-print/thir-tree-loop-match.stdout index 4a1b2aaf67f5..1bfd3f0952a3 100644 --- a/tests/ui/thir-print/thir-tree-loop-match.stdout +++ b/tests/ui/thir-print/thir-tree-loop-match.stdout @@ -6,7 +6,7 @@ params: [ self_kind: None hir_id: Some(HirId(DefId(0:3 ~ thir_tree_loop_match[3c53]::boolean).1)) param: Some( - Pat: { + Pat { ty: bool span: $DIR/thir-tree-loop-match.rs:7:12: 7:21 (#0) kind: PatKind { @@ -117,7 +117,7 @@ body: arms: [ Arm { pattern: - Pat: { + Pat { ty: bool span: $DIR/thir-tree-loop-match.rs:12:17: 12:21 (#0) kind: PatKind { @@ -215,7 +215,7 @@ body: } Arm { pattern: - Pat: { + Pat { ty: bool span: $DIR/thir-tree-loop-match.rs:16:17: 16:22 (#0) kind: PatKind { diff --git a/tests/ui/thir-print/thir-tree-match.stdout b/tests/ui/thir-print/thir-tree-match.stdout index a6d23ee204cb..31f8d368736c 100644 --- a/tests/ui/thir-print/thir-tree-match.stdout +++ b/tests/ui/thir-print/thir-tree-match.stdout @@ -6,7 +6,7 @@ params: [ self_kind: None hir_id: Some(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).1)) param: Some( - Pat: { + Pat { ty: Foo span: $DIR/thir-tree-match.rs:15:14: 15:17 (#0) kind: PatKind { @@ -85,7 +85,7 @@ body: arms: [ Arm { pattern: - Pat: { + Pat { ty: Foo span: $DIR/thir-tree-match.rs:17:9: 17:32 (#0) kind: PatKind { @@ -96,10 +96,11 @@ body: variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[fcf8]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[fcf8]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[fcf8]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[fcf8])), safety: Safe, value: None }], tainted: None, flags: }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[fcf8]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[fcf8]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], tainted: None, flags: }] flags: IS_ENUM repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 13397682652773712997 } + } args: [] variant_index: 0 subpatterns: [ - Pat: { + Pat { ty: Bar span: $DIR/thir-tree-match.rs:17:21: 17:31 (#0) kind: PatKind { @@ -110,6 +111,7 @@ body: variants: [VariantDef { def_id: DefId(0:4 ~ thir_tree_match[fcf8]::Bar::First), ctor: Some((Const, DefId(0:5 ~ thir_tree_match[fcf8]::Bar::First::{constructor#0}))), name: "First", discr: Relative(0), fields: [], tainted: None, flags: }, VariantDef { def_id: DefId(0:6 ~ thir_tree_match[fcf8]::Bar::Second), ctor: Some((Const, DefId(0:7 ~ thir_tree_match[fcf8]::Bar::Second::{constructor#0}))), name: "Second", discr: Relative(1), fields: [], tainted: None, flags: }, VariantDef { def_id: DefId(0:8 ~ thir_tree_match[fcf8]::Bar::Third), ctor: Some((Const, DefId(0:9 ~ thir_tree_match[fcf8]::Bar::Third::{constructor#0}))), name: "Third", discr: Relative(2), fields: [], tainted: None, flags: }] flags: IS_ENUM repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 7908585036048874241 } + } args: [] variant_index: 0 subpatterns: [] @@ -147,7 +149,7 @@ body: } Arm { pattern: - Pat: { + Pat { ty: Foo span: $DIR/thir-tree-match.rs:18:9: 18:23 (#0) kind: PatKind { @@ -158,10 +160,11 @@ body: variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[fcf8]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[fcf8]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[fcf8]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[fcf8])), safety: Safe, value: None }], tainted: None, flags: }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[fcf8]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[fcf8]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], tainted: None, flags: }] flags: IS_ENUM repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 13397682652773712997 } + } args: [] variant_index: 0 subpatterns: [ - Pat: { + Pat { ty: Bar span: $DIR/thir-tree-match.rs:18:21: 18:22 (#0) kind: PatKind { @@ -199,7 +202,7 @@ body: } Arm { pattern: - Pat: { + Pat { ty: Foo span: $DIR/thir-tree-match.rs:19:9: 19:20 (#0) kind: PatKind { @@ -210,6 +213,7 @@ body: variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[fcf8]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[fcf8]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[fcf8]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[fcf8])), safety: Safe, value: None }], tainted: None, flags: }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[fcf8]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[fcf8]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], tainted: None, flags: }] flags: IS_ENUM repr: ReprOptions { int: None, align: None, pack: None, flags: , scalable: None, field_shuffle_seed: 13397682652773712997 } + } args: [] variant_index: 1 subpatterns: [] diff --git a/tests/ui/unpretty/box.stdout b/tests/ui/unpretty/box.stdout index 123273be4efe..2576a2aa125d 100644 --- a/tests/ui/unpretty/box.stdout +++ b/tests/ui/unpretty/box.stdout @@ -27,7 +27,7 @@ body: remainder_scope: Remainder { block: 1, first_statement_index: 0} init_scope: Node(2) pattern: - Pat: { + Pat { ty: std::boxed::Box span: $DIR/box.rs:7:9: 7:10 (#0) kind: PatKind { From 5f58acba529112e75692833212ea25ad337828ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 16 Jan 2026 04:17:24 +0000 Subject: [PATCH 083/146] Add `const Default` impls for `HashSet` and `HashMap` with custom `Hasher` --- library/core/src/hash/mod.rs | 3 ++- library/core/src/hash/sip.rs | 9 ++++++--- library/std/src/collections/hash/map.rs | 5 +++-- library/std/src/collections/hash/map/tests.rs | 3 +++ library/std/src/collections/hash/set.rs | 7 ++++--- library/std/src/collections/hash/set/tests.rs | 2 ++ library/std/src/hash/random.rs | 6 ++++-- 7 files changed, 24 insertions(+), 11 deletions(-) diff --git a/library/core/src/hash/mod.rs b/library/core/src/hash/mod.rs index c3f3cd729425..a800e1b41fbe 100644 --- a/library/core/src/hash/mod.rs +++ b/library/core/src/hash/mod.rs @@ -784,7 +784,8 @@ impl Clone for BuildHasherDefault { } #[stable(since = "1.7.0", feature = "build_hasher")] -impl Default for BuildHasherDefault { +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +impl const Default for BuildHasherDefault { fn default() -> BuildHasherDefault { Self::new() } diff --git a/library/core/src/hash/sip.rs b/library/core/src/hash/sip.rs index 4f2e8a22d180..4569c7da035d 100644 --- a/library/core/src/hash/sip.rs +++ b/library/core/src/hash/sip.rs @@ -166,16 +166,18 @@ impl SipHasher13 { /// Creates a new `SipHasher13` with the two initial keys set to 0. #[inline] #[unstable(feature = "hashmap_internals", issue = "none")] + #[rustc_const_unstable(feature = "const_default", issue = "143894")] #[deprecated(since = "1.13.0", note = "use `std::hash::DefaultHasher` instead")] - pub fn new() -> SipHasher13 { + pub const fn new() -> SipHasher13 { SipHasher13::new_with_keys(0, 0) } /// Creates a `SipHasher13` that is keyed off the provided keys. #[inline] #[unstable(feature = "hashmap_internals", issue = "none")] + #[rustc_const_unstable(feature = "const_default", issue = "143894")] #[deprecated(since = "1.13.0", note = "use `std::hash::DefaultHasher` instead")] - pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 { + pub const fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 { SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) } } } @@ -338,7 +340,8 @@ impl Clone for Hasher { } } -impl Default for Hasher { +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +impl const Default for Hasher { /// Creates a `Hasher` with the two initial keys set to 0. #[inline] fn default() -> Hasher { diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index ad6328f76ed6..b82beb3b8b2e 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -1444,9 +1444,10 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for HashMap +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +impl const Default for HashMap where - S: Default, + S: [const] Default, { /// Creates an empty `HashMap`, with the `Default` value for the hasher. #[inline] diff --git a/library/std/src/collections/hash/map/tests.rs b/library/std/src/collections/hash/map/tests.rs index 9f7df20a1d7e..cc1a9900bec9 100644 --- a/library/std/src/collections/hash/map/tests.rs +++ b/library/std/src/collections/hash/map/tests.rs @@ -1053,4 +1053,7 @@ fn const_with_hasher() { assert_eq!(y.len(), 0); y.insert((), ()); assert_eq!(y.len(), 1); + + const Z: HashMap<(), (), BuildHasherDefault> = Default::default(); + assert_eq!(X, Z); } diff --git a/library/std/src/collections/hash/set.rs b/library/std/src/collections/hash/set.rs index 02a4a0d9c815..3f3d601e4d30 100644 --- a/library/std/src/collections/hash/set.rs +++ b/library/std/src/collections/hash/set.rs @@ -1236,14 +1236,15 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for HashSet +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +impl const Default for HashSet where - S: Default, + S: [const] Default, { /// Creates an empty `HashSet` with the `Default` value for the hasher. #[inline] fn default() -> HashSet { - HashSet { base: Default::default() } + HashSet { base: base::HashSet::with_hasher(Default::default()) } } } diff --git a/library/std/src/collections/hash/set/tests.rs b/library/std/src/collections/hash/set/tests.rs index 8ee8a3e8bf6a..d7bbc7bdc6a5 100644 --- a/library/std/src/collections/hash/set/tests.rs +++ b/library/std/src/collections/hash/set/tests.rs @@ -504,7 +504,9 @@ fn from_array() { #[test] fn const_with_hasher() { const X: HashSet<(), ()> = HashSet::with_hasher(()); + const Y: HashSet<(), ()> = Default::default(); assert_eq!(X.len(), 0); + assert_eq!(Y.len(), 0); } #[test] diff --git a/library/std/src/hash/random.rs b/library/std/src/hash/random.rs index 236803b24a2e..fab090e31f03 100644 --- a/library/std/src/hash/random.rs +++ b/library/std/src/hash/random.rs @@ -105,14 +105,16 @@ impl DefaultHasher { #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] #[inline] #[allow(deprecated)] + #[rustc_const_unstable(feature = "const_default", issue = "143894")] #[must_use] - pub fn new() -> DefaultHasher { + pub const fn new() -> DefaultHasher { DefaultHasher(SipHasher13::new_with_keys(0, 0)) } } #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] -impl Default for DefaultHasher { +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +impl const Default for DefaultHasher { /// Creates a new `DefaultHasher` using [`new`]. /// See its documentation for more. /// From bad82f22a9f1e1972fb5000e5e1c03fc3281aa7a Mon Sep 17 00:00:00 2001 From: tuturuu Date: Fri, 16 Jan 2026 17:51:43 +0100 Subject: [PATCH 084/146] move tests --- .../elided-self-lifetime-in-trait-fn.rs} | 0 .../elided-self-lifetime-in-trait-fn.stderr} | 2 +- .../struct_pattern_on_tuple_enum_in_match.rs} | 0 .../struct_pattern_on_tuple_enum_in_match.stderr} | 2 +- .../trait_more_private_than_item.rs} | 0 .../trait_more_private_than_item.stderr} | 4 ++-- .../{issues/issue-18119.rs => resolve/impl-on-non-type.rs} | 0 .../issue-18119.stderr => resolve/impl-on-non-type.stderr} | 6 +++--- .../issue-17994.rs => type-alias/unused_type_parameter.rs} | 0 .../unused_type_parameter.stderr} | 2 +- 10 files changed, 8 insertions(+), 8 deletions(-) rename tests/ui/{issues/issue-16683.rs => lifetimes/elided-self-lifetime-in-trait-fn.rs} (100%) rename tests/ui/{issues/issue-16683.stderr => lifetimes/elided-self-lifetime-in-trait-fn.stderr} (87%) rename tests/ui/{issues/issue-17405.rs => mismatched_types/struct_pattern_on_tuple_enum_in_match.rs} (100%) rename tests/ui/{issues/issue-17405.stderr => mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr} (82%) rename tests/ui/{issues/issue-18389.rs => privacy/trait_more_private_than_item.rs} (100%) rename tests/ui/{issues/issue-18389.stderr => privacy/trait_more_private_than_item.stderr} (85%) rename tests/ui/{issues/issue-18119.rs => resolve/impl-on-non-type.rs} (100%) rename tests/ui/{issues/issue-18119.stderr => resolve/impl-on-non-type.stderr} (78%) rename tests/ui/{issues/issue-17994.rs => type-alias/unused_type_parameter.rs} (100%) rename tests/ui/{issues/issue-17994.stderr => type-alias/unused_type_parameter.stderr} (88%) diff --git a/tests/ui/issues/issue-16683.rs b/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.rs similarity index 100% rename from tests/ui/issues/issue-16683.rs rename to tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.rs diff --git a/tests/ui/issues/issue-16683.stderr b/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.stderr similarity index 87% rename from tests/ui/issues/issue-16683.stderr rename to tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.stderr index 39b22ed1f156..127f1ab99457 100644 --- a/tests/ui/issues/issue-16683.stderr +++ b/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.stderr @@ -1,5 +1,5 @@ error: lifetime may not live long enough - --> $DIR/issue-16683.rs:4:9 + --> $DIR/elided-self-lifetime-in-trait-fn.rs:4:9 | LL | trait T<'a> { | -- lifetime `'a` defined here diff --git a/tests/ui/issues/issue-17405.rs b/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.rs similarity index 100% rename from tests/ui/issues/issue-17405.rs rename to tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.rs diff --git a/tests/ui/issues/issue-17405.stderr b/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr similarity index 82% rename from tests/ui/issues/issue-17405.stderr rename to tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr index 47f5bf4dc330..52da5c9b9cb3 100644 --- a/tests/ui/issues/issue-17405.stderr +++ b/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr @@ -1,5 +1,5 @@ error[E0574]: expected struct, variant or union type, found enum `Foo` - --> $DIR/issue-17405.rs:7:9 + --> $DIR/struct_pattern_on_tuple_enum_in_match.rs:7:9 | LL | Foo { i } => () | ^^^ not a struct, variant or union type diff --git a/tests/ui/issues/issue-18389.rs b/tests/ui/privacy/trait_more_private_than_item.rs similarity index 100% rename from tests/ui/issues/issue-18389.rs rename to tests/ui/privacy/trait_more_private_than_item.rs diff --git a/tests/ui/issues/issue-18389.stderr b/tests/ui/privacy/trait_more_private_than_item.stderr similarity index 85% rename from tests/ui/issues/issue-18389.stderr rename to tests/ui/privacy/trait_more_private_than_item.stderr index 4706d1ba1779..7ec3a1030599 100644 --- a/tests/ui/issues/issue-18389.stderr +++ b/tests/ui/privacy/trait_more_private_than_item.stderr @@ -1,5 +1,5 @@ warning: trait `Private<::P, ::R>` is more private than the item `Public` - --> $DIR/issue-18389.rs:9:1 + --> $DIR/trait_more_private_than_item.rs:9:1 | LL | / pub trait Public: Private< LL | | @@ -9,7 +9,7 @@ LL | | > { | |_^ trait `Public` is reachable at visibility `pub` | note: but trait `Private<::P, ::R>` is only usable at visibility `pub(crate)` - --> $DIR/issue-18389.rs:6:1 + --> $DIR/trait_more_private_than_item.rs:6:1 | LL | trait Private { | ^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/issues/issue-18119.rs b/tests/ui/resolve/impl-on-non-type.rs similarity index 100% rename from tests/ui/issues/issue-18119.rs rename to tests/ui/resolve/impl-on-non-type.rs diff --git a/tests/ui/issues/issue-18119.stderr b/tests/ui/resolve/impl-on-non-type.stderr similarity index 78% rename from tests/ui/issues/issue-18119.stderr rename to tests/ui/resolve/impl-on-non-type.stderr index ddee5a9da7a4..e29ac90b297c 100644 --- a/tests/ui/issues/issue-18119.stderr +++ b/tests/ui/resolve/impl-on-non-type.stderr @@ -1,17 +1,17 @@ error[E0573]: expected type, found constant `X` - --> $DIR/issue-18119.rs:5:6 + --> $DIR/impl-on-non-type.rs:5:6 | LL | impl X {} | ^ not a type error[E0573]: expected type, found static `Y` - --> $DIR/issue-18119.rs:7:6 + --> $DIR/impl-on-non-type.rs:7:6 | LL | impl Y {} | ^ not a type error[E0573]: expected type, found function `foo` - --> $DIR/issue-18119.rs:9:6 + --> $DIR/impl-on-non-type.rs:9:6 | LL | impl foo {} | ^^^ not a type diff --git a/tests/ui/issues/issue-17994.rs b/tests/ui/type-alias/unused_type_parameter.rs similarity index 100% rename from tests/ui/issues/issue-17994.rs rename to tests/ui/type-alias/unused_type_parameter.rs diff --git a/tests/ui/issues/issue-17994.stderr b/tests/ui/type-alias/unused_type_parameter.stderr similarity index 88% rename from tests/ui/issues/issue-17994.stderr rename to tests/ui/type-alias/unused_type_parameter.stderr index f149e5d08faa..4c9f356ebbee 100644 --- a/tests/ui/issues/issue-17994.stderr +++ b/tests/ui/type-alias/unused_type_parameter.stderr @@ -1,5 +1,5 @@ error[E0091]: type parameter `T` is never used - --> $DIR/issue-17994.rs:2:10 + --> $DIR/unused_type_parameter.rs:2:10 | LL | type Huh where T: Tr = isize; | ^ unused type parameter From 9d1a1ae298f47bbc319ae5ea8c5e6164e9ad8a46 Mon Sep 17 00:00:00 2001 From: tuturuu Date: Fri, 16 Jan 2026 18:15:09 +0100 Subject: [PATCH 085/146] add tests metadata, regenerate stderr --- tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.rs | 1 + tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.stderr | 2 +- .../struct_pattern_on_tuple_enum_in_match.rs | 1 + .../struct_pattern_on_tuple_enum_in_match.stderr | 2 +- tests/ui/privacy/trait_more_private_than_item.rs | 1 + tests/ui/privacy/trait_more_private_than_item.stderr | 4 ++-- tests/ui/resolve/impl-on-non-type.rs | 1 + tests/ui/resolve/impl-on-non-type.stderr | 6 +++--- tests/ui/type-alias/unused_type_parameter.rs | 1 + tests/ui/type-alias/unused_type_parameter.stderr | 2 +- 10 files changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.rs b/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.rs index 72fa21bddd18..5ac39c6f5d9b 100644 --- a/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.rs +++ b/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.rs @@ -1,3 +1,4 @@ +//! regression test for trait T<'a> { fn a(&'a self) -> &'a bool; fn b(&self) { diff --git a/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.stderr b/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.stderr index 127f1ab99457..383afaf782f9 100644 --- a/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.stderr +++ b/tests/ui/lifetimes/elided-self-lifetime-in-trait-fn.stderr @@ -1,5 +1,5 @@ error: lifetime may not live long enough - --> $DIR/elided-self-lifetime-in-trait-fn.rs:4:9 + --> $DIR/elided-self-lifetime-in-trait-fn.rs:5:9 | LL | trait T<'a> { | -- lifetime `'a` defined here diff --git a/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.rs b/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.rs index 14781a7d3f7e..a82778841939 100644 --- a/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.rs +++ b/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.rs @@ -1,3 +1,4 @@ +//! regression test for enum Foo { Bar(isize) } diff --git a/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr b/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr index 52da5c9b9cb3..c9cc1580b480 100644 --- a/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr +++ b/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr @@ -1,5 +1,5 @@ error[E0574]: expected struct, variant or union type, found enum `Foo` - --> $DIR/struct_pattern_on_tuple_enum_in_match.rs:7:9 + --> $DIR/struct_pattern_on_tuple_enum_in_match.rs:8:9 | LL | Foo { i } => () | ^^^ not a struct, variant or union type diff --git a/tests/ui/privacy/trait_more_private_than_item.rs b/tests/ui/privacy/trait_more_private_than_item.rs index 0ab3f1454572..f55a494abd21 100644 --- a/tests/ui/privacy/trait_more_private_than_item.rs +++ b/tests/ui/privacy/trait_more_private_than_item.rs @@ -1,3 +1,4 @@ +//! regression test for //@ check-pass use std::any::Any; diff --git a/tests/ui/privacy/trait_more_private_than_item.stderr b/tests/ui/privacy/trait_more_private_than_item.stderr index 7ec3a1030599..03bffcd390c5 100644 --- a/tests/ui/privacy/trait_more_private_than_item.stderr +++ b/tests/ui/privacy/trait_more_private_than_item.stderr @@ -1,5 +1,5 @@ warning: trait `Private<::P, ::R>` is more private than the item `Public` - --> $DIR/trait_more_private_than_item.rs:9:1 + --> $DIR/trait_more_private_than_item.rs:10:1 | LL | / pub trait Public: Private< LL | | @@ -9,7 +9,7 @@ LL | | > { | |_^ trait `Public` is reachable at visibility `pub` | note: but trait `Private<::P, ::R>` is only usable at visibility `pub(crate)` - --> $DIR/trait_more_private_than_item.rs:6:1 + --> $DIR/trait_more_private_than_item.rs:7:1 | LL | trait Private { | ^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/resolve/impl-on-non-type.rs b/tests/ui/resolve/impl-on-non-type.rs index e48dc51a2c64..3db13d520f9f 100644 --- a/tests/ui/resolve/impl-on-non-type.rs +++ b/tests/ui/resolve/impl-on-non-type.rs @@ -1,3 +1,4 @@ +//! regression test for const X: u8 = 1; static Y: u8 = 1; fn foo() {} diff --git a/tests/ui/resolve/impl-on-non-type.stderr b/tests/ui/resolve/impl-on-non-type.stderr index e29ac90b297c..99cc405015b5 100644 --- a/tests/ui/resolve/impl-on-non-type.stderr +++ b/tests/ui/resolve/impl-on-non-type.stderr @@ -1,17 +1,17 @@ error[E0573]: expected type, found constant `X` - --> $DIR/impl-on-non-type.rs:5:6 + --> $DIR/impl-on-non-type.rs:6:6 | LL | impl X {} | ^ not a type error[E0573]: expected type, found static `Y` - --> $DIR/impl-on-non-type.rs:7:6 + --> $DIR/impl-on-non-type.rs:8:6 | LL | impl Y {} | ^ not a type error[E0573]: expected type, found function `foo` - --> $DIR/impl-on-non-type.rs:9:6 + --> $DIR/impl-on-non-type.rs:10:6 | LL | impl foo {} | ^^^ not a type diff --git a/tests/ui/type-alias/unused_type_parameter.rs b/tests/ui/type-alias/unused_type_parameter.rs index ab37a172eaa7..64fb98be1bf7 100644 --- a/tests/ui/type-alias/unused_type_parameter.rs +++ b/tests/ui/type-alias/unused_type_parameter.rs @@ -1,3 +1,4 @@ +//! regression test for trait Tr {} type Huh where T: Tr = isize; //~ ERROR type parameter `T` is never used fn main() {} diff --git a/tests/ui/type-alias/unused_type_parameter.stderr b/tests/ui/type-alias/unused_type_parameter.stderr index 4c9f356ebbee..a9ddbc8c5001 100644 --- a/tests/ui/type-alias/unused_type_parameter.stderr +++ b/tests/ui/type-alias/unused_type_parameter.stderr @@ -1,5 +1,5 @@ error[E0091]: type parameter `T` is never used - --> $DIR/unused_type_parameter.rs:2:10 + --> $DIR/unused_type_parameter.rs:3:10 | LL | type Huh where T: Tr = isize; | ^ unused type parameter From 4530e26f4eec47b92061d9ab3fca18ed8db97e63 Mon Sep 17 00:00:00 2001 From: Martin Nordholts Date: Fri, 16 Jan 2026 17:47:42 +0100 Subject: [PATCH 086/146] compiletest: Add `AuxCrate` struct with docs. To make the code clearer. --- src/tools/compiletest/src/directives.rs | 2 +- .../compiletest/src/directives/auxiliary.rs | 24 +++++++++++++------ src/tools/compiletest/src/runtest.rs | 8 +++---- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index 624f4dd7c2b1..0263b91f50b8 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -8,8 +8,8 @@ use tracing::*; use crate::common::{CodegenBackend, Config, Debugger, FailMode, PassMode, RunFailMode, TestMode}; use crate::debuggers::{extract_cdb_version, extract_gdb_version}; -pub(crate) use crate::directives::auxiliary::AuxProps; use crate::directives::auxiliary::parse_and_update_aux; +pub(crate) use crate::directives::auxiliary::{AuxCrate, AuxProps}; use crate::directives::directive_names::{ KNOWN_DIRECTIVE_NAMES_SET, KNOWN_HTMLDOCCK_DIRECTIVE_NAMES, KNOWN_JSONDOCCK_DIRECTIVE_NAMES, }; diff --git a/src/tools/compiletest/src/directives/auxiliary.rs b/src/tools/compiletest/src/directives/auxiliary.rs index 40e2e7049c8f..1b72931949c5 100644 --- a/src/tools/compiletest/src/directives/auxiliary.rs +++ b/src/tools/compiletest/src/directives/auxiliary.rs @@ -7,6 +7,16 @@ use super::directives::{AUX_BIN, AUX_BUILD, AUX_CODEGEN_BACKEND, AUX_CRATE, PROC use crate::common::Config; use crate::directives::DirectiveLine; +/// The value of an `aux-crate` directive. +#[derive(Clone, Debug, Default)] +pub struct AuxCrate { + /// With `aux-crate: foo=bar.rs` this will be `foo`. + /// With `aux-crate: noprelude:foo=bar.rs` this will be `noprelude:foo`. + pub name: String, + /// With `aux-crate: foo=bar.rs` this will be `bar.rs`. + pub path: String, +} + /// Properties parsed from `aux-*` test directives. #[derive(Clone, Debug, Default)] pub(crate) struct AuxProps { @@ -17,7 +27,7 @@ pub(crate) struct AuxProps { pub(crate) bins: Vec, /// Similar to `builds`, but a list of NAME=somelib.rs of dependencies /// to build and pass with the `--extern` flag. - pub(crate) crates: Vec<(String, String)>, + pub(crate) crates: Vec, /// Same as `builds`, but for proc-macros. pub(crate) proc_macros: Vec, /// Similar to `builds`, but also uses the resulting dylib as a @@ -34,7 +44,7 @@ impl AuxProps { iter::empty() .chain(builds.iter().map(String::as_str)) .chain(bins.iter().map(String::as_str)) - .chain(crates.iter().map(|(_, path)| path.as_str())) + .chain(crates.iter().map(|c| c.path.as_str())) .chain(proc_macros.iter().map(String::as_str)) .chain(codegen_backend.iter().map(String::as_str)) } @@ -63,10 +73,10 @@ pub(super) fn parse_and_update_aux( } } -fn parse_aux_crate(r: String) -> (String, String) { +fn parse_aux_crate(r: String) -> AuxCrate { let mut parts = r.trim().splitn(2, '='); - ( - parts.next().expect("missing aux-crate name (e.g. log=log.rs)").to_string(), - parts.next().expect("missing aux-crate value (e.g. log=log.rs)").to_string(), - ) + AuxCrate { + name: parts.next().expect("missing aux-crate name (e.g. log=log.rs)").to_string(), + path: parts.next().expect("missing aux-crate value (e.g. log=log.rs)").to_string(), + } } diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 6efdb5a99ee2..901ce8421ebf 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -18,7 +18,7 @@ use crate::common::{ TestSuite, UI_EXTENSIONS, UI_FIXED, UI_RUN_STDERR, UI_RUN_STDOUT, UI_STDERR, UI_STDOUT, UI_SVG, UI_WINDOWS_SVG, expected_output_path, incremental_dir, output_base_dir, output_base_name, }; -use crate::directives::TestProps; +use crate::directives::{AuxCrate, TestProps}; use crate::errors::{Error, ErrorKind, load_errors}; use crate::output_capture::ConsoleOut; use crate::read2::{Truncated, read2_abbreviated}; @@ -1285,9 +1285,9 @@ impl<'test> TestCx<'test> { } }; - for (aux_name, aux_path) in &self.props.aux.crates { - let aux_type = self.build_auxiliary(&aux_path, &aux_dir, None); - add_extern(rustc, aux_name, aux_path, aux_type); + for AuxCrate { name, path } in &self.props.aux.crates { + let aux_type = self.build_auxiliary(&path, &aux_dir, None); + add_extern(rustc, name, path, aux_type); } for proc_macro in &self.props.aux.proc_macros { From b323651ded6429a4205af1de65af01503dfe59eb Mon Sep 17 00:00:00 2001 From: tuturuu Date: Fri, 16 Jan 2026 20:55:37 +0100 Subject: [PATCH 087/146] move struct_pattern_on_tuple_enum to ui/pattern --- .../struct_pattern_on_tuple_enum.rs} | 0 .../struct_pattern_on_tuple_enum.stderr} | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename tests/ui/{mismatched_types/struct_pattern_on_tuple_enum_in_match.rs => pattern/struct_pattern_on_tuple_enum.rs} (100%) rename tests/ui/{mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr => pattern/struct_pattern_on_tuple_enum.stderr} (82%) diff --git a/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.rs b/tests/ui/pattern/struct_pattern_on_tuple_enum.rs similarity index 100% rename from tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.rs rename to tests/ui/pattern/struct_pattern_on_tuple_enum.rs diff --git a/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr b/tests/ui/pattern/struct_pattern_on_tuple_enum.stderr similarity index 82% rename from tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr rename to tests/ui/pattern/struct_pattern_on_tuple_enum.stderr index c9cc1580b480..a322b363aa9c 100644 --- a/tests/ui/mismatched_types/struct_pattern_on_tuple_enum_in_match.stderr +++ b/tests/ui/pattern/struct_pattern_on_tuple_enum.stderr @@ -1,5 +1,5 @@ error[E0574]: expected struct, variant or union type, found enum `Foo` - --> $DIR/struct_pattern_on_tuple_enum_in_match.rs:8:9 + --> $DIR/struct_pattern_on_tuple_enum.rs:8:9 | LL | Foo { i } => () | ^^^ not a struct, variant or union type From 5c85d522d0083bee0d5fd7f26868fa0e62372485 Mon Sep 17 00:00:00 2001 From: Manuel Drehwald Date: Tue, 13 Jan 2026 09:52:36 -0800 Subject: [PATCH 088/146] Generate global openmp metadata to trigger llvm openmp-opt pass --- compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs | 4 ++++ tests/codegen-llvm/gpu_offload/gpu_host.rs | 2 ++ 2 files changed, 6 insertions(+) diff --git a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs index b8eb4f038216..084d40317ba8 100644 --- a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs +++ b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs @@ -55,6 +55,10 @@ impl<'ll> OffloadGlobals<'ll> { let init_ty = cx.type_func(&[], cx.type_void()); let init_rtls = declare_offload_fn(cx, "__tgt_init_all_rtls", init_ty); + // We want LLVM's openmp-opt pass to pick up and optimize this module, since it covers both + // openmp and offload optimizations. + llvm::add_module_flag_u32(cx.llmod(), llvm::ModuleFlagMergeBehavior::Max, "openmp", 51); + OffloadGlobals { launcher_fn, launcher_ty, diff --git a/tests/codegen-llvm/gpu_offload/gpu_host.rs b/tests/codegen-llvm/gpu_offload/gpu_host.rs index dcbd65b14427..27ff6f325aa0 100644 --- a/tests/codegen-llvm/gpu_offload/gpu_host.rs +++ b/tests/codegen-llvm/gpu_offload/gpu_host.rs @@ -104,3 +104,5 @@ pub fn _kernel_1(x: &mut [f32; 256]) { // CHECK-NEXT: call void @__tgt_unregister_lib(ptr nonnull %EmptyDesc) // CHECK-NEXT: ret void // CHECK-NEXT: } + +// CHECK: !{i32 7, !"openmp", i32 51} From 500c94f94517a7bf2df86e04bb900ab35aca1678 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Fri, 16 Jan 2026 15:45:53 -0500 Subject: [PATCH 089/146] Update cargo submodule --- src/tools/cargo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/cargo b/src/tools/cargo index 6d1bd93c47f0..85eff7c80277 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 6d1bd93c47f059ec1344cb31e68a2fb284cbc6b1 +Subproject commit 85eff7c80277b57f78b11e28d14154ab12fcf643 From 79f12eb1ed02e763dafe13938996f69e6b0b5f7a Mon Sep 17 00:00:00 2001 From: dianne Date: Fri, 16 Jan 2026 15:42:25 -0800 Subject: [PATCH 090/146] remove some confusing mutation `oprnd_t` was used both for the type of the operand of a unary operator and for the type of the operator expression as a whole. Now it's only used for the operand's type. --- compiler/rustc_hir_typeck/src/expr.rs | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 9f3ff0b2d03c..1d7faf1345cf 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -434,14 +434,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::UnOp::Not | hir::UnOp::Neg => expected, hir::UnOp::Deref => NoExpectation, }; - let mut oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner); + let oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner); - if !oprnd_t.references_error() { - oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t); + if let Err(guar) = oprnd_t.error_reported() { + Ty::new_error(tcx, guar) + } else { + let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t); match unop { hir::UnOp::Deref => { if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) { - oprnd_t = ty; + ty } else { let mut err = self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t }); @@ -451,26 +453,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp)); } - oprnd_t = Ty::new_error(tcx, err.emit()); + Ty::new_error(tcx, err.emit()) } } hir::UnOp::Not => { let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner); // If it's builtin, we can reuse the type, this helps inference. - if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) { - oprnd_t = result; + if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { + oprnd_t + } else { + result } } hir::UnOp::Neg => { let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner); // If it's builtin, we can reuse the type, this helps inference. - if !oprnd_t.is_numeric() { - oprnd_t = result; - } + if oprnd_t.is_numeric() { oprnd_t } else { result } } } } - oprnd_t } fn check_expr_addr_of( From 91bbb692d5a32faae9a8fb3f212f518bd98ff3cd Mon Sep 17 00:00:00 2001 From: dianne Date: Fri, 16 Jan 2026 15:51:29 -0800 Subject: [PATCH 091/146] re-style `check_expr_unop` --- compiler/rustc_hir_typeck/src/expr.rs | 54 +++++++++++---------------- 1 file changed, 22 insertions(+), 32 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 1d7faf1345cf..885af3b909b8 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -437,39 +437,29 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner); if let Err(guar) = oprnd_t.error_reported() { - Ty::new_error(tcx, guar) - } else { - let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t); - match unop { - hir::UnOp::Deref => { - if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) { - ty - } else { - let mut err = - self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t }); - let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None); - if let Some(sp) = - tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) - { - err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp)); - } - Ty::new_error(tcx, err.emit()) - } - } - hir::UnOp::Not => { - let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner); - // If it's builtin, we can reuse the type, this helps inference. - if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { - oprnd_t - } else { - result - } - } - hir::UnOp::Neg => { - let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner); - // If it's builtin, we can reuse the type, this helps inference. - if oprnd_t.is_numeric() { oprnd_t } else { result } + return Ty::new_error(tcx, guar); + } + + let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t); + match unop { + hir::UnOp::Deref => self.lookup_derefing(expr, oprnd, oprnd_t).unwrap_or_else(|| { + let mut err = + self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t }); + let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None); + if let Some(sp) = tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) { + err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp)); } + Ty::new_error(tcx, err.emit()) + }), + hir::UnOp::Not => { + let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner); + // If it's builtin, we can reuse the type, this helps inference. + if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { oprnd_t } else { result } + } + hir::UnOp::Neg => { + let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner); + // If it's builtin, we can reuse the type, this helps inference. + if oprnd_t.is_numeric() { oprnd_t } else { result } } } } From c7031e93c50ad46601993efe6d7e6139977bd1a2 Mon Sep 17 00:00:00 2001 From: Jamie Hill-Daniel Date: Fri, 16 Jan 2026 18:31:11 +0000 Subject: [PATCH 092/146] feat: Support references in reflection type info --- .../src/const_eval/type_info.rs | 35 ++++++++++++++- compiler/rustc_span/src/symbol.rs | 2 + library/core/src/mem/type_info.rs | 13 ++++++ library/coretests/tests/mem/type_info.rs | 32 +++++++++++++- tests/ui/reflection/dump.bit32.run.stdout | 43 +++++++++++++++++-- tests/ui/reflection/dump.bit64.run.stdout | 43 +++++++++++++++++-- tests/ui/reflection/dump.rs | 1 + 7 files changed, 161 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index 5d37db06d76a..3c6064d3f87d 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -1,4 +1,5 @@ use rustc_abi::FieldIdx; +use rustc_ast::Mutability; use rustc_hir::LangItem; use rustc_middle::mir::interpret::{CtfeProvenance, Scalar}; use rustc_middle::span_bug; @@ -103,12 +104,19 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { let (variant, _variant_place) = downcast(sym::Str)?; variant } + ty::Ref(_, ty, mutability) => { + let (variant, variant_place) = downcast(sym::Reference)?; + let reference_place = + self.project_field(&variant_place, FieldIdx::ZERO)?; + self.write_reference_type_info(reference_place, *ty, *mutability)?; + + variant + } ty::Adt(_, _) | ty::Foreign(_) | ty::Pat(_, _) | ty::Slice(_) | ty::RawPtr(..) - | ty::Ref(..) | ty::FnDef(..) | ty::FnPtr(..) | ty::UnsafeBinder(..) @@ -279,4 +287,29 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { } interp_ok(()) } + + pub(crate) fn write_reference_type_info( + &mut self, + place: impl Writeable<'tcx, CtfeProvenance>, + ty: Ty<'tcx>, + mutability: Mutability, + ) -> InterpResult<'tcx> { + // Iterate over all fields of `type_info::Reference`. + for (field_idx, field) in + place.layout().ty.ty_adt_def().unwrap().non_enum_variant().fields.iter_enumerated() + { + let field_place = self.project_field(&place, field_idx)?; + + match field.name { + // Write the `TypeId` of the reference's inner type to the `ty` field. + sym::pointee => self.write_type_id(ty, &field_place)?, + // Write the boolean representing the reference's mutability to the `mutable` field. + sym::mutable => { + self.write_scalar(Scalar::from_bool(mutability.is_mut()), &field_place)? + } + other => span_bug!(self.tcx.def_span(field.did), "unimplemented field {other}"), + } + } + interp_ok(()) + } } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 51920db8cd79..f0576002354d 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -343,6 +343,7 @@ symbols! { RefCell, RefCellRef, RefCellRefMut, + Reference, Relaxed, Release, Result, @@ -1521,6 +1522,7 @@ symbols! { must_use, mut_preserve_binding_mode_2024, mut_ref, + mutable, naked, naked_asm, naked_functions, diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 2e3bdb45ce05..ee647ef55840 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -55,6 +55,8 @@ pub enum TypeKind { Float(Float), /// String slice type. Str(Str), + /// References. + Reference(Reference), /// FIXME(#146922): add all the common types Other, } @@ -133,3 +135,14 @@ pub struct Float { pub struct Str { // No additional information to provide for now. } + +/// Compile-time type information about references. +#[derive(Debug)] +#[non_exhaustive] +#[unstable(feature = "type_info", issue = "146922")] +pub struct Reference { + /// The type of the value being referred to. + pub pointee: TypeId, + /// Whether this reference is mutable or not. + pub mutable: bool, +} diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index fc13637a5574..7df632981ce1 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -1,4 +1,4 @@ -use std::any::TypeId; +use std::any::{Any, TypeId}; use std::mem::type_info::{Type, TypeKind}; #[test] @@ -95,3 +95,33 @@ fn test_primitives() { let Type { kind: Str(_ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, None); } + +#[test] +fn test_references() { + // Immutable reference. + match const { Type::of::<&u8>() }.kind { + TypeKind::Reference(reference) => { + assert_eq!(reference.pointee, TypeId::of::()); + assert!(!reference.mutable); + } + _ => unreachable!(), + } + + // Mutable pointer. + match const { Type::of::<&mut u64>() }.kind { + TypeKind::Reference(reference) => { + assert_eq!(reference.pointee, TypeId::of::()); + assert!(reference.mutable); + } + _ => unreachable!(), + } + + // Wide pointer. + match const { Type::of::<&dyn Any>() }.kind { + TypeKind::Reference(reference) => { + assert_eq!(reference.pointee, TypeId::of::()); + assert!(!reference.mutable); + } + _ => unreachable!(), + } +} diff --git a/tests/ui/reflection/dump.bit32.run.stdout b/tests/ui/reflection/dump.bit32.run.stdout index 483efdbbd12a..8d0398bdd53a 100644 --- a/tests/ui/reflection/dump.bit32.run.stdout +++ b/tests/ui/reflection/dump.bit32.run.stdout @@ -155,19 +155,34 @@ Type { ), } Type { - kind: Other, + kind: Reference( + Reference { + pointee: TypeId(0xda1b6da9bd297bb2900de9303aadea79), + mutable: false, + }, + ), size: Some( 8, ), } Type { - kind: Other, + kind: Reference( + Reference { + pointee: TypeId(0x474ccf3b5db264ef53916706f7d7bb2c), + mutable: false, + }, + ), size: Some( 8, ), } Type { - kind: Other, + kind: Reference( + Reference { + pointee: TypeId(0x641e3def269c37acc6dcb92bf8c5f196), + mutable: false, + }, + ), size: Some( 8, ), @@ -182,3 +197,25 @@ Type { kind: Other, size: None, } +Type { + kind: Reference( + Reference { + pointee: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + mutable: false, + }, + ), + size: Some( + 4, + ), +} +Type { + kind: Reference( + Reference { + pointee: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + mutable: true, + }, + ), + size: Some( + 4, + ), +} diff --git a/tests/ui/reflection/dump.bit64.run.stdout b/tests/ui/reflection/dump.bit64.run.stdout index 681e81b71d56..3564922fc171 100644 --- a/tests/ui/reflection/dump.bit64.run.stdout +++ b/tests/ui/reflection/dump.bit64.run.stdout @@ -155,19 +155,34 @@ Type { ), } Type { - kind: Other, + kind: Reference( + Reference { + pointee: TypeId(0xda1b6da9bd297bb2900de9303aadea79), + mutable: false, + }, + ), size: Some( 16, ), } Type { - kind: Other, + kind: Reference( + Reference { + pointee: TypeId(0x474ccf3b5db264ef53916706f7d7bb2c), + mutable: false, + }, + ), size: Some( 16, ), } Type { - kind: Other, + kind: Reference( + Reference { + pointee: TypeId(0x641e3def269c37acc6dcb92bf8c5f196), + mutable: false, + }, + ), size: Some( 16, ), @@ -182,3 +197,25 @@ Type { kind: Other, size: None, } +Type { + kind: Reference( + Reference { + pointee: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + mutable: false, + }, + ), + size: Some( + 8, + ), +} +Type { + kind: Reference( + Reference { + pointee: TypeId(0x0596b48cc04376e64d5c788c2aa46bdb), + mutable: true, + }, + ), + size: Some( + 8, + ), +} diff --git a/tests/ui/reflection/dump.rs b/tests/ui/reflection/dump.rs index 584b7c8ed4ae..d42216a62fdc 100644 --- a/tests/ui/reflection/dump.rs +++ b/tests/ui/reflection/dump.rs @@ -40,5 +40,6 @@ fn main() { Foo, Bar, &Unsized, &str, &[u8], str, [u8], + &u8, &mut u8, } } From 27b02796609e43103ce06a5c38cfc82e029c53c7 Mon Sep 17 00:00:00 2001 From: Asuna Date: Sat, 17 Jan 2026 01:53:08 +0100 Subject: [PATCH 093/146] Change field `bit_width: usize` to `bits: u32` in type info --- .../src/const_eval/type_info.rs | 8 ++++---- compiler/rustc_span/src/symbol.rs | 2 +- library/core/src/mem/type_info.rs | 4 ++-- library/coretests/tests/mem/type_info.rs | 14 ++++++------- tests/ui/reflection/dump.bit32.run.stdout | 20 +++++++++---------- tests/ui/reflection/dump.bit64.run.stdout | 20 +++++++++---------- 6 files changed, 34 insertions(+), 34 deletions(-) diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index 5d37db06d76a..195714b1c0e6 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -249,8 +249,8 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { { let field_place = self.project_field(&place, field_idx)?; match field.name { - sym::bit_width => self.write_scalar( - ScalarInt::try_from_target_usize(bit_width, self.tcx.tcx).unwrap(), + sym::bits => self.write_scalar( + Scalar::from_u32(bit_width.try_into().expect("bit_width overflowed")), &field_place, )?, sym::signed => self.write_scalar(Scalar::from_bool(signed), &field_place)?, @@ -270,8 +270,8 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { { let field_place = self.project_field(&place, field_idx)?; match field.name { - sym::bit_width => self.write_scalar( - ScalarInt::try_from_target_usize(bit_width, self.tcx.tcx).unwrap(), + sym::bits => self.write_scalar( + Scalar::from_u32(bit_width.try_into().expect("bit_width overflowed")), &field_place, )?, other => span_bug!(self.tcx.def_span(field.did), "unimplemented field {other}"), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 51920db8cd79..2bd9ee6a6123 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -589,12 +589,12 @@ symbols! { binaryheap_iter, bind_by_move_pattern_guards, bindings_after_at, - bit_width, bitand, bitand_assign, bitor, bitor_assign, bitreverse, + bits, bitxor, bitxor_assign, black_box, diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 2e3bdb45ce05..5a105573db77 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -112,7 +112,7 @@ pub struct Char { #[unstable(feature = "type_info", issue = "146922")] pub struct Int { /// The bit width of the signed integer type. - pub bit_width: usize, + pub bits: u32, /// Whether the integer type is signed. pub signed: bool, } @@ -123,7 +123,7 @@ pub struct Int { #[unstable(feature = "type_info", issue = "146922")] pub struct Float { /// The bit width of the floating-point type. - pub bit_width: usize, + pub bits: u32, } /// Compile-time type information about string slice types. diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index fc13637a5574..53195fc5be0e 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -47,8 +47,8 @@ fn test_tuples() { match (a.ty.info().kind, b.ty.info().kind) { (TypeKind::Int(a), TypeKind::Int(b)) => { - assert!(a.bit_width == 8 && a.signed); - assert!(b.bit_width == 8 && !b.signed); + assert!(a.bits == 8 && a.signed); + assert!(b.bits == 8 && !b.signed); } _ => unreachable!(), } @@ -70,27 +70,27 @@ fn test_primitives() { let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(4)); - assert_eq!(ty.bit_width, 32); + assert_eq!(ty.bits, 32); assert!(ty.signed); let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(size_of::())); - assert_eq!(ty.bit_width, size_of::() * 8); + assert_eq!(ty.bits as usize, size_of::() * 8); assert!(ty.signed); let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(4)); - assert_eq!(ty.bit_width, 32); + assert_eq!(ty.bits, 32); assert!(!ty.signed); let Type { kind: Int(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(size_of::())); - assert_eq!(ty.bit_width, size_of::() * 8); + assert_eq!(ty.bits as usize, size_of::() * 8); assert!(!ty.signed); let Type { kind: Float(ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, Some(4)); - assert_eq!(ty.bit_width, 32); + assert_eq!(ty.bits, 32); let Type { kind: Str(_ty), size, .. } = (const { Type::of::() }) else { panic!() }; assert_eq!(size, None); diff --git a/tests/ui/reflection/dump.bit32.run.stdout b/tests/ui/reflection/dump.bit32.run.stdout index 483efdbbd12a..c086cdd11aff 100644 --- a/tests/ui/reflection/dump.bit32.run.stdout +++ b/tests/ui/reflection/dump.bit32.run.stdout @@ -35,7 +35,7 @@ Type { Type { kind: Int( Int { - bit_width: 8, + bits: 8, signed: true, }, ), @@ -46,7 +46,7 @@ Type { Type { kind: Int( Int { - bit_width: 32, + bits: 32, signed: true, }, ), @@ -57,7 +57,7 @@ Type { Type { kind: Int( Int { - bit_width: 64, + bits: 64, signed: true, }, ), @@ -68,7 +68,7 @@ Type { Type { kind: Int( Int { - bit_width: 128, + bits: 128, signed: true, }, ), @@ -79,7 +79,7 @@ Type { Type { kind: Int( Int { - bit_width: 32, + bits: 32, signed: true, }, ), @@ -90,7 +90,7 @@ Type { Type { kind: Int( Int { - bit_width: 8, + bits: 8, signed: false, }, ), @@ -101,7 +101,7 @@ Type { Type { kind: Int( Int { - bit_width: 32, + bits: 32, signed: false, }, ), @@ -112,7 +112,7 @@ Type { Type { kind: Int( Int { - bit_width: 64, + bits: 64, signed: false, }, ), @@ -123,7 +123,7 @@ Type { Type { kind: Int( Int { - bit_width: 128, + bits: 128, signed: false, }, ), @@ -134,7 +134,7 @@ Type { Type { kind: Int( Int { - bit_width: 32, + bits: 32, signed: false, }, ), diff --git a/tests/ui/reflection/dump.bit64.run.stdout b/tests/ui/reflection/dump.bit64.run.stdout index 681e81b71d56..5f82ab44a91d 100644 --- a/tests/ui/reflection/dump.bit64.run.stdout +++ b/tests/ui/reflection/dump.bit64.run.stdout @@ -35,7 +35,7 @@ Type { Type { kind: Int( Int { - bit_width: 8, + bits: 8, signed: true, }, ), @@ -46,7 +46,7 @@ Type { Type { kind: Int( Int { - bit_width: 32, + bits: 32, signed: true, }, ), @@ -57,7 +57,7 @@ Type { Type { kind: Int( Int { - bit_width: 64, + bits: 64, signed: true, }, ), @@ -68,7 +68,7 @@ Type { Type { kind: Int( Int { - bit_width: 128, + bits: 128, signed: true, }, ), @@ -79,7 +79,7 @@ Type { Type { kind: Int( Int { - bit_width: 64, + bits: 64, signed: true, }, ), @@ -90,7 +90,7 @@ Type { Type { kind: Int( Int { - bit_width: 8, + bits: 8, signed: false, }, ), @@ -101,7 +101,7 @@ Type { Type { kind: Int( Int { - bit_width: 32, + bits: 32, signed: false, }, ), @@ -112,7 +112,7 @@ Type { Type { kind: Int( Int { - bit_width: 64, + bits: 64, signed: false, }, ), @@ -123,7 +123,7 @@ Type { Type { kind: Int( Int { - bit_width: 128, + bits: 128, signed: false, }, ), @@ -134,7 +134,7 @@ Type { Type { kind: Int( Int { - bit_width: 64, + bits: 64, signed: false, }, ), From 4c93efae2b741b9df51fd55364ad08d57c2f196d Mon Sep 17 00:00:00 2001 From: Keith-Cancel Date: Tue, 13 Jan 2026 13:02:33 -0800 Subject: [PATCH 094/146] Fix ICE: When Trying to check visibility of a #[type_const], check RHS instead. We want to evaluate the rhs of a type_const. Also added an early return/guard in eval_in_interpreter which is used in functions like `eval_to_allocation_raw_provider` Lastly add a debug assert to `thir_body()` if we have gotten there with a type_const something as gone wrong. Get rid of a call to is_type_const() and instead use a match arm. Change this is_type_const() check to a debug_assert!() Change to use an if else statment instead. Update type_const-pub.rs Fix formatting. Noticed that this is the same check as is_type_const() centralize it. Add test case for pub type_const. --- .../rustc_const_eval/src/const_eval/eval_queries.rs | 4 +++- compiler/rustc_metadata/src/rmeta/encoder.rs | 5 ++--- compiler/rustc_mir_build/src/thir/cx/mod.rs | 2 ++ compiler/rustc_passes/src/reachable.rs | 5 ++++- tests/ui/const-generics/mgca/type_const-pub.rs | 10 ++++++++++ 5 files changed, 21 insertions(+), 5 deletions(-) create mode 100644 tests/ui/const-generics/mgca/type_const-pub.rs diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index beea1b4a28c9..5383ab3547af 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -394,8 +394,10 @@ fn eval_in_interpreter<'tcx, R: InterpretationResult<'tcx>>( typing_env: ty::TypingEnv<'tcx>, ) -> Result { let def = cid.instance.def.def_id(); - let is_static = tcx.is_static(def); + // #[type_const] don't have bodys + debug_assert!(!tcx.is_type_const(def), "CTFE tried to evaluate type-const: {:?}", def); + let is_static = tcx.is_static(def); let mut ecx = InterpCx::new( tcx, tcx.def_span(def), diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index a62826cd7cec..4fcc7f064f3f 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1379,9 +1379,8 @@ fn should_encode_const(def_kind: DefKind) -> bool { } fn should_encode_const_of_item<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool { - matches!(def_kind, DefKind::Const | DefKind::AssocConst) - && find_attr!(tcx.get_all_attrs(def_id), AttributeKind::TypeConst(_)) - // AssocConst ==> assoc item has value + // AssocConst ==> assoc item has value + tcx.is_type_const(def_id) && (!matches!(def_kind, DefKind::AssocConst) || assoc_item_has_value(tcx, def_id)) } diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 79e85a243f40..b08d1d4bcf27 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -18,6 +18,8 @@ pub(crate) fn thir_body( tcx: TyCtxt<'_>, owner_def: LocalDefId, ) -> Result<(&Steal>, ExprId), ErrorGuaranteed> { + debug_assert!(!tcx.is_type_const(owner_def.to_def_id()), "thir_body queried for type_const"); + let body = tcx.hir_body_owned_by(owner_def); let mut cx = ThirBuildCx::new(tcx, owner_def); if let Some(reported) = cx.typeck_results.tainted_by_errors { diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index b9323e91ca83..d9565e2dae0e 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -209,7 +209,10 @@ impl<'tcx> ReachableContext<'tcx> { self.visit_nested_body(body); } } - + // For #[type_const] we want to evaluate the RHS. + hir::ItemKind::Const(_, _, _, init @ hir::ConstItemRhs::TypeConst(_)) => { + self.visit_const_item_rhs(init); + } hir::ItemKind::Const(_, _, _, init) => { // Only things actually ending up in the final constant value are reachable // for codegen. Everything else is only needed during const-eval, so even if diff --git a/tests/ui/const-generics/mgca/type_const-pub.rs b/tests/ui/const-generics/mgca/type_const-pub.rs new file mode 100644 index 000000000000..fc5b1ce36a14 --- /dev/null +++ b/tests/ui/const-generics/mgca/type_const-pub.rs @@ -0,0 +1,10 @@ +//@ check-pass +// This previously caused an ICE when checking reachability of a pub const item +// This is because reachability also tried to evaluate the #[type_const] which +// requires the item have a body. #[type_const] do not have bodies. +#![expect(incomplete_features)] +#![feature(min_generic_const_args)] + +#[type_const] +pub const TYPE_CONST : usize = 1; +fn main() {} From ac8e8505b7c12d826f970e8e8ec8c18b067c6dc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Fri, 16 Jan 2026 21:08:01 +0100 Subject: [PATCH 095/146] rustdoc: Stop unconditionally evaluating the initializer of associated consts --- src/librustdoc/html/render/mod.rs | 9 ++--- .../anchors/anchors.no_const_anchor2.html | 2 +- tests/rustdoc-html/attributes.rs | 2 +- .../constant/assoc-const-has-projection-ty.rs | 31 +++++++++++++++++ tests/rustdoc-html/constant/assoc-consts.rs | 2 +- .../rustdoc-html/deref/deref-to-primitive.rs | 2 +- tests/rustdoc-html/display-hidden-items.rs | 4 +-- .../impl/impl-associated-items-order.rs | 4 +-- tests/rustdoc-ui/diverging-assoc-consts.rs | 33 +++++++++++++++++++ 9 files changed, 75 insertions(+), 14 deletions(-) create mode 100644 tests/rustdoc-html/constant/assoc-const-has-projection-ty.rs create mode 100644 tests/rustdoc-ui/diverging-assoc-consts.rs diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 63de870f07f4..e6fca29e23e5 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -1050,14 +1050,11 @@ fn assoc_const( ty = print_type(ty, cx), )?; if let AssocConstValue::TraitDefault(konst) | AssocConstValue::Impl(konst) = value { - // FIXME: `.value()` uses `clean::utils::format_integer_with_underscore_sep` under the - // hood which adds noisy underscores and a type suffix to number literals. - // This hurts readability in this context especially when more complex expressions - // are involved and it doesn't add much of value. - // Find a way to print constants here without all that jazz. - let repr = konst.value(tcx).unwrap_or_else(|| konst.expr(tcx)); + let repr = konst.expr(tcx); if match value { AssocConstValue::TraitDefault(_) => true, // always show + // FIXME: Comparing against the special string "_" denoting overly complex const exprs + // is rather hacky; `ConstKind::expr` should have a richer return type. AssocConstValue::Impl(_) => repr != "_", // show if there is a meaningful value to show AssocConstValue::None => unreachable!(), } { diff --git a/tests/rustdoc-html/anchors/anchors.no_const_anchor2.html b/tests/rustdoc-html/anchors/anchors.no_const_anchor2.html index 091dac3e4b26..310957ac1ae0 100644 --- a/tests/rustdoc-html/anchors/anchors.no_const_anchor2.html +++ b/tests/rustdoc-html/anchors/anchors.no_const_anchor2.html @@ -1 +1 @@ -

Source

pub const X: i32 = 0i32

\ No newline at end of file +
Source

pub const X: i32 = 0

\ No newline at end of file diff --git a/tests/rustdoc-html/attributes.rs b/tests/rustdoc-html/attributes.rs index 429a42a7252c..6032c3d38801 100644 --- a/tests/rustdoc-html/attributes.rs +++ b/tests/rustdoc-html/attributes.rs @@ -59,7 +59,7 @@ pub enum Enum { pub trait Trait { //@ has 'foo/trait.Trait.html' //@ has - '//*[@id="associatedconstant.BAR"]/*[@class="code-header"]/*[@class="code-attribute"]' '#[unsafe(link_section = "bar")]' - //@ has - '//*[@id="associatedconstant.BAR"]/*[@class="code-header"]' 'const BAR: u32 = 0u32' + //@ has - '//*[@id="associatedconstant.BAR"]/*[@class="code-header"]' 'const BAR: u32 = 0' #[unsafe(link_section = "bar")] const BAR: u32 = 0; diff --git a/tests/rustdoc-html/constant/assoc-const-has-projection-ty.rs b/tests/rustdoc-html/constant/assoc-const-has-projection-ty.rs new file mode 100644 index 000000000000..ed0789dade57 --- /dev/null +++ b/tests/rustdoc-html/constant/assoc-const-has-projection-ty.rs @@ -0,0 +1,31 @@ +// Ensure that we properly print the value `1` as `1` in the initializer of associated constants +// that have user type "projection". +// +// We once used to evaluate the initializer in rustdoc and use rustc's MIR pretty-printer to +// render the resulting MIR const value. This pretty printer matches on the type to interpret +// the data and falls back to a cryptic `"{transmute(0x$data): $ty}"` for types it can't handle. +// Crucially, when constructing the MIR const we passed the unnormalized type of the initializer, +// i.e., the projection `::Ty` instead of the normalized `u32` which the +// pretty printer obviously can't handle. +// +// Now we no longer evaluate it and use a custom printer for the const expr. +// +// issue: + +#![crate_name = "it"] + +pub trait Trait { + type Ty; + + const CT: Self::Ty; +} + +pub struct Struct; + +impl Trait for Struct { + type Ty = u32; + + //@ has it/struct.Struct.html + //@ has - '//*[@id="associatedconstant.CT"]' 'const CT: Self::Ty = 1' + const CT: Self::Ty = 1; +} diff --git a/tests/rustdoc-html/constant/assoc-consts.rs b/tests/rustdoc-html/constant/assoc-consts.rs index 247b5b180a86..0994ec7517e3 100644 --- a/tests/rustdoc-html/constant/assoc-consts.rs +++ b/tests/rustdoc-html/constant/assoc-consts.rs @@ -1,6 +1,6 @@ pub trait Foo { //@ has assoc_consts/trait.Foo.html '//pre[@class="rust item-decl"]' \ - // 'const FOO: usize = 13usize;' + // 'const FOO: usize = _;' //@ has - '//*[@id="associatedconstant.FOO"]' 'const FOO: usize' const FOO: usize = 12 + 1; //@ has - '//*[@id="associatedconstant.FOO_NO_DEFAULT"]' 'const FOO_NO_DEFAULT: bool' diff --git a/tests/rustdoc-html/deref/deref-to-primitive.rs b/tests/rustdoc-html/deref/deref-to-primitive.rs index 7a5a3cd8fd65..6fdc382b2213 100644 --- a/tests/rustdoc-html/deref/deref-to-primitive.rs +++ b/tests/rustdoc-html/deref/deref-to-primitive.rs @@ -3,7 +3,7 @@ //@ has 'foo/struct.Foo.html' //@ has - '//*[@id="deref-methods-i32"]' 'Methods from Deref' //@ has - '//*[@id="deref-methods-i32-1"]//*[@id="associatedconstant.BITS"]/h4' \ -// 'pub const BITS: u32 = 32u32' +// 'pub const BITS: u32 = u32::BITS' pub struct Foo(i32); impl std::ops::Deref for Foo { diff --git a/tests/rustdoc-html/display-hidden-items.rs b/tests/rustdoc-html/display-hidden-items.rs index 40cd636e2fe2..8b0854d1ade8 100644 --- a/tests/rustdoc-html/display-hidden-items.rs +++ b/tests/rustdoc-html/display-hidden-items.rs @@ -20,7 +20,7 @@ pub trait TraitHidden {} //@ has 'foo/index.html' '//dt/a[@class="trait"]' 'Trait' pub trait Trait { //@ has 'foo/trait.Trait.html' - //@ has - '//*[@id="associatedconstant.BAR"]/*[@class="code-header"]' '#[doc(hidden)] const BAR: u32 = 0u32' + //@ has - '//*[@id="associatedconstant.BAR"]/*[@class="code-header"]' '#[doc(hidden)] const BAR: u32 = 0' #[doc(hidden)] const BAR: u32 = 0; @@ -44,7 +44,7 @@ impl Struct { } impl Trait for Struct { - //@ has - '//*[@id="associatedconstant.BAR"]/*[@class="code-header"]' '#[doc(hidden)] const BAR: u32 = 0u32' + //@ has - '//*[@id="associatedconstant.BAR"]/*[@class="code-header"]' '#[doc(hidden)] const BAR: u32 = 0' //@ has - '//*[@id="method.foo"]/*[@class="code-header"]' '#[doc(hidden)] fn foo()' } //@ has - '//*[@id="impl-TraitHidden-for-Struct"]/*[@class="code-header"]' 'impl TraitHidden for Struct' diff --git a/tests/rustdoc-html/impl/impl-associated-items-order.rs b/tests/rustdoc-html/impl/impl-associated-items-order.rs index 759e0f0b4009..3f1d04720163 100644 --- a/tests/rustdoc-html/impl/impl-associated-items-order.rs +++ b/tests/rustdoc-html/impl/impl-associated-items-order.rs @@ -16,7 +16,7 @@ impl Bar { // 'pub fn foo()' pub fn foo() {} //@ has - '//*[@id="implementations-list"]//*[@class="impl-items"]/section[1]/h4' \ - // 'pub const X: u8 = 12u8' + // 'pub const X: u8 = 12' pub const X: u8 = 12; //@ has - '//*[@id="implementations-list"]//*[@class="impl-items"]/section[2]/h4' \ // 'pub type Y = u8' @@ -34,7 +34,7 @@ impl Foo for Bar { // 'type Z = u8' type Z = u8; //@ has - '//*[@id="trait-implementations-list"]//*[@class="impl-items"]/section[1]/h4' \ - // 'const W: u32 = 12u32' + // 'const W: u32 = 12' const W: u32 = 12; //@ has - '//*[@id="trait-implementations-list"]//*[@class="impl-items"]/section[3]/h4' \ // 'fn yeay()' diff --git a/tests/rustdoc-ui/diverging-assoc-consts.rs b/tests/rustdoc-ui/diverging-assoc-consts.rs new file mode 100644 index 000000000000..fd0a177e7c4b --- /dev/null +++ b/tests/rustdoc-ui/diverging-assoc-consts.rs @@ -0,0 +1,33 @@ +// Ensure that we don't unconditionally evaluate the initializer of associated constants. +// +// We once used to evaluate them so we could display more kinds of expressions +// (like `1 + 1` as `2`) given the fact that we generally only want to render +// literals (otherwise we would risk dumping extremely large exprs or leaking +// private struct fields). +// +// However, that deviated from rustc's behavior, made rustdoc accept less code +// and was understandably surprising to users. So let's not. +// +// In the future we *might* provide users a mechanism to control this behavior. +// E.g., via a new `#[doc(...)]` attribute. +// +// See also: +// issue: +// issue: + +//@ check-pass + +pub struct Type; + +impl Type { + pub const K0: () = panic!(); + pub const K1: std::convert::Infallible = loop {}; +} + +pub trait Trait { + const K2: i32 = panic!(); +} + +impl Trait for Type { + const K2: i32 = loop {}; +} From ebfd22796fa3eb0bc52612ce7b45cd789f8cb089 Mon Sep 17 00:00:00 2001 From: Oscar Bray Date: Sat, 17 Jan 2026 12:02:37 +0000 Subject: [PATCH 096/146] Port #[needs_allocator] to attribute parser --- compiler/rustc_attr_parsing/src/attributes/link_attrs.rs | 9 +++++++++ compiler/rustc_attr_parsing/src/context.rs | 3 ++- compiler/rustc_hir/src/attrs/data_structures.rs | 3 +++ compiler/rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_metadata/src/rmeta/encoder.rs | 2 +- compiler/rustc_passes/src/check_attr.rs | 2 +- 6 files changed, 17 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs index 61f975555884..2a04b55f469e 100644 --- a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs @@ -658,3 +658,12 @@ impl SingleAttributeParser for LinkageParser { Some(AttributeKind::Linkage(linkage, cx.attr_span)) } } + +pub(crate) struct NeedsAllocatorParser; + +impl NoArgsAttributeParser for NeedsAllocatorParser { + const PATH: &[Symbol] = &[sym::needs_allocator]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::NeedsAllocator; +} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 2a2fccd32202..449894f7834b 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -41,7 +41,7 @@ use crate::attributes::inline::{InlineParser, RustcForceInlineParser}; use crate::attributes::instruction_set::InstructionSetParser; use crate::attributes::link_attrs::{ ExportStableParser, FfiConstParser, FfiPureParser, LinkNameParser, LinkOrdinalParser, - LinkParser, LinkSectionParser, LinkageParser, StdInternalSymbolParser, + LinkParser, LinkSectionParser, LinkageParser, NeedsAllocatorParser, StdInternalSymbolParser, }; use crate::attributes::lint_helpers::{ AsPtrParser, AutomaticallyDerivedParser, PassByValueParser, PubTransparentParser, @@ -259,6 +259,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 126fb8eac11b..7b7fae9fdcca 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -840,6 +840,9 @@ pub enum AttributeKind { /// Represents `#[naked]` Naked(Span), + /// Represents `#[needs_allocator]` + NeedsAllocator, + /// Represents `#[no_core]` NoCore(Span), diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 760e7c76df35..dff8a5727771 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -75,6 +75,7 @@ impl AttributeKind { MustNotSupend { .. } => Yes, MustUse { .. } => Yes, Naked(..) => No, + NeedsAllocator => No, NoCore(..) => No, NoImplicitPrelude(..) => No, NoLink => No, diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index a62826cd7cec..dbcb44e3220e 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -742,7 +742,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { proc_macro_data, debugger_visualizers, compiler_builtins: ast::attr::contains_name(attrs, sym::compiler_builtins), - needs_allocator: ast::attr::contains_name(attrs, sym::needs_allocator), + needs_allocator: find_attr!(attrs, AttributeKind::NeedsAllocator), needs_panic_runtime: ast::attr::contains_name(attrs, sym::needs_panic_runtime), no_builtins: ast::attr::contains_name(attrs, sym::no_builtins), panic_runtime: ast::attr::contains_name(attrs, sym::panic_runtime), diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index f57bd62d3e99..4b71d4755cb6 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -315,6 +315,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcDumpPredicates | AttributeKind::RustcDumpDefParents | AttributeKind::RustcDumpVtable(..) + | AttributeKind::NeedsAllocator ) => { /* do nothing */ } Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); @@ -346,7 +347,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::prelude_import | sym::panic_handler | sym::lang - | sym::needs_allocator | sym::default_lib_allocator | sym::rustc_diagnostic_item | sym::rustc_no_mir_inline From fe63539778fd3ae3b7aae1e03b96f10991f41d16 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sat, 17 Jan 2026 14:18:11 +0100 Subject: [PATCH 097/146] Explicitly list crate level attrs --- compiler/rustc_passes/src/check_attr.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index f57bd62d3e99..a4aed2b92804 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -389,13 +389,25 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::rustc_partition_reused | sym::rustc_partition_codegened | sym::rustc_expected_cgu_reuse - | sym::rustc_nounwind, + | sym::rustc_nounwind + // crate-level attrs, are checked below + | sym::feature + | sym::register_tool + | sym::rustc_no_implicit_bounds + | sym::test_runner + | sym::reexport_test_harness_main + | sym::no_main + | sym::no_builtins + | sym::crate_type + | sym::compiler_builtins + | sym::profiler_runtime + | sym::needs_panic_runtime + | sym::panic_runtime + | sym::rustc_preserve_ub_checks, .. ] => {} [name, rest@..] => { match BUILTIN_ATTRIBUTE_MAP.get(name) { - // checked below - Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) => {} Some(_) => { if rest.len() > 0 && AttributeParser::::is_parsed_attribute(slice::from_ref(name)) { // Check if we tried to use a builtin attribute as an attribute namespace, like `#[must_use::skip]`. From ad3e082afe997060dc1be247dc227db3e8d250d6 Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Sat, 17 Jan 2026 10:19:26 -0500 Subject: [PATCH 098/146] Bump version to 1.95.0 --- src/version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/version b/src/version index 8db4a57b3d02..55f6ae93382d 100644 --- a/src/version +++ b/src/version @@ -1 +1 @@ -1.94.0 +1.95.0 From 4d2f6a0843b161df938c341ecf142e636cd54b5b Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Sun, 18 Jan 2026 04:34:46 +0900 Subject: [PATCH 099/146] fix ICE on inconsistent import resolution with macro-attributed extern crate --- compiler/rustc_resolve/src/imports.rs | 2 +- .../resolve/ice-inconsistent-resolution-151213.rs | 14 ++++++++++++++ .../ice-inconsistent-resolution-151213.stderr | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 tests/ui/resolve/ice-inconsistent-resolution-151213.rs create mode 100644 tests/ui/resolve/ice-inconsistent-resolution-151213.stderr diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 451779ae32c6..016fc407daab 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -989,7 +989,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { PathResult::Module(module) => { // Consistency checks, analogous to `finalize_macro_resolutions`. if let Some(initial_module) = import.imported_module.get() { - if module != initial_module && no_ambiguity { + if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied { span_bug!(import.span, "inconsistent resolution for an import"); } } else if self.privacy_errors.is_empty() { diff --git a/tests/ui/resolve/ice-inconsistent-resolution-151213.rs b/tests/ui/resolve/ice-inconsistent-resolution-151213.rs new file mode 100644 index 000000000000..ea0f1c2858ef --- /dev/null +++ b/tests/ui/resolve/ice-inconsistent-resolution-151213.rs @@ -0,0 +1,14 @@ +//@ edition: 2024 + +#[attr] +//~^ ERROR cannot find attribute `attr` in this scope +extern crate core as std; +//~^ ERROR macro-expanded `extern crate` items cannot shadow names passed with `--extern` + +mod inner { + use std::str; + + use crate::*; +} + +fn main() {} diff --git a/tests/ui/resolve/ice-inconsistent-resolution-151213.stderr b/tests/ui/resolve/ice-inconsistent-resolution-151213.stderr new file mode 100644 index 000000000000..deb1e6c3e1cf --- /dev/null +++ b/tests/ui/resolve/ice-inconsistent-resolution-151213.stderr @@ -0,0 +1,14 @@ +error: macro-expanded `extern crate` items cannot shadow names passed with `--extern` + --> $DIR/ice-inconsistent-resolution-151213.rs:5:1 + | +LL | extern crate core as std; + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: cannot find attribute `attr` in this scope + --> $DIR/ice-inconsistent-resolution-151213.rs:3:3 + | +LL | #[attr] + | ^^^^ + +error: aborting due to 2 previous errors + From b49539e0490188136ae5805e144967ad6d510a2b Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sat, 17 Jan 2026 15:08:53 -0800 Subject: [PATCH 100/146] Include a link to `count_ones` in the docs for `uN::count_zeros` --- library/core/src/num/uint_macros.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index eea5ce348355..57f0cd48fbe8 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -93,6 +93,28 @@ macro_rules! uint_impl { #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] /// assert_eq!(max.count_zeros(), 0); /// ``` + /// + /// This is heavily dependent on the width of the type, and thus + /// might give surprising results depending on type inference: + /// ``` + /// # fn foo(_: u8) {} + /// # fn bar(_: u16) {} + /// let lucky = 7; + /// foo(lucky); + /// assert_eq!(lucky.count_zeros(), 5); + /// assert_eq!(lucky.count_ones(), 3); + /// + /// let lucky = 7; + /// bar(lucky); + /// assert_eq!(lucky.count_zeros(), 13); + /// assert_eq!(lucky.count_ones(), 3); + /// ``` + /// You might want to use [`Self::count_ones`] instead, or emphasize + /// the type you're using in the call rather than method syntax: + /// ``` + /// let small = 1; + #[doc = concat!("assert_eq!(", stringify!($SelfT), "::count_zeros(small), ", stringify!($BITS_MINUS_ONE) ,");")] + /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_math", since = "1.32.0")] #[must_use = "this returns the result of the operation, \ From 216ca145fd5967d1ff8731b8cc76eca7b53cff03 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 17 Jan 2026 21:43:50 -0500 Subject: [PATCH 101/146] remove trailing periods in built-in attribute gate messages --- compiler/rustc_feature/src/builtin_attrs.rs | 22 ++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 22753adb4c99..1fd6c3c10fab 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -678,7 +678,7 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ rustc_attr!( rustc_pass_indirectly_in_non_rustic_abis, Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::No, - "types marked with `#[rustc_pass_indirectly_in_non_rustic_abis]` are always passed indirectly by non-Rustic abis." + "types marked with `#[rustc_pass_indirectly_in_non_rustic_abis]` are always passed indirectly by non-Rustic ABIs" ), // Limits: @@ -1275,38 +1275,38 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ rustc_attr!( rustc_as_ptr, Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, - "`#[rustc_as_ptr]` is used to mark functions returning pointers to their inner allocations." + "`#[rustc_as_ptr]` is used to mark functions returning pointers to their inner allocations" ), rustc_attr!( rustc_should_not_be_called_on_const_items, Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, - "`#[rustc_should_not_be_called_on_const_items]` is used to mark methods that don't make sense to be called on interior mutable consts." + "`#[rustc_should_not_be_called_on_const_items]` is used to mark methods that don't make sense to be called on interior mutable consts" ), rustc_attr!( rustc_pass_by_value, Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, - "`#[rustc_pass_by_value]` is used to mark types that must be passed by value instead of reference." + "`#[rustc_pass_by_value]` is used to mark types that must be passed by value instead of reference" ), rustc_attr!( rustc_never_returns_null_ptr, Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, - "`#[rustc_never_returns_null_ptr]` is used to mark functions returning non-null pointers." + "`#[rustc_never_returns_null_ptr]` is used to mark functions returning non-null pointers" ), rustc_attr!( rustc_no_implicit_autorefs, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, - "`#[rustc_no_implicit_autorefs]` is used to mark functions for which an autoref to the dereference of a raw pointer should not be used as an argument." + "`#[rustc_no_implicit_autorefs]` is used to mark functions for which an autoref to the dereference of a raw pointer should not be used as an argument" ), rustc_attr!( rustc_coherence_is_core, AttributeType::CrateLevel, template!(Word), ErrorFollowing, EncodeCrossCrate::No, - "`#![rustc_coherence_is_core]` allows inherent methods on builtin types, only intended to be used in `core`." + "`#![rustc_coherence_is_core]` allows inherent methods on builtin types, only intended to be used in `core`" ), rustc_attr!( rustc_coinductive, AttributeType::Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, - "`#[rustc_coinductive]` changes a trait to be coinductive, allowing cycles in the trait solver." + "`#[rustc_coinductive]` changes a trait to be coinductive, allowing cycles in the trait solver" ), rustc_attr!( rustc_allow_incoherent_impl, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::No, - "`#[rustc_allow_incoherent_impl]` has to be added to all impl items of an incoherent inherent impl." + "`#[rustc_allow_incoherent_impl]` has to be added to all impl items of an incoherent inherent impl" ), rustc_attr!( rustc_preserve_ub_checks, AttributeType::CrateLevel, template!(Word), ErrorFollowing, EncodeCrossCrate::No, @@ -1333,7 +1333,7 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ rustc_has_incoherent_inherent_impls, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, "`#[rustc_has_incoherent_inherent_impls]` allows the addition of incoherent inherent impls for \ - the given type by annotating all impl items with `#[rustc_allow_incoherent_impl]`." + the given type by annotating all impl items with `#[rustc_allow_incoherent_impl]`" ), BuiltinAttribute { @@ -1396,7 +1396,7 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ EncodeCrossCrate::No, "the `#[rustc_skip_during_method_dispatch]` attribute is used to exclude a trait \ from method dispatch when the receiver is of the following type, for compatibility in \ - editions < 2021 (array) or editions < 2024 (boxed_slice)." + editions < 2021 (array) or editions < 2024 (boxed_slice)" ), rustc_attr!( rustc_must_implement_one_of, Normal, template!(List: &["function1, function2, ..."]), From 7510f747a8599c430a054ba58d53dc8dae1465ee Mon Sep 17 00:00:00 2001 From: mu001999 Date: Sun, 18 Jan 2026 11:40:42 +0800 Subject: [PATCH 102/146] Normalize type_const items even with feature `generic_const_exprs` --- .../rustc_trait_selection/src/traits/normalize.rs | 7 ++++++- tests/crashes/138089.rs | 2 ++ .../const-generics/mgca/cyclic-type-const-151251.rs | 11 +++++++++++ .../mgca/cyclic-type-const-151251.stderr | 11 +++++++++++ 4 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 tests/ui/const-generics/mgca/cyclic-type-const-151251.rs create mode 100644 tests/ui/const-generics/mgca/cyclic-type-const-151251.stderr diff --git a/compiler/rustc_trait_selection/src/traits/normalize.rs b/compiler/rustc_trait_selection/src/traits/normalize.rs index 71e9914f93fa..24854990fe71 100644 --- a/compiler/rustc_trait_selection/src/traits/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/normalize.rs @@ -433,7 +433,12 @@ impl<'a, 'b, 'tcx> TypeFolder> for AssocTypeNormalizer<'a, 'b, 'tcx #[instrument(skip(self), level = "debug")] fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { let tcx = self.selcx.tcx(); - if tcx.features().generic_const_exprs() || !needs_normalization(self.selcx.infcx, &ct) { + + if tcx.features().generic_const_exprs() + // Normalize type_const items even with feature `generic_const_exprs`. + && !matches!(ct.kind(), ty::ConstKind::Unevaluated(uv) if tcx.is_type_const(uv.def)) + || !needs_normalization(self.selcx.infcx, &ct) + { return ct; } diff --git a/tests/crashes/138089.rs b/tests/crashes/138089.rs index 054d1b216959..f4864971ae5d 100644 --- a/tests/crashes/138089.rs +++ b/tests/crashes/138089.rs @@ -1,4 +1,6 @@ //@ known-bug: #138089 +//@ needs-rustc-debug-assertions + #![feature(generic_const_exprs)] #![feature(min_generic_const_args)] #![feature(inherent_associated_types)] diff --git a/tests/ui/const-generics/mgca/cyclic-type-const-151251.rs b/tests/ui/const-generics/mgca/cyclic-type-const-151251.rs new file mode 100644 index 000000000000..823a6d58bf47 --- /dev/null +++ b/tests/ui/const-generics/mgca/cyclic-type-const-151251.rs @@ -0,0 +1,11 @@ +//@ needs-rustc-debug-assertions + +#![feature(min_generic_const_args)] +#![feature(generic_const_exprs)] +#![expect(incomplete_features)] + +#[type_const] +const A: u8 = A; +//~^ ERROR overflow normalizing the unevaluated constant `A` + +fn main() {} diff --git a/tests/ui/const-generics/mgca/cyclic-type-const-151251.stderr b/tests/ui/const-generics/mgca/cyclic-type-const-151251.stderr new file mode 100644 index 000000000000..1ce2af817277 --- /dev/null +++ b/tests/ui/const-generics/mgca/cyclic-type-const-151251.stderr @@ -0,0 +1,11 @@ +error[E0275]: overflow normalizing the unevaluated constant `A` + --> $DIR/cyclic-type-const-151251.rs:8:1 + | +LL | const A: u8 = A; + | ^^^^^^^^^^^ + | + = note: in case this is a recursive type alias, consider using a struct, enum, or union instead + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0275`. From cf5a7da23f59af669aab128d919d04b96d9ec08b Mon Sep 17 00:00:00 2001 From: tuturuu Date: Sun, 18 Jan 2026 05:16:29 +0100 Subject: [PATCH 103/146] move some tests --- .../associated-type-as-value.rs} | 0 .../associated-type-as-value.stderr} | 0 tests/ui/{issues/issue-17441.rs => cast/cast-to-unsized-type.rs} | 0 .../issue-17441.stderr => cast/cast-to-unsized-type.stderr} | 0 .../issue-2995.rs => cast/non-primitive-isize-ref-cast.rs} | 0 .../non-primitive-isize-ref-cast.stderr} | 0 .../ui/{issues/issue-19922.rs => enum/enum-nonexisting-field.rs} | 0 .../issue-19922.stderr => enum/enum-nonexisting-field.stderr} | 0 .../ui/{issues/issue-17351.rs => lint/unused/unused-trait-fn.rs} | 0 .../issue-17351.stderr => lint/unused/unused-trait-fn.stderr} | 0 .../issue-22599.rs => lint/unused/unused-var-in-match-arm.rs} | 0 .../unused/unused-var-in-match-arm.stderr} | 0 .../issue-19692.rs => methods/method-not-found-on-struct.rs} | 0 .../method-not-found-on-struct.stderr} | 0 .../{issues/issue-34209.rs => pattern/enum-variant-not-found.rs} | 0 .../issue-34209.stderr => pattern/enum-variant-not-found.stderr} | 0 .../issue-16745.rs => pattern/match-constant-and-byte-literal.rs} | 0 .../auxiliary/imported-enum-is-private.rs} | 0 .../issue-11680.rs => privacy/imported-enum-is-private.rs} | 0 .../imported-enum-is-private.stderr} | 0 .../issue-26472.rs => privacy/private-struct-field-in-module.rs} | 0 .../private-struct-field-in-module.stderr} | 0 .../panic-with-unspecified-type.rs} | 0 .../panic-with-unspecified-type.stderr} | 0 .../send-with-unspecified-type.rs} | 0 .../send-with-unspecified-type.stderr} | 0 .../swap-with-unspecified-type.rs} | 0 .../swap-with-unspecified-type.stderr} | 0 .../issue-35241.rs => type/struct-constructor-as-value.rs} | 0 .../struct-constructor-as-value.stderr} | 0 30 files changed, 0 insertions(+), 0 deletions(-) rename tests/ui/{issues/issue-38919.rs => associated-types/associated-type-as-value.rs} (100%) rename tests/ui/{issues/issue-38919.stderr => associated-types/associated-type-as-value.stderr} (100%) rename tests/ui/{issues/issue-17441.rs => cast/cast-to-unsized-type.rs} (100%) rename tests/ui/{issues/issue-17441.stderr => cast/cast-to-unsized-type.stderr} (100%) rename tests/ui/{issues/issue-2995.rs => cast/non-primitive-isize-ref-cast.rs} (100%) rename tests/ui/{issues/issue-2995.stderr => cast/non-primitive-isize-ref-cast.stderr} (100%) rename tests/ui/{issues/issue-19922.rs => enum/enum-nonexisting-field.rs} (100%) rename tests/ui/{issues/issue-19922.stderr => enum/enum-nonexisting-field.stderr} (100%) rename tests/ui/{issues/issue-17351.rs => lint/unused/unused-trait-fn.rs} (100%) rename tests/ui/{issues/issue-17351.stderr => lint/unused/unused-trait-fn.stderr} (100%) rename tests/ui/{issues/issue-22599.rs => lint/unused/unused-var-in-match-arm.rs} (100%) rename tests/ui/{issues/issue-22599.stderr => lint/unused/unused-var-in-match-arm.stderr} (100%) rename tests/ui/{issues/issue-19692.rs => methods/method-not-found-on-struct.rs} (100%) rename tests/ui/{issues/issue-19692.stderr => methods/method-not-found-on-struct.stderr} (100%) rename tests/ui/{issues/issue-34209.rs => pattern/enum-variant-not-found.rs} (100%) rename tests/ui/{issues/issue-34209.stderr => pattern/enum-variant-not-found.stderr} (100%) rename tests/ui/{issues/issue-16745.rs => pattern/match-constant-and-byte-literal.rs} (100%) rename tests/ui/{issues/auxiliary/issue-11680.rs => privacy/auxiliary/imported-enum-is-private.rs} (100%) rename tests/ui/{issues/issue-11680.rs => privacy/imported-enum-is-private.rs} (100%) rename tests/ui/{issues/issue-11680.stderr => privacy/imported-enum-is-private.stderr} (100%) rename tests/ui/{issues/issue-26472.rs => privacy/private-struct-field-in-module.rs} (100%) rename tests/ui/{issues/issue-26472.stderr => privacy/private-struct-field-in-module.stderr} (100%) rename tests/ui/{issues/issue-16966.rs => type-inference/panic-with-unspecified-type.rs} (100%) rename tests/ui/{issues/issue-16966.stderr => type-inference/panic-with-unspecified-type.stderr} (100%) rename tests/ui/{issues/issue-25368.rs => type-inference/send-with-unspecified-type.rs} (100%) rename tests/ui/{issues/issue-25368.stderr => type-inference/send-with-unspecified-type.stderr} (100%) rename tests/ui/{issues/issue-24013.rs => type-inference/swap-with-unspecified-type.rs} (100%) rename tests/ui/{issues/issue-24013.stderr => type-inference/swap-with-unspecified-type.stderr} (100%) rename tests/ui/{issues/issue-35241.rs => type/struct-constructor-as-value.rs} (100%) rename tests/ui/{issues/issue-35241.stderr => type/struct-constructor-as-value.stderr} (100%) diff --git a/tests/ui/issues/issue-38919.rs b/tests/ui/associated-types/associated-type-as-value.rs similarity index 100% rename from tests/ui/issues/issue-38919.rs rename to tests/ui/associated-types/associated-type-as-value.rs diff --git a/tests/ui/issues/issue-38919.stderr b/tests/ui/associated-types/associated-type-as-value.stderr similarity index 100% rename from tests/ui/issues/issue-38919.stderr rename to tests/ui/associated-types/associated-type-as-value.stderr diff --git a/tests/ui/issues/issue-17441.rs b/tests/ui/cast/cast-to-unsized-type.rs similarity index 100% rename from tests/ui/issues/issue-17441.rs rename to tests/ui/cast/cast-to-unsized-type.rs diff --git a/tests/ui/issues/issue-17441.stderr b/tests/ui/cast/cast-to-unsized-type.stderr similarity index 100% rename from tests/ui/issues/issue-17441.stderr rename to tests/ui/cast/cast-to-unsized-type.stderr diff --git a/tests/ui/issues/issue-2995.rs b/tests/ui/cast/non-primitive-isize-ref-cast.rs similarity index 100% rename from tests/ui/issues/issue-2995.rs rename to tests/ui/cast/non-primitive-isize-ref-cast.rs diff --git a/tests/ui/issues/issue-2995.stderr b/tests/ui/cast/non-primitive-isize-ref-cast.stderr similarity index 100% rename from tests/ui/issues/issue-2995.stderr rename to tests/ui/cast/non-primitive-isize-ref-cast.stderr diff --git a/tests/ui/issues/issue-19922.rs b/tests/ui/enum/enum-nonexisting-field.rs similarity index 100% rename from tests/ui/issues/issue-19922.rs rename to tests/ui/enum/enum-nonexisting-field.rs diff --git a/tests/ui/issues/issue-19922.stderr b/tests/ui/enum/enum-nonexisting-field.stderr similarity index 100% rename from tests/ui/issues/issue-19922.stderr rename to tests/ui/enum/enum-nonexisting-field.stderr diff --git a/tests/ui/issues/issue-17351.rs b/tests/ui/lint/unused/unused-trait-fn.rs similarity index 100% rename from tests/ui/issues/issue-17351.rs rename to tests/ui/lint/unused/unused-trait-fn.rs diff --git a/tests/ui/issues/issue-17351.stderr b/tests/ui/lint/unused/unused-trait-fn.stderr similarity index 100% rename from tests/ui/issues/issue-17351.stderr rename to tests/ui/lint/unused/unused-trait-fn.stderr diff --git a/tests/ui/issues/issue-22599.rs b/tests/ui/lint/unused/unused-var-in-match-arm.rs similarity index 100% rename from tests/ui/issues/issue-22599.rs rename to tests/ui/lint/unused/unused-var-in-match-arm.rs diff --git a/tests/ui/issues/issue-22599.stderr b/tests/ui/lint/unused/unused-var-in-match-arm.stderr similarity index 100% rename from tests/ui/issues/issue-22599.stderr rename to tests/ui/lint/unused/unused-var-in-match-arm.stderr diff --git a/tests/ui/issues/issue-19692.rs b/tests/ui/methods/method-not-found-on-struct.rs similarity index 100% rename from tests/ui/issues/issue-19692.rs rename to tests/ui/methods/method-not-found-on-struct.rs diff --git a/tests/ui/issues/issue-19692.stderr b/tests/ui/methods/method-not-found-on-struct.stderr similarity index 100% rename from tests/ui/issues/issue-19692.stderr rename to tests/ui/methods/method-not-found-on-struct.stderr diff --git a/tests/ui/issues/issue-34209.rs b/tests/ui/pattern/enum-variant-not-found.rs similarity index 100% rename from tests/ui/issues/issue-34209.rs rename to tests/ui/pattern/enum-variant-not-found.rs diff --git a/tests/ui/issues/issue-34209.stderr b/tests/ui/pattern/enum-variant-not-found.stderr similarity index 100% rename from tests/ui/issues/issue-34209.stderr rename to tests/ui/pattern/enum-variant-not-found.stderr diff --git a/tests/ui/issues/issue-16745.rs b/tests/ui/pattern/match-constant-and-byte-literal.rs similarity index 100% rename from tests/ui/issues/issue-16745.rs rename to tests/ui/pattern/match-constant-and-byte-literal.rs diff --git a/tests/ui/issues/auxiliary/issue-11680.rs b/tests/ui/privacy/auxiliary/imported-enum-is-private.rs similarity index 100% rename from tests/ui/issues/auxiliary/issue-11680.rs rename to tests/ui/privacy/auxiliary/imported-enum-is-private.rs diff --git a/tests/ui/issues/issue-11680.rs b/tests/ui/privacy/imported-enum-is-private.rs similarity index 100% rename from tests/ui/issues/issue-11680.rs rename to tests/ui/privacy/imported-enum-is-private.rs diff --git a/tests/ui/issues/issue-11680.stderr b/tests/ui/privacy/imported-enum-is-private.stderr similarity index 100% rename from tests/ui/issues/issue-11680.stderr rename to tests/ui/privacy/imported-enum-is-private.stderr diff --git a/tests/ui/issues/issue-26472.rs b/tests/ui/privacy/private-struct-field-in-module.rs similarity index 100% rename from tests/ui/issues/issue-26472.rs rename to tests/ui/privacy/private-struct-field-in-module.rs diff --git a/tests/ui/issues/issue-26472.stderr b/tests/ui/privacy/private-struct-field-in-module.stderr similarity index 100% rename from tests/ui/issues/issue-26472.stderr rename to tests/ui/privacy/private-struct-field-in-module.stderr diff --git a/tests/ui/issues/issue-16966.rs b/tests/ui/type-inference/panic-with-unspecified-type.rs similarity index 100% rename from tests/ui/issues/issue-16966.rs rename to tests/ui/type-inference/panic-with-unspecified-type.rs diff --git a/tests/ui/issues/issue-16966.stderr b/tests/ui/type-inference/panic-with-unspecified-type.stderr similarity index 100% rename from tests/ui/issues/issue-16966.stderr rename to tests/ui/type-inference/panic-with-unspecified-type.stderr diff --git a/tests/ui/issues/issue-25368.rs b/tests/ui/type-inference/send-with-unspecified-type.rs similarity index 100% rename from tests/ui/issues/issue-25368.rs rename to tests/ui/type-inference/send-with-unspecified-type.rs diff --git a/tests/ui/issues/issue-25368.stderr b/tests/ui/type-inference/send-with-unspecified-type.stderr similarity index 100% rename from tests/ui/issues/issue-25368.stderr rename to tests/ui/type-inference/send-with-unspecified-type.stderr diff --git a/tests/ui/issues/issue-24013.rs b/tests/ui/type-inference/swap-with-unspecified-type.rs similarity index 100% rename from tests/ui/issues/issue-24013.rs rename to tests/ui/type-inference/swap-with-unspecified-type.rs diff --git a/tests/ui/issues/issue-24013.stderr b/tests/ui/type-inference/swap-with-unspecified-type.stderr similarity index 100% rename from tests/ui/issues/issue-24013.stderr rename to tests/ui/type-inference/swap-with-unspecified-type.stderr diff --git a/tests/ui/issues/issue-35241.rs b/tests/ui/type/struct-constructor-as-value.rs similarity index 100% rename from tests/ui/issues/issue-35241.rs rename to tests/ui/type/struct-constructor-as-value.rs diff --git a/tests/ui/issues/issue-35241.stderr b/tests/ui/type/struct-constructor-as-value.stderr similarity index 100% rename from tests/ui/issues/issue-35241.stderr rename to tests/ui/type/struct-constructor-as-value.stderr From 2c7969a0cd4217900f96511b16117a0ef31836c4 Mon Sep 17 00:00:00 2001 From: tuturuu Date: Sun, 18 Jan 2026 06:10:16 +0100 Subject: [PATCH 104/146] add metadata and bless moved tests --- .../ui/associated-types/associated-type-as-value.rs | 2 ++ .../associated-types/associated-type-as-value.stderr | 2 +- tests/ui/cast/cast-to-unsized-type.rs | 2 ++ tests/ui/cast/cast-to-unsized-type.stderr | 12 ++++++------ tests/ui/cast/non-primitive-isize-ref-cast.rs | 2 ++ tests/ui/cast/non-primitive-isize-ref-cast.stderr | 2 +- tests/ui/enum/enum-nonexisting-field.rs | 2 ++ tests/ui/enum/enum-nonexisting-field.stderr | 2 +- tests/ui/lint/unused/unused-trait-fn.rs | 1 + tests/ui/lint/unused/unused-trait-fn.stderr | 2 +- tests/ui/lint/unused/unused-var-in-match-arm.rs | 1 + tests/ui/lint/unused/unused-var-in-match-arm.stderr | 4 ++-- tests/ui/methods/method-not-found-on-struct.rs | 2 ++ tests/ui/methods/method-not-found-on-struct.stderr | 2 +- tests/ui/pattern/enum-variant-not-found.rs | 2 ++ tests/ui/pattern/enum-variant-not-found.stderr | 2 +- tests/ui/pattern/match-constant-and-byte-literal.rs | 1 + .../ui/privacy/auxiliary/imported-enum-is-private.rs | 2 ++ tests/ui/privacy/imported-enum-is-private.rs | 5 +++-- tests/ui/privacy/imported-enum-is-private.stderr | 8 ++++---- tests/ui/privacy/private-struct-field-in-module.rs | 2 ++ .../ui/privacy/private-struct-field-in-module.stderr | 4 ++-- .../ui/type-inference/panic-with-unspecified-type.rs | 1 + .../panic-with-unspecified-type.stderr | 2 +- .../ui/type-inference/send-with-unspecified-type.rs | 2 ++ .../type-inference/send-with-unspecified-type.stderr | 2 +- .../ui/type-inference/swap-with-unspecified-type.rs | 2 ++ .../type-inference/swap-with-unspecified-type.stderr | 2 +- tests/ui/type/struct-constructor-as-value.rs | 2 ++ tests/ui/type/struct-constructor-as-value.stderr | 2 +- 30 files changed, 53 insertions(+), 26 deletions(-) diff --git a/tests/ui/associated-types/associated-type-as-value.rs b/tests/ui/associated-types/associated-type-as-value.rs index 3d28f1936b47..ddc808236658 100644 --- a/tests/ui/associated-types/associated-type-as-value.rs +++ b/tests/ui/associated-types/associated-type-as-value.rs @@ -1,3 +1,5 @@ +//! regression test for + fn foo() { T::Item; //~ ERROR no associated item named `Item` found } diff --git a/tests/ui/associated-types/associated-type-as-value.stderr b/tests/ui/associated-types/associated-type-as-value.stderr index 4a4bd2ee43d8..c553582b3907 100644 --- a/tests/ui/associated-types/associated-type-as-value.stderr +++ b/tests/ui/associated-types/associated-type-as-value.stderr @@ -1,5 +1,5 @@ error[E0599]: no associated item named `Item` found for type parameter `T` in the current scope - --> $DIR/issue-38919.rs:2:8 + --> $DIR/associated-type-as-value.rs:4:8 | LL | fn foo() { | - associated item `Item` not found for this type parameter diff --git a/tests/ui/cast/cast-to-unsized-type.rs b/tests/ui/cast/cast-to-unsized-type.rs index e5f83c4ebadd..4c7ca49fd98d 100644 --- a/tests/ui/cast/cast-to-unsized-type.rs +++ b/tests/ui/cast/cast-to-unsized-type.rs @@ -1,3 +1,5 @@ +//! regression test for + fn main() { let _foo = &[1_usize, 2] as [usize]; //~^ ERROR cast to unsized type: `&[usize; 2]` as `[usize]` diff --git a/tests/ui/cast/cast-to-unsized-type.stderr b/tests/ui/cast/cast-to-unsized-type.stderr index 96aad879e24d..087cfac77484 100644 --- a/tests/ui/cast/cast-to-unsized-type.stderr +++ b/tests/ui/cast/cast-to-unsized-type.stderr @@ -1,5 +1,5 @@ error[E0620]: cast to unsized type: `&[usize; 2]` as `[usize]` - --> $DIR/issue-17441.rs:2:16 + --> $DIR/cast-to-unsized-type.rs:4:16 | LL | let _foo = &[1_usize, 2] as [usize]; | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -10,7 +10,7 @@ LL | let _foo = &[1_usize, 2] as &[usize]; | + error[E0620]: cast to unsized type: `Box` as `dyn Debug` - --> $DIR/issue-17441.rs:5:16 + --> $DIR/cast-to-unsized-type.rs:7:16 | LL | let _bar = Box::new(1_usize) as dyn std::fmt::Debug; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -21,25 +21,25 @@ LL | let _bar = Box::new(1_usize) as Box; | ++++ + error[E0620]: cast to unsized type: `usize` as `dyn Debug` - --> $DIR/issue-17441.rs:8:16 + --> $DIR/cast-to-unsized-type.rs:10:16 | LL | let _baz = 1_usize as dyn std::fmt::Debug; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: consider using a box or reference as appropriate - --> $DIR/issue-17441.rs:8:16 + --> $DIR/cast-to-unsized-type.rs:10:16 | LL | let _baz = 1_usize as dyn std::fmt::Debug; | ^^^^^^^ error[E0620]: cast to unsized type: `[usize; 2]` as `[usize]` - --> $DIR/issue-17441.rs:11:17 + --> $DIR/cast-to-unsized-type.rs:13:17 | LL | let _quux = [1_usize, 2] as [usize]; | ^^^^^^^^^^^^^^^^^^^^^^^ | help: consider using a box or reference as appropriate - --> $DIR/issue-17441.rs:11:17 + --> $DIR/cast-to-unsized-type.rs:13:17 | LL | let _quux = [1_usize, 2] as [usize]; | ^^^^^^^^^^^^ diff --git a/tests/ui/cast/non-primitive-isize-ref-cast.rs b/tests/ui/cast/non-primitive-isize-ref-cast.rs index 0da7909480d2..95259456eede 100644 --- a/tests/ui/cast/non-primitive-isize-ref-cast.rs +++ b/tests/ui/cast/non-primitive-isize-ref-cast.rs @@ -1,3 +1,5 @@ +//! regression test for + fn bad (p: *const isize) { let _q: &isize = p as &isize; //~ ERROR non-primitive cast } diff --git a/tests/ui/cast/non-primitive-isize-ref-cast.stderr b/tests/ui/cast/non-primitive-isize-ref-cast.stderr index f4a08e1751fc..3f4c171d3dc7 100644 --- a/tests/ui/cast/non-primitive-isize-ref-cast.stderr +++ b/tests/ui/cast/non-primitive-isize-ref-cast.stderr @@ -1,5 +1,5 @@ error[E0605]: non-primitive cast: `*const isize` as `&isize` - --> $DIR/issue-2995.rs:2:22 + --> $DIR/non-primitive-isize-ref-cast.rs:4:22 | LL | let _q: &isize = p as &isize; | ^^^^^^^^^^^ invalid cast diff --git a/tests/ui/enum/enum-nonexisting-field.rs b/tests/ui/enum/enum-nonexisting-field.rs index fede86f22afd..837430340f33 100644 --- a/tests/ui/enum/enum-nonexisting-field.rs +++ b/tests/ui/enum/enum-nonexisting-field.rs @@ -1,3 +1,5 @@ +//! regression test for + enum Homura { Akemi { madoka: () } } diff --git a/tests/ui/enum/enum-nonexisting-field.stderr b/tests/ui/enum/enum-nonexisting-field.stderr index 0355d3a89710..22bfa08dadb3 100644 --- a/tests/ui/enum/enum-nonexisting-field.stderr +++ b/tests/ui/enum/enum-nonexisting-field.stderr @@ -1,5 +1,5 @@ error[E0559]: variant `Homura::Akemi` has no field named `kaname` - --> $DIR/issue-19922.rs:6:34 + --> $DIR/enum-nonexisting-field.rs:8:34 | LL | let homura = Homura::Akemi { kaname: () }; | ^^^^^^ `Homura::Akemi` does not have this field diff --git a/tests/ui/lint/unused/unused-trait-fn.rs b/tests/ui/lint/unused/unused-trait-fn.rs index 86049377198c..57b39c0de17e 100644 --- a/tests/ui/lint/unused/unused-trait-fn.rs +++ b/tests/ui/lint/unused/unused-trait-fn.rs @@ -1,3 +1,4 @@ +//! regression test for //@ run-pass trait Str { fn foo(&self) {} } //~ WARN method `foo` is never used diff --git a/tests/ui/lint/unused/unused-trait-fn.stderr b/tests/ui/lint/unused/unused-trait-fn.stderr index 043d4ffc7808..f33fed29c94c 100644 --- a/tests/ui/lint/unused/unused-trait-fn.stderr +++ b/tests/ui/lint/unused/unused-trait-fn.stderr @@ -1,5 +1,5 @@ warning: method `foo` is never used - --> $DIR/issue-17351.rs:3:16 + --> $DIR/unused-trait-fn.rs:4:16 | LL | trait Str { fn foo(&self) {} } | --- ^^^ diff --git a/tests/ui/lint/unused/unused-var-in-match-arm.rs b/tests/ui/lint/unused/unused-var-in-match-arm.rs index 05096e5c1853..780225f98dbb 100644 --- a/tests/ui/lint/unused/unused-var-in-match-arm.rs +++ b/tests/ui/lint/unused/unused-var-in-match-arm.rs @@ -1,3 +1,4 @@ +//! regression test for #![deny(unused_variables)] fn f(_: i32) {} diff --git a/tests/ui/lint/unused/unused-var-in-match-arm.stderr b/tests/ui/lint/unused/unused-var-in-match-arm.stderr index b599f6febe31..a1b9849293ef 100644 --- a/tests/ui/lint/unused/unused-var-in-match-arm.stderr +++ b/tests/ui/lint/unused/unused-var-in-match-arm.stderr @@ -1,11 +1,11 @@ error: unused variable: `a` - --> $DIR/issue-22599.rs:8:19 + --> $DIR/unused-var-in-match-arm.rs:9:19 | LL | v = match 0 { a => 0 }; | ^ help: if this is intentional, prefix it with an underscore: `_a` | note: the lint level is defined here - --> $DIR/issue-22599.rs:1:9 + --> $DIR/unused-var-in-match-arm.rs:2:9 | LL | #![deny(unused_variables)] | ^^^^^^^^^^^^^^^^ diff --git a/tests/ui/methods/method-not-found-on-struct.rs b/tests/ui/methods/method-not-found-on-struct.rs index 99eccc8a8175..b2a457ed19e5 100644 --- a/tests/ui/methods/method-not-found-on-struct.rs +++ b/tests/ui/methods/method-not-found-on-struct.rs @@ -1,3 +1,5 @@ +//! regression test for + struct Homura; fn akemi(homura: Homura) { diff --git a/tests/ui/methods/method-not-found-on-struct.stderr b/tests/ui/methods/method-not-found-on-struct.stderr index 1e3d7a2e2f51..3bf775f30a7a 100644 --- a/tests/ui/methods/method-not-found-on-struct.stderr +++ b/tests/ui/methods/method-not-found-on-struct.stderr @@ -1,5 +1,5 @@ error[E0599]: no method named `kaname` found for struct `Homura` in the current scope - --> $DIR/issue-19692.rs:4:40 + --> $DIR/method-not-found-on-struct.rs:6:40 | LL | struct Homura; | ------------- method `kaname` not found for this struct diff --git a/tests/ui/pattern/enum-variant-not-found.rs b/tests/ui/pattern/enum-variant-not-found.rs index 632ddb91b36f..e78e28abeb6e 100644 --- a/tests/ui/pattern/enum-variant-not-found.rs +++ b/tests/ui/pattern/enum-variant-not-found.rs @@ -1,3 +1,5 @@ +//! regression test for + enum S { A, } diff --git a/tests/ui/pattern/enum-variant-not-found.stderr b/tests/ui/pattern/enum-variant-not-found.stderr index 83b40d0c0816..6db4cf79d6b3 100644 --- a/tests/ui/pattern/enum-variant-not-found.stderr +++ b/tests/ui/pattern/enum-variant-not-found.stderr @@ -1,5 +1,5 @@ error[E0599]: no variant named `B` found for enum `S` - --> $DIR/issue-34209.rs:7:12 + --> $DIR/enum-variant-not-found.rs:9:12 | LL | enum S { | ------ variant `B` not found here diff --git a/tests/ui/pattern/match-constant-and-byte-literal.rs b/tests/ui/pattern/match-constant-and-byte-literal.rs index 99c85bcffcf8..7a793478016d 100644 --- a/tests/ui/pattern/match-constant-and-byte-literal.rs +++ b/tests/ui/pattern/match-constant-and-byte-literal.rs @@ -1,3 +1,4 @@ +//! regression test for //@ run-pass fn main() { const X: u8 = 0; diff --git a/tests/ui/privacy/auxiliary/imported-enum-is-private.rs b/tests/ui/privacy/auxiliary/imported-enum-is-private.rs index 74abbf0bf8cd..ea847d9aff13 100644 --- a/tests/ui/privacy/auxiliary/imported-enum-is-private.rs +++ b/tests/ui/privacy/auxiliary/imported-enum-is-private.rs @@ -1,3 +1,5 @@ +//! auxiliary crate for + enum Foo { Bar(isize) } diff --git a/tests/ui/privacy/imported-enum-is-private.rs b/tests/ui/privacy/imported-enum-is-private.rs index 9f3dfebcc812..b628676a25c6 100644 --- a/tests/ui/privacy/imported-enum-is-private.rs +++ b/tests/ui/privacy/imported-enum-is-private.rs @@ -1,6 +1,7 @@ -//@ aux-build:issue-11680.rs +//! regression test for +//@ aux-build:imported-enum-is-private.rs -extern crate issue_11680 as other; +extern crate imported_enum_is_private as other; fn main() { let _b = other::Foo::Bar(1); diff --git a/tests/ui/privacy/imported-enum-is-private.stderr b/tests/ui/privacy/imported-enum-is-private.stderr index 5bcf93de811f..cae1ebb0e29e 100644 --- a/tests/ui/privacy/imported-enum-is-private.stderr +++ b/tests/ui/privacy/imported-enum-is-private.stderr @@ -1,5 +1,5 @@ error[E0603]: enum `Foo` is private - --> $DIR/issue-11680.rs:6:21 + --> $DIR/imported-enum-is-private.rs:7:21 | LL | let _b = other::Foo::Bar(1); | ^^^ --- tuple variant `Bar` is not publicly re-exported @@ -7,13 +7,13 @@ LL | let _b = other::Foo::Bar(1); | private enum | note: the enum `Foo` is defined here - --> $DIR/auxiliary/issue-11680.rs:1:1 + --> $DIR/auxiliary/imported-enum-is-private.rs:3:1 | LL | enum Foo { | ^^^^^^^^ error[E0603]: enum `Foo` is private - --> $DIR/issue-11680.rs:9:27 + --> $DIR/imported-enum-is-private.rs:10:27 | LL | let _b = other::test::Foo::Bar(1); | ^^^ --- tuple variant `Bar` is not publicly re-exported @@ -21,7 +21,7 @@ LL | let _b = other::test::Foo::Bar(1); | private enum | note: the enum `Foo` is defined here - --> $DIR/auxiliary/issue-11680.rs:6:5 + --> $DIR/auxiliary/imported-enum-is-private.rs:8:5 | LL | enum Foo { | ^^^^^^^^ diff --git a/tests/ui/privacy/private-struct-field-in-module.rs b/tests/ui/privacy/private-struct-field-in-module.rs index b100c59ad0bd..7ed8def1c691 100644 --- a/tests/ui/privacy/private-struct-field-in-module.rs +++ b/tests/ui/privacy/private-struct-field-in-module.rs @@ -1,3 +1,5 @@ +//! regression test for + mod sub { pub struct S { len: usize } impl S { diff --git a/tests/ui/privacy/private-struct-field-in-module.stderr b/tests/ui/privacy/private-struct-field-in-module.stderr index d7134bff1761..2394686f69ca 100644 --- a/tests/ui/privacy/private-struct-field-in-module.stderr +++ b/tests/ui/privacy/private-struct-field-in-module.stderr @@ -1,5 +1,5 @@ error[E0616]: field `len` of struct `S` is private - --> $DIR/issue-26472.rs:11:15 + --> $DIR/private-struct-field-in-module.rs:13:15 | LL | let v = s.len; | ^^^ private field @@ -10,7 +10,7 @@ LL | let v = s.len(); | ++ error[E0616]: field `len` of struct `S` is private - --> $DIR/issue-26472.rs:12:7 + --> $DIR/private-struct-field-in-module.rs:14:7 | LL | s.len = v; | ^^^ private field diff --git a/tests/ui/type-inference/panic-with-unspecified-type.rs b/tests/ui/type-inference/panic-with-unspecified-type.rs index 66a3fadac8d9..0f96759e8144 100644 --- a/tests/ui/type-inference/panic-with-unspecified-type.rs +++ b/tests/ui/type-inference/panic-with-unspecified-type.rs @@ -1,3 +1,4 @@ +//! regression test for //@ edition:2015..2021 fn main() { panic!(std::default::Default::default()); diff --git a/tests/ui/type-inference/panic-with-unspecified-type.stderr b/tests/ui/type-inference/panic-with-unspecified-type.stderr index e294d8830de0..5f08a7552632 100644 --- a/tests/ui/type-inference/panic-with-unspecified-type.stderr +++ b/tests/ui/type-inference/panic-with-unspecified-type.stderr @@ -1,5 +1,5 @@ error[E0283]: type annotations needed - --> $DIR/issue-16966.rs:3:12 + --> $DIR/panic-with-unspecified-type.rs:4:12 | LL | panic!(std::default::Default::default()); | -------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- diff --git a/tests/ui/type-inference/send-with-unspecified-type.rs b/tests/ui/type-inference/send-with-unspecified-type.rs index 4be83457f7a8..4c2de025d69c 100644 --- a/tests/ui/type-inference/send-with-unspecified-type.rs +++ b/tests/ui/type-inference/send-with-unspecified-type.rs @@ -1,3 +1,5 @@ +//! regression test for + use std::sync::mpsc::channel; use std::thread::spawn; use std::marker::PhantomData; diff --git a/tests/ui/type-inference/send-with-unspecified-type.stderr b/tests/ui/type-inference/send-with-unspecified-type.stderr index 23f1441e69dc..85692e8ad0cd 100644 --- a/tests/ui/type-inference/send-with-unspecified-type.stderr +++ b/tests/ui/type-inference/send-with-unspecified-type.stderr @@ -1,5 +1,5 @@ error[E0282]: type annotations needed - --> $DIR/issue-25368.rs:11:27 + --> $DIR/send-with-unspecified-type.rs:13:27 | LL | tx.send(Foo{ foo: PhantomData }); | ^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the struct `PhantomData` diff --git a/tests/ui/type-inference/swap-with-unspecified-type.rs b/tests/ui/type-inference/swap-with-unspecified-type.rs index c6d301671272..db415df19e99 100644 --- a/tests/ui/type-inference/swap-with-unspecified-type.rs +++ b/tests/ui/type-inference/swap-with-unspecified-type.rs @@ -1,3 +1,5 @@ +//! regression test for + fn main() { use std::mem::{transmute, swap}; let a = 1; diff --git a/tests/ui/type-inference/swap-with-unspecified-type.stderr b/tests/ui/type-inference/swap-with-unspecified-type.stderr index 37a86ecc5437..eaaed559ebf1 100644 --- a/tests/ui/type-inference/swap-with-unspecified-type.stderr +++ b/tests/ui/type-inference/swap-with-unspecified-type.stderr @@ -1,5 +1,5 @@ error[E0282]: type annotations needed - --> $DIR/issue-24013.rs:5:13 + --> $DIR/swap-with-unspecified-type.rs:7:13 | LL | unsafe {swap::<&mut _>(transmute(&a), transmute(&b))}; | ^^^^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the function `swap` diff --git a/tests/ui/type/struct-constructor-as-value.rs b/tests/ui/type/struct-constructor-as-value.rs index 2fa762475da9..9cac1caf86ec 100644 --- a/tests/ui/type/struct-constructor-as-value.rs +++ b/tests/ui/type/struct-constructor-as-value.rs @@ -1,3 +1,5 @@ +//! regression test for + struct Foo(u32); fn test() -> Foo { Foo } //~ ERROR mismatched types diff --git a/tests/ui/type/struct-constructor-as-value.stderr b/tests/ui/type/struct-constructor-as-value.stderr index 6f6602793fdb..5915f971b324 100644 --- a/tests/ui/type/struct-constructor-as-value.stderr +++ b/tests/ui/type/struct-constructor-as-value.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-35241.rs:3:20 + --> $DIR/struct-constructor-as-value.rs:5:20 | LL | struct Foo(u32); | ---------- `Foo` defines a struct constructor here, which should be called From db9f9e65013419e87af78c54727f1b4f44bf75b2 Mon Sep 17 00:00:00 2001 From: mu001999 Date: Sun, 18 Jan 2026 13:38:19 +0800 Subject: [PATCH 105/146] Use find_attr instead of attr::contains_name in lower_const_item_rhs --- compiler/rustc_ast_lowering/src/lib.rs | 2 +- .../type-const-assoc-const-without-body.rs | 19 +++++++++++++++++++ ...type-const-assoc-const-without-body.stderr | 10 ++++++++++ ...const-inherent-assoc-const-without-body.rs | 12 ++++++++++++ ...t-inherent-assoc-const-without-body.stderr | 17 +++++++++++++++++ 5 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 tests/ui/const-generics/mgca/type-const-assoc-const-without-body.rs create mode 100644 tests/ui/const-generics/mgca/type-const-assoc-const-without-body.stderr create mode 100644 tests/ui/const-generics/mgca/type-const-inherent-assoc-const-without-body.rs create mode 100644 tests/ui/const-generics/mgca/type-const-inherent-assoc-const-without-body.stderr diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 51d1fd20cec6..8c6ee9d6bc63 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -2384,7 +2384,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { Some(ConstItemRhs::TypeConst(anon)) => { hir::ConstItemRhs::TypeConst(self.lower_anon_const_to_const_arg_and_alloc(anon)) } - None if attr::contains_name(attrs, sym::type_const) => { + None if find_attr!(attrs, AttributeKind::TypeConst(_)) => { let const_arg = ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Error( diff --git a/tests/ui/const-generics/mgca/type-const-assoc-const-without-body.rs b/tests/ui/const-generics/mgca/type-const-assoc-const-without-body.rs new file mode 100644 index 000000000000..158a7addd10d --- /dev/null +++ b/tests/ui/const-generics/mgca/type-const-assoc-const-without-body.rs @@ -0,0 +1,19 @@ +//@ needs-rustc-debug-assertions + +#![feature(min_generic_const_args)] +#![expect(incomplete_features)] + +trait Tr { + #[type_const] + const SIZE: usize; +} + +struct T; + +impl Tr for T { + #[type_const] + const SIZE: usize; + //~^ ERROR associated constant in `impl` without body +} + +fn main() {} diff --git a/tests/ui/const-generics/mgca/type-const-assoc-const-without-body.stderr b/tests/ui/const-generics/mgca/type-const-assoc-const-without-body.stderr new file mode 100644 index 000000000000..2db677aa0ca6 --- /dev/null +++ b/tests/ui/const-generics/mgca/type-const-assoc-const-without-body.stderr @@ -0,0 +1,10 @@ +error: associated constant in `impl` without body + --> $DIR/type-const-assoc-const-without-body.rs:15:5 + | +LL | const SIZE: usize; + | ^^^^^^^^^^^^^^^^^- + | | + | help: provide a definition for the constant: `= ;` + +error: aborting due to 1 previous error + diff --git a/tests/ui/const-generics/mgca/type-const-inherent-assoc-const-without-body.rs b/tests/ui/const-generics/mgca/type-const-inherent-assoc-const-without-body.rs new file mode 100644 index 000000000000..85b2327d3351 --- /dev/null +++ b/tests/ui/const-generics/mgca/type-const-inherent-assoc-const-without-body.rs @@ -0,0 +1,12 @@ +//@ needs-rustc-debug-assertions + +#![feature(min_generic_const_args)] +#![expect(incomplete_features)] + +impl S { //~ ERROR cannot find type `S` in this scope + #[type_const] + const SIZE: usize; + //~^ ERROR associated constant in `impl` without body +} + +fn main() {} diff --git a/tests/ui/const-generics/mgca/type-const-inherent-assoc-const-without-body.stderr b/tests/ui/const-generics/mgca/type-const-inherent-assoc-const-without-body.stderr new file mode 100644 index 000000000000..ac520a4e6946 --- /dev/null +++ b/tests/ui/const-generics/mgca/type-const-inherent-assoc-const-without-body.stderr @@ -0,0 +1,17 @@ +error: associated constant in `impl` without body + --> $DIR/type-const-inherent-assoc-const-without-body.rs:8:5 + | +LL | const SIZE: usize; + | ^^^^^^^^^^^^^^^^^- + | | + | help: provide a definition for the constant: `= ;` + +error[E0425]: cannot find type `S` in this scope + --> $DIR/type-const-inherent-assoc-const-without-body.rs:6:6 + | +LL | impl S { + | ^ not found in this scope + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0425`. From 97603c0df04af46512957dda2b5d9dbba73353e3 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 18 Jan 2026 18:00:08 +1100 Subject: [PATCH 106/146] Use `ty::Value` in more places throughout `const_to_pat` --- .../src/thir/pattern/const_to_pat.rs | 85 +++++++++---------- 1 file changed, 39 insertions(+), 46 deletions(-) diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 70bc142131e4..7fbf8cd11466 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -13,9 +13,7 @@ use rustc_infer::traits::Obligation; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::span_bug; use rustc_middle::thir::{FieldPat, Pat, PatKind}; -use rustc_middle::ty::{ - self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitableExt, TypeVisitor, ValTree, -}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitableExt, TypeVisitor}; use rustc_span::def_id::DefId; use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::traits::ObligationCause; @@ -48,7 +46,7 @@ impl<'tcx> PatCtxt<'tcx> { match c.kind() { ty::ConstKind::Unevaluated(uv) => convert.unevaluated_to_pat(uv, ty), - ty::ConstKind::Value(cv) => convert.valtree_to_pat(cv.valtree, cv.ty), + ty::ConstKind::Value(value) => convert.valtree_to_pat(value), _ => span_bug!(span, "Invalid `ConstKind` for `const_to_pat`: {:?}", c), } } @@ -175,7 +173,7 @@ impl<'tcx> ConstToPat<'tcx> { }; // Lower the valtree to a THIR pattern. - let mut thir_pat = self.valtree_to_pat(valtree, ty); + let mut thir_pat = self.valtree_to_pat(ty::Value { ty, valtree }); if !thir_pat.references_error() { // Always check for `PartialEq` if we had no other errors yet. @@ -192,31 +190,32 @@ impl<'tcx> ConstToPat<'tcx> { thir_pat } - fn field_pats( + fn lower_field_values_to_fieldpats( &self, - vals: impl Iterator, Ty<'tcx>)>, + values: impl Iterator>, ) -> Vec> { - vals.enumerate() - .map(|(idx, (val, ty))| { - let field = FieldIdx::new(idx); - // Patterns can only use monomorphic types. - let ty = self.tcx.normalize_erasing_regions(self.typing_env, ty); - FieldPat { field, pattern: *self.valtree_to_pat(val, ty) } + values + .enumerate() + .map(|(index, value)| FieldPat { + field: FieldIdx::new(index), + pattern: *self.valtree_to_pat(value), }) .collect() } // Recursive helper for `to_pat`; invoke that (instead of calling this directly). - // FIXME(valtrees): Accept `ty::Value` instead of `Ty` and `ty::ValTree` separately. #[instrument(skip(self), level = "debug")] - fn valtree_to_pat(&self, cv: ValTree<'tcx>, ty: Ty<'tcx>) -> Box> { + fn valtree_to_pat(&self, value: ty::Value<'tcx>) -> Box> { let span = self.span; let tcx = self.tcx; + let ty::Value { ty, valtree } = value; + let kind = match ty.kind() { + // Extremely important check for all ADTs! + // Make sure they are eligible to be used in patterns, and if not, emit an error. ty::Adt(adt_def, _) if !self.type_marked_structural(ty) => { - // Extremely important check for all ADTs! Make sure they opted-in to be used in - // patterns. - debug!("adt_def {:?} has !type_marked_structural for cv.ty: {:?}", adt_def, ty); + // This ADT cannot be used as a constant in patterns. + debug!(?adt_def, ?value.ty, "ADT type in pattern is not `type_marked_structural`"); let PartialEqImplStatus { is_derived, structural_partial_eq, non_blanket_impl, .. } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty); @@ -239,51 +238,43 @@ impl<'tcx> ConstToPat<'tcx> { return self.mk_err(tcx.dcx().create_err(err), ty); } ty::Adt(adt_def, args) if adt_def.is_enum() => { - let (&variant_index, fields) = cv.to_branch().split_first().unwrap(); + let (&variant_index, fields) = valtree.to_branch().split_first().unwrap(); let variant_index = VariantIdx::from_u32(variant_index.to_leaf().to_u32()); PatKind::Variant { adt_def: *adt_def, args, variant_index, - subpatterns: self.field_pats( - fields.iter().map(|ct| ct.to_value().valtree).zip( - adt_def.variants()[variant_index] - .fields - .iter() - .map(|field| field.ty(tcx, args)), - ), - ), + subpatterns: self + .lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())), } } - ty::Adt(def, args) => { + ty::Adt(def, _) => { assert!(!def.is_union()); // Valtree construction would never succeed for unions. PatKind::Leaf { - subpatterns: self.field_pats( - cv.to_branch().iter().map(|ct| ct.to_value().valtree).zip( - def.non_enum_variant().fields.iter().map(|field| field.ty(tcx, args)), - ), + subpatterns: self.lower_field_values_to_fieldpats( + valtree.to_branch().iter().map(|ct| ct.to_value()), ), } } - ty::Tuple(fields) => PatKind::Leaf { - subpatterns: self.field_pats( - cv.to_branch().iter().map(|ct| ct.to_value().valtree).zip(fields.iter()), + ty::Tuple(_) => PatKind::Leaf { + subpatterns: self.lower_field_values_to_fieldpats( + valtree.to_branch().iter().map(|ct| ct.to_value()), ), }, - ty::Slice(elem_ty) => PatKind::Slice { - prefix: cv + ty::Slice(_) => PatKind::Slice { + prefix: valtree .to_branch() .iter() - .map(|val| *self.valtree_to_pat(val.to_value().valtree, *elem_ty)) + .map(|val| *self.valtree_to_pat(val.to_value())) .collect(), slice: None, suffix: Box::new([]), }, - ty::Array(elem_ty, _) => PatKind::Array { - prefix: cv + ty::Array(_, _) => PatKind::Array { + prefix: valtree .to_branch() .iter() - .map(|val| *self.valtree_to_pat(val.to_value().valtree, *elem_ty)) + .map(|val| *self.valtree_to_pat(val.to_value())) .collect(), slice: None, suffix: Box::new([]), @@ -296,7 +287,7 @@ impl<'tcx> ConstToPat<'tcx> { // Under `feature(deref_patterns)`, string literal patterns can also // have type `str` directly, without the `&`, in order to allow things // like `deref!("...")` to work when the scrutinee is `String`. - PatKind::Constant { value: ty::Value { ty, valtree: cv } } + PatKind::Constant { value } } ty::Ref(_, pointee_ty, ..) => { if pointee_ty.is_str() @@ -304,7 +295,9 @@ impl<'tcx> ConstToPat<'tcx> { || pointee_ty.is_sized(tcx, self.typing_env) { // References have the same valtree representation as their pointee. - PatKind::Deref { subpattern: self.valtree_to_pat(cv, *pointee_ty) } + PatKind::Deref { + subpattern: self.valtree_to_pat(ty::Value { ty: *pointee_ty, valtree }), + } } else { return self.mk_err( tcx.dcx().create_err(UnsizedPattern { span, non_sm_ty: *pointee_ty }), @@ -313,7 +306,7 @@ impl<'tcx> ConstToPat<'tcx> { } } ty::Float(flt) => { - let v = cv.to_leaf(); + let v = valtree.to_leaf(); let is_nan = match flt { ty::FloatTy::F16 => v.to_f16().is_nan(), ty::FloatTy::F32 => v.to_f32().is_nan(), @@ -325,13 +318,13 @@ impl<'tcx> ConstToPat<'tcx> { // Also see . return self.mk_err(tcx.dcx().create_err(NaNPattern { span }), ty); } else { - PatKind::Constant { value: ty::Value { ty, valtree: cv } } + PatKind::Constant { value } } } ty::Pat(..) | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) => { // The raw pointers we see here have been "vetted" by valtree construction to be // just integers, so we simply allow them. - PatKind::Constant { value: ty::Value { ty, valtree: cv } } + PatKind::Constant { value } } ty::FnPtr(..) => { unreachable!( From f3e73dced1144f3b7cc81b34c45fdafec66e29f2 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Sun, 30 Nov 2025 17:02:07 +0100 Subject: [PATCH 107/146] Supress some lookup errors if a module contains `compile_error!` The problem is that when a macro expand to `compile_error!` because its input is malformed, the actual error message from the `compile_error!` might be hidden in a long list of other messages about using items that should have otherwise been generated by the macro. So suppress error about missing items in that module. Fixes issue 68838 --- .../rustc_builtin_macros/src/compile_error.rs | 1 + compiler/rustc_expand/src/base.rs | 4 ++ compiler/rustc_resolve/src/ident.rs | 3 +- compiler/rustc_resolve/src/macros.rs | 8 ++++ .../compile_error_macro-suppress-errors.rs | 40 ++++++++++++++++ ...compile_error_macro-suppress-errors.stderr | 46 +++++++++++++++++++ 6 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 tests/ui/macros/compile_error_macro-suppress-errors.rs create mode 100644 tests/ui/macros/compile_error_macro-suppress-errors.stderr diff --git a/compiler/rustc_builtin_macros/src/compile_error.rs b/compiler/rustc_builtin_macros/src/compile_error.rs index 7fc4b437c1d8..df64d8f314db 100644 --- a/compiler/rustc_builtin_macros/src/compile_error.rs +++ b/compiler/rustc_builtin_macros/src/compile_error.rs @@ -22,6 +22,7 @@ pub(crate) fn expand_compile_error<'cx>( #[expect(rustc::diagnostic_outside_of_impl, reason = "diagnostic message is specified by user")] #[expect(rustc::untranslatable_diagnostic, reason = "diagnostic message is specified by user")] let guar = cx.dcx().span_err(sp, var.to_string()); + cx.resolver.mark_scope_with_compile_error(cx.current_expansion.lint_node_id); ExpandResult::Ready(DummyResult::any(sp, guar)) } diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index bf653fac5253..a1fc9694d663 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1173,6 +1173,10 @@ pub trait ResolverExpand { /// Record the name of an opaque `Ty::ImplTrait` pre-expansion so that it can be used /// to generate an item name later that does not reference placeholder macros. fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol); + + /// Mark the scope as having a compile error so that error for lookup in this scope + /// should be suppressed + fn mark_scope_with_compile_error(&mut self, parent_node: NodeId); } pub trait LintStoreExpand { diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index f7e628048ccd..79d08828ccc4 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -1711,7 +1711,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { diag_metadata: Option<&DiagMetadata<'_>>, ) -> PathResult<'ra> { let mut module = None; - let mut module_had_parse_errors = false; + let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty() + && self.mods_with_parse_errors.contains(&parent_scope.module.nearest_parent_mod()); let mut allow_super = true; let mut second_binding = None; diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 38628332f43e..7246eded2e72 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -166,6 +166,14 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> { self.invocation_parents[&id].parent_def } + fn mark_scope_with_compile_error(&mut self, id: NodeId) { + if let Some(id) = self.opt_local_def_id(id) + && self.tcx.def_kind(id).is_module_like() + { + self.mods_with_parse_errors.insert(id.to_def_id()); + } + } + fn resolve_dollar_crates(&self) { hygiene::update_dollar_crate_names(|ctxt| { let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt)); diff --git a/tests/ui/macros/compile_error_macro-suppress-errors.rs b/tests/ui/macros/compile_error_macro-suppress-errors.rs new file mode 100644 index 000000000000..b2b6a8ae0088 --- /dev/null +++ b/tests/ui/macros/compile_error_macro-suppress-errors.rs @@ -0,0 +1,40 @@ +pub mod some_module { + compile_error!("Error in a module"); //~ ERROR: Error in a module + + fn abc() -> Hello { + let _: self::SomeType = self::Hello::new(); + let _: SomeType = Hello::new(); + } + + mod inner_module { + use super::Hello; + use crate::another_module::NotExist; //~ ERROR: unresolved import `crate::another_module::NotExist` + use crate::some_module::World; + struct Foo { + bar: crate::some_module::Xyz, + error: self::MissingType, //~ ERROR: cannot find type `MissingType` in module `self` + } + } +} + +pub mod another_module { + use crate::some_module::NotExist; + fn error_in_this_function() { + compile_error!("Error in a function"); //~ ERROR: Error in a function + } +} + +fn main() { + // these errors are suppressed because of the compile_error! macro + + let _ = some_module::some_function(); + let _: some_module::SomeType = some_module::Hello::new(); + + // these errors are not suppressed + + let _ = another_module::some_function(); + //~^ ERROR: cannot find function `some_function` in module `another_module` + let _: another_module::SomeType = another_module::Hello::new(); + //~^ ERROR: cannot find type `SomeType` in module `another_module` + //~^^ ERROR: failed to resolve: could not find `Hello` in `another_module` +} diff --git a/tests/ui/macros/compile_error_macro-suppress-errors.stderr b/tests/ui/macros/compile_error_macro-suppress-errors.stderr new file mode 100644 index 000000000000..73b156359624 --- /dev/null +++ b/tests/ui/macros/compile_error_macro-suppress-errors.stderr @@ -0,0 +1,46 @@ +error: Error in a module + --> $DIR/compile_error_macro-suppress-errors.rs:2:5 + | +LL | compile_error!("Error in a module"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: Error in a function + --> $DIR/compile_error_macro-suppress-errors.rs:23:9 + | +LL | compile_error!("Error in a function"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error[E0432]: unresolved import `crate::another_module::NotExist` + --> $DIR/compile_error_macro-suppress-errors.rs:11:13 + | +LL | use crate::another_module::NotExist; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `NotExist` in `another_module` + +error[E0433]: failed to resolve: could not find `Hello` in `another_module` + --> $DIR/compile_error_macro-suppress-errors.rs:37:55 + | +LL | let _: another_module::SomeType = another_module::Hello::new(); + | ^^^^^ could not find `Hello` in `another_module` + +error[E0425]: cannot find type `MissingType` in module `self` + --> $DIR/compile_error_macro-suppress-errors.rs:15:26 + | +LL | error: self::MissingType, + | ^^^^^^^^^^^ not found in `self` + +error[E0425]: cannot find function `some_function` in module `another_module` + --> $DIR/compile_error_macro-suppress-errors.rs:35:29 + | +LL | let _ = another_module::some_function(); + | ^^^^^^^^^^^^^ not found in `another_module` + +error[E0425]: cannot find type `SomeType` in module `another_module` + --> $DIR/compile_error_macro-suppress-errors.rs:37:28 + | +LL | let _: another_module::SomeType = another_module::Hello::new(); + | ^^^^^^^^ not found in `another_module` + +error: aborting due to 7 previous errors + +Some errors have detailed explanations: E0425, E0432, E0433. +For more information about an error, try `rustc --explain E0425`. From b35f80f7f71336b1b22c5de4af9eb8e6b59cb8f5 Mon Sep 17 00:00:00 2001 From: oligamiq Date: Sun, 18 Jan 2026 23:37:51 +0900 Subject: [PATCH 108/146] fix: thread creation failed on the wasm32-wasip1-threads target. --- library/std/src/sys/thread/unix.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/thread/unix.rs b/library/std/src/sys/thread/unix.rs index 6f23c28c04d6..5a210703ce9b 100644 --- a/library/std/src/sys/thread/unix.rs +++ b/library/std/src/sys/thread/unix.rs @@ -49,7 +49,7 @@ impl Thread { // WASI does not support threading via pthreads. While wasi-libc provides // pthread stubs, pthread_create returns EAGAIN, which causes confusing // errors. We return UNSUPPORTED_PLATFORM directly instead. - if cfg!(target_os = "wasi") { + if cfg!(all(target_os = "wasi", not(target_feature = "atomics"))) { return Err(io::Error::UNSUPPORTED_PLATFORM); } From ea77786cdb7e94006f74399ee67ff57068773375 Mon Sep 17 00:00:00 2001 From: Oscar Bray Date: Sun, 18 Jan 2026 16:48:45 +0000 Subject: [PATCH 109/146] Port #![no_main] to the attribute parser. --- .../src/attributes/crate_level.rs | 9 ++ compiler/rustc_attr_parsing/src/context.rs | 7 +- .../rustc_hir/src/attrs/data_structures.rs | 3 + .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 1 + compiler/rustc_passes/src/entry.rs | 5 +- .../issue-43106-gating-of-builtin-attrs.rs | 12 +- ...issue-43106-gating-of-builtin-attrs.stderr | 131 ++++++++++-------- 8 files changed, 96 insertions(+), 73 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/crate_level.rs b/compiler/rustc_attr_parsing/src/attributes/crate_level.rs index 5604fbd25edc..ab99186777f9 100644 --- a/compiler/rustc_attr_parsing/src/attributes/crate_level.rs +++ b/compiler/rustc_attr_parsing/src/attributes/crate_level.rs @@ -136,6 +136,15 @@ impl NoArgsAttributeParser for NoStdParser { const CREATE: fn(Span) -> AttributeKind = AttributeKind::NoStd; } +pub(crate) struct NoMainParser; + +impl NoArgsAttributeParser for NoMainParser { + const PATH: &[Symbol] = &[sym::no_main]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::NoMain; +} + pub(crate) struct RustcCoherenceIsCoreParser; impl NoArgsAttributeParser for RustcCoherenceIsCoreParser { diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 449894f7834b..c5b98139074e 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -28,9 +28,9 @@ use crate::attributes::codegen_attrs::{ }; use crate::attributes::confusables::ConfusablesParser; use crate::attributes::crate_level::{ - CrateNameParser, MoveSizeLimitParser, NoCoreParser, NoStdParser, PatternComplexityLimitParser, - RecursionLimitParser, RustcCoherenceIsCoreParser, TypeLengthLimitParser, - WindowsSubsystemParser, + CrateNameParser, MoveSizeLimitParser, NoCoreParser, NoMainParser, NoStdParser, + PatternComplexityLimitParser, RecursionLimitParser, RustcCoherenceIsCoreParser, + TypeLengthLimitParser, WindowsSubsystemParser, }; use crate::attributes::debugger::DebuggerViualizerParser; use crate::attributes::deprecation::DeprecationParser; @@ -263,6 +263,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 7b7fae9fdcca..119bf554b2ae 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -852,6 +852,9 @@ pub enum AttributeKind { /// Represents `#[no_link]` NoLink, + /// Represents `#[no_main]` + NoMain, + /// Represents `#[no_mangle]` NoMangle(Span), diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index dff8a5727771..7ba268c16271 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -79,6 +79,7 @@ impl AttributeKind { NoCore(..) => No, NoImplicitPrelude(..) => No, NoLink => No, + NoMain => No, NoMangle(..) => Yes, // Needed for rustdoc NoStd(..) => No, NonExhaustive(..) => Yes, // Needed for rustdoc diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4b71d4755cb6..50e80cabdb07 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -297,6 +297,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::PatternComplexityLimit { .. } | AttributeKind::NoCore { .. } | AttributeKind::NoStd { .. } + | AttributeKind::NoMain | AttributeKind::ObjcClass { .. } | AttributeKind::ObjcSelector { .. } | AttributeKind::RustcCoherenceIsCore(..) diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index c02a01c1b823..bd737518ed47 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -1,4 +1,3 @@ -use rustc_ast::attr; use rustc_ast::entry::EntryPointType; use rustc_errors::codes::*; use rustc_hir::attrs::AttributeKind; @@ -7,7 +6,7 @@ use rustc_hir::{CRATE_HIR_ID, ItemId, Node, find_attr}; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::config::{CrateType, EntryFnType, sigpipe}; -use rustc_span::{RemapPathScopeComponents, Span, sym}; +use rustc_span::{RemapPathScopeComponents, Span}; use crate::errors::{ExternMain, MultipleRustcMain, NoMainErr}; @@ -30,7 +29,7 @@ fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> { } // If the user wants no main function at all, then stop here. - if attr::contains_name(tcx.hir_attrs(CRATE_HIR_ID), sym::no_main) { + if find_attr!(tcx.hir_attrs(CRATE_HIR_ID), AttributeKind::NoMain) { return None; } diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs index 6716e78a7197..3e3235e658f6 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs @@ -884,26 +884,26 @@ mod feature { #[no_main] //~^ WARN crate-level attribute should be an inner attribute -//~| HELP add a `!` mod no_main_1 { + //~^ NOTE: This attribute does not have an `!`, which means it is applied to this module mod inner { #![no_main] } -//~^ WARN crate-level attribute should be in the root module + //~^ WARN the `#![no_main]` attribute can only be used at the crate root #[no_main] fn f() { } //~^ WARN crate-level attribute should be an inner attribute - //~| HELP add a `!` + //~| NOTE This attribute does not have an `!`, which means it is applied to this function #[no_main] struct S; //~^ WARN crate-level attribute should be an inner attribute - //~| HELP add a `!` + //~| NOTE This attribute does not have an `!`, which means it is applied to this struct #[no_main] type T = S; //~^ WARN crate-level attribute should be an inner attribute - //~| HELP add a `!` + //~| NOTE This attribute does not have an `!`, which means it is applied to this type alias #[no_main] impl S { } //~^ WARN crate-level attribute should be an inner attribute - //~| HELP add a `!` + //~| NOTE This attribute does not have an `!`, which means it is applied to this implementation } #[no_builtins] diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr index 8ed39a0079ba..d89aec222be8 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr @@ -240,17 +240,6 @@ help: add a `!` LL | #![feature(x0600)] | + -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:885:1 - | -LL | #[no_main] - | ^^^^^^^^^^ - | -help: add a `!` - | -LL | #![no_main] - | + - warning: crate-level attribute should be an inner attribute --> $DIR/issue-43106-gating-of-builtin-attrs.rs:909:1 | @@ -476,56 +465,6 @@ help: add a `!` LL | #![feature(x0600)] impl S { } | + -warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:889:17 - | -LL | mod inner { #![no_main] } - | ^^^^^^^^^^^ - -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:892:5 - | -LL | #[no_main] fn f() { } - | ^^^^^^^^^^ - | -help: add a `!` - | -LL | #![no_main] fn f() { } - | + - -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:896:5 - | -LL | #[no_main] struct S; - | ^^^^^^^^^^ - | -help: add a `!` - | -LL | #![no_main] struct S; - | + - -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:900:5 - | -LL | #[no_main] type T = S; - | ^^^^^^^^^^ - | -help: add a `!` - | -LL | #![no_main] type T = S; - | + - -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:904:5 - | -LL | #[no_main] impl S { } - | ^^^^^^^^^^ - | -help: add a `!` - | -LL | #![no_main] impl S { } - | + - warning: crate-level attribute should be in the root module --> $DIR/issue-43106-gating-of-builtin-attrs.rs:913:17 | @@ -1407,6 +1346,76 @@ note: This attribute does not have an `!`, which means it is applied to this imp LL | #[crate_name = "0900"] impl S { } | ^^^^^^^^^^ +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![no_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:885:1 + | +LL | #[no_main] + | ^^^^^^^^^^ + | +note: This attribute does not have an `!`, which means it is applied to this module + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:887:1 + | +LL | / mod no_main_1 { +LL | | +LL | | mod inner { #![no_main] } +... | +LL | | } + | |_^ + +warning: the `#![no_main]` attribute can only be used at the crate root + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:889:17 + | +LL | mod inner { #![no_main] } + | ^^^^^^^^^^^ + +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![no_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:892:5 + | +LL | #[no_main] fn f() { } + | ^^^^^^^^^^ + | +note: This attribute does not have an `!`, which means it is applied to this function + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:892:16 + | +LL | #[no_main] fn f() { } + | ^^^^^^^^^^ + +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![no_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:896:5 + | +LL | #[no_main] struct S; + | ^^^^^^^^^^ + | +note: This attribute does not have an `!`, which means it is applied to this struct + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:896:16 + | +LL | #[no_main] struct S; + | ^^^^^^^^^ + +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![no_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:900:5 + | +LL | #[no_main] type T = S; + | ^^^^^^^^^^ + | +note: This attribute does not have an `!`, which means it is applied to this type alias + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:900:16 + | +LL | #[no_main] type T = S; + | ^^^^^^^^^^^ + +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![no_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:904:5 + | +LL | #[no_main] impl S { } + | ^^^^^^^^^^ + | +note: This attribute does not have an `!`, which means it is applied to this implementation block + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:904:16 + | +LL | #[no_main] impl S { } + | ^^^^^^^^^^ + warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![recursion_limit]` --> $DIR/issue-43106-gating-of-builtin-attrs.rs:933:1 | From ec787b07fd34fd68a35a6d9b07927dd06dad6da4 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 18 Jan 2026 18:26:59 +0100 Subject: [PATCH 110/146] Remove `DiagMessage::Translated` in favour of `DiagMessage::Str` --- compiler/rustc_error_messages/src/lib.rs | 22 +++++----------------- compiler/rustc_errors/src/lib.rs | 2 +- compiler/rustc_errors/src/translation.rs | 2 +- 3 files changed, 7 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index 085403c8ef36..c0737edd7d65 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -244,13 +244,6 @@ type FluentId = Cow<'static, str>; pub enum SubdiagMessage { /// Non-translatable diagnostic message. Str(Cow<'static, str>), - /// Translatable message which has already been translated eagerly. - /// - /// Some diagnostics have repeated subdiagnostics where the same interpolated variables would - /// be instantiated multiple times with different values. These subdiagnostics' messages - /// are translated when they are added to the parent diagnostic, producing this variant of - /// `DiagMessage`. - Translated(Cow<'static, str>), /// Identifier of a Fluent message. Instances of this variant are generated by the /// `Subdiagnostic` derive. FluentIdentifier(FluentId), @@ -285,15 +278,13 @@ impl From> for SubdiagMessage { #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)] #[rustc_diagnostic_item = "DiagMessage"] pub enum DiagMessage { - /// Non-translatable diagnostic message. - Str(Cow<'static, str>), - /// Translatable message which has been already translated. + /// Non-translatable diagnostic message or a message that has been translated eagerly. /// /// Some diagnostics have repeated subdiagnostics where the same interpolated variables would /// be instantiated multiple times with different values. These subdiagnostics' messages - /// are translated when they are added to the parent diagnostic, producing this variant of - /// `DiagMessage`. - Translated(Cow<'static, str>), + /// are translated when they are added to the parent diagnostic. This is one of the ways + /// this variant of `DiagMessage` is produced. + Str(Cow<'static, str>), /// Identifier for a Fluent message (with optional attribute) corresponding to the diagnostic /// message. Yet to be translated. /// @@ -311,7 +302,6 @@ impl DiagMessage { pub fn with_subdiagnostic_message(&self, sub: SubdiagMessage) -> Self { let attr = match sub { SubdiagMessage::Str(s) => return DiagMessage::Str(s), - SubdiagMessage::Translated(s) => return DiagMessage::Translated(s), SubdiagMessage::FluentIdentifier(id) => { return DiagMessage::FluentIdentifier(id, None); } @@ -320,7 +310,6 @@ impl DiagMessage { match self { DiagMessage::Str(s) => DiagMessage::Str(s.clone()), - DiagMessage::Translated(s) => DiagMessage::Translated(s.clone()), DiagMessage::FluentIdentifier(id, _) => { DiagMessage::FluentIdentifier(id.clone(), Some(attr)) } @@ -329,7 +318,7 @@ impl DiagMessage { pub fn as_str(&self) -> Option<&str> { match self { - DiagMessage::Translated(s) | DiagMessage::Str(s) => Some(s), + DiagMessage::Str(s) => Some(s), DiagMessage::FluentIdentifier(_, _) => None, } } @@ -360,7 +349,6 @@ impl From for SubdiagMessage { fn from(val: DiagMessage) -> Self { match val { DiagMessage::Str(s) => SubdiagMessage::Str(s), - DiagMessage::Translated(s) => SubdiagMessage::Translated(s), DiagMessage::FluentIdentifier(id, None) => SubdiagMessage::FluentIdentifier(id), // There isn't really a sensible behaviour for this because it loses information but // this is the most sensible of the behaviours. diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 148368045f4f..102dd840556b 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -1745,7 +1745,7 @@ impl DiagCtxtInner { message: DiagMessage, args: impl Iterator>, ) -> SubdiagMessage { - SubdiagMessage::Translated(Cow::from(self.eagerly_translate_to_string(message, args))) + SubdiagMessage::Str(Cow::from(self.eagerly_translate_to_string(message, args))) } /// Translate `message` eagerly with `args` to `String`. diff --git a/compiler/rustc_errors/src/translation.rs b/compiler/rustc_errors/src/translation.rs index c0bcec093c7e..5bffd74740dc 100644 --- a/compiler/rustc_errors/src/translation.rs +++ b/compiler/rustc_errors/src/translation.rs @@ -76,7 +76,7 @@ impl Translator { ) -> Result, TranslateError<'a>> { trace!(?message, ?args); let (identifier, attr) = match message { - DiagMessage::Str(msg) | DiagMessage::Translated(msg) => { + DiagMessage::Str(msg) => { return Ok(Cow::Borrowed(msg)); } DiagMessage::FluentIdentifier(identifier, attr) => (identifier, attr), From 858fb400225aca8bc3a666ba9e1a039b03cc3131 Mon Sep 17 00:00:00 2001 From: Edvin Bryntesson Date: Sun, 18 Jan 2026 20:06:15 +0100 Subject: [PATCH 111/146] Port #[rustc_allocator] to attr parser --- compiler/rustc_attr_parsing/src/attributes/mod.rs | 1 + .../src/attributes/rustc_allocator.rs | 11 +++++++++++ compiler/rustc_attr_parsing/src/context.rs | 15 +++++++++------ compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 4 +++- compiler/rustc_hir/src/attrs/data_structures.rs | 3 +++ .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 2 +- 7 files changed, 29 insertions(+), 8 deletions(-) create mode 100644 compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index 64aa7a66b019..0d328d5cc6a7 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -58,6 +58,7 @@ pub(crate) mod pin_v2; pub(crate) mod proc_macro_attrs; pub(crate) mod prototype; pub(crate) mod repr; +pub(crate) mod rustc_allocator; pub(crate) mod rustc_dump; pub(crate) mod rustc_internal; pub(crate) mod semantics; diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs new file mode 100644 index 000000000000..d7925f6fc372 --- /dev/null +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs @@ -0,0 +1,11 @@ +use super::prelude::*; + +pub(crate) struct RustcAllocatorParser; + +impl NoArgsAttributeParser for RustcAllocatorParser { + const PATH: &[Symbol] = &[sym::rustc_allocator]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = + AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcAllocator; +} \ No newline at end of file diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 449894f7834b..652a5e2cf1c6 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -64,17 +64,19 @@ use crate::attributes::proc_macro_attrs::{ }; use crate::attributes::prototype::CustomMirParser; use crate::attributes::repr::{AlignParser, AlignStaticParser, ReprParser}; +use crate::attributes::rustc_allocator::RustcAllocatorParser; use crate::attributes::rustc_dump::{ RustcDumpDefParents, RustcDumpItemBounds, RustcDumpPredicates, RustcDumpUserArgs, RustcDumpVtable, }; use crate::attributes::rustc_internal::{ - RustcHasIncoherentInherentImplsParser, RustcLayoutScalarValidRangeEndParser, - RustcLayoutScalarValidRangeStartParser, RustcLegacyConstGenericsParser, - RustcLintDiagnosticsParser, RustcLintOptDenyFieldAccessParser, RustcLintOptTyParser, - RustcLintQueryInstabilityParser, RustcLintUntrackedQueryInformationParser, RustcMainParser, - RustcMustImplementOneOfParser, RustcNeverReturnsNullPointerParser, - RustcNoImplicitAutorefsParser, RustcObjectLifetimeDefaultParser, RustcScalableVectorParser, + RustcHasIncoherentInherentImplsParser, + RustcLayoutScalarValidRangeEndParser, RustcLayoutScalarValidRangeStartParser, + RustcLegacyConstGenericsParser, RustcLintDiagnosticsParser, RustcLintOptDenyFieldAccessParser, + RustcLintOptTyParser, RustcLintQueryInstabilityParser, + RustcLintUntrackedQueryInformationParser, RustcMainParser, RustcMustImplementOneOfParser, + RustcNeverReturnsNullPointerParser, RustcNoImplicitAutorefsParser, + RustcObjectLifetimeDefaultParser, RustcScalableVectorParser, RustcSimdMonomorphizeLaneLimitParser, }; use crate::attributes::semantics::MayDangleParser; @@ -273,6 +275,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index fa02c5c51f7c..c3bf92df34a0 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -335,6 +335,9 @@ fn process_builtin_attrs( AttributeKind::InstructionSet(instruction_set) => { codegen_fn_attrs.instruction_set = Some(*instruction_set) } + AttributeKind::RustcAllocator => { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR + } _ => {} } } @@ -344,7 +347,6 @@ fn process_builtin_attrs( }; match name { - sym::rustc_allocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR, sym::rustc_nounwind => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND, sym::rustc_reallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR, sym::rustc_deallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR, diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 7b7fae9fdcca..b884372c2a7c 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -906,6 +906,9 @@ pub enum AttributeKind { /// Represents [`#[repr]`](https://doc.rust-lang.org/stable/reference/type-layout.html#representations). Repr { reprs: ThinVec<(ReprAttr, Span)>, first_span: Span }, + /// Represents `#[rustc_allocator]` + RustcAllocator, + /// Represents `#[rustc_builtin_macro]`. RustcBuiltinMacro { builtin_name: Option, helper_attrs: ThinVec, span: Span }, diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index dff8a5727771..e81e74435e51 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -97,6 +97,7 @@ impl AttributeKind { PubTransparent(..) => Yes, RecursionLimit { .. } => No, Repr { .. } => No, + RustcAllocator => No, RustcBuiltinMacro { .. } => Yes, RustcCoherenceIsCore(..) => No, RustcDumpDefParents => No, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4b71d4755cb6..c4de0f44a648 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -316,6 +316,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcDumpDefParents | AttributeKind::RustcDumpVtable(..) | AttributeKind::NeedsAllocator + | AttributeKind::RustcAllocator ) => { /* do nothing */ } Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); @@ -360,7 +361,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::rustc_do_not_const_check | sym::rustc_reservation_impl | sym::rustc_doc_primitive - | sym::rustc_allocator | sym::rustc_deallocator | sym::rustc_reallocator | sym::rustc_conversion_suggestion From 027a6f268f4989198db21aded966c22eb48311cf Mon Sep 17 00:00:00 2001 From: Edvin Bryntesson Date: Sun, 18 Jan 2026 19:35:33 +0100 Subject: [PATCH 112/146] Port `#[rustc_deallocator]` to attr parser --- .../src/attributes/rustc_allocator.rs | 12 +++++++++++- compiler/rustc_attr_parsing/src/context.rs | 16 ++++++++-------- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 4 +++- compiler/rustc_hir/src/attrs/data_structures.rs | 3 +++ .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 2 +- 6 files changed, 27 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs index d7925f6fc372..8eb252d3ff8d 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs @@ -8,4 +8,14 @@ impl NoArgsAttributeParser for RustcAllocatorParser { const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]); const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcAllocator; -} \ No newline at end of file +} + +pub(crate) struct RustcDeallocatorParser; + +impl NoArgsAttributeParser for RustcDeallocatorParser { + const PATH: &[Symbol] = &[sym::rustc_deallocator]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = + AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDeallocator; +} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 652a5e2cf1c6..454a2b427313 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -64,19 +64,18 @@ use crate::attributes::proc_macro_attrs::{ }; use crate::attributes::prototype::CustomMirParser; use crate::attributes::repr::{AlignParser, AlignStaticParser, ReprParser}; -use crate::attributes::rustc_allocator::RustcAllocatorParser; +use crate::attributes::rustc_allocator::{RustcAllocatorParser, RustcDeallocatorParser}; use crate::attributes::rustc_dump::{ RustcDumpDefParents, RustcDumpItemBounds, RustcDumpPredicates, RustcDumpUserArgs, RustcDumpVtable, }; use crate::attributes::rustc_internal::{ - RustcHasIncoherentInherentImplsParser, - RustcLayoutScalarValidRangeEndParser, RustcLayoutScalarValidRangeStartParser, - RustcLegacyConstGenericsParser, RustcLintDiagnosticsParser, RustcLintOptDenyFieldAccessParser, - RustcLintOptTyParser, RustcLintQueryInstabilityParser, - RustcLintUntrackedQueryInformationParser, RustcMainParser, RustcMustImplementOneOfParser, - RustcNeverReturnsNullPointerParser, RustcNoImplicitAutorefsParser, - RustcObjectLifetimeDefaultParser, RustcScalableVectorParser, + RustcHasIncoherentInherentImplsParser, RustcLayoutScalarValidRangeEndParser, + RustcLayoutScalarValidRangeStartParser, RustcLegacyConstGenericsParser, + RustcLintDiagnosticsParser, RustcLintOptDenyFieldAccessParser, RustcLintOptTyParser, + RustcLintQueryInstabilityParser, RustcLintUntrackedQueryInformationParser, RustcMainParser, + RustcMustImplementOneOfParser, RustcNeverReturnsNullPointerParser, + RustcNoImplicitAutorefsParser, RustcObjectLifetimeDefaultParser, RustcScalableVectorParser, RustcSimdMonomorphizeLaneLimitParser, }; use crate::attributes::semantics::MayDangleParser; @@ -277,6 +276,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index c3bf92df34a0..70328c14b19c 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -338,6 +338,9 @@ fn process_builtin_attrs( AttributeKind::RustcAllocator => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR } + AttributeKind::RustcDeallocator => { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR + } _ => {} } } @@ -349,7 +352,6 @@ fn process_builtin_attrs( match name { sym::rustc_nounwind => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND, sym::rustc_reallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR, - sym::rustc_deallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR, sym::rustc_allocator_zeroed => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED } diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index b884372c2a7c..6f91dd48cb5a 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -915,6 +915,9 @@ pub enum AttributeKind { /// Represents `#[rustc_coherence_is_core]` RustcCoherenceIsCore(Span), + /// Represents `#[rustc_deallocator]` + RustcDeallocator, + /// Represents `#[rustc_dump_def_parents]` RustcDumpDefParents, diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index e81e74435e51..9fcaf77f69a4 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -100,6 +100,7 @@ impl AttributeKind { RustcAllocator => No, RustcBuiltinMacro { .. } => Yes, RustcCoherenceIsCore(..) => No, + RustcDeallocator => No, RustcDumpDefParents => No, RustcDumpItemBounds => No, RustcDumpPredicates => No, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index c4de0f44a648..83a4bd9f0cda 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -317,6 +317,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcDumpVtable(..) | AttributeKind::NeedsAllocator | AttributeKind::RustcAllocator + | AttributeKind::RustcDeallocator ) => { /* do nothing */ } Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); @@ -361,7 +362,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::rustc_do_not_const_check | sym::rustc_reservation_impl | sym::rustc_doc_primitive - | sym::rustc_deallocator | sym::rustc_reallocator | sym::rustc_conversion_suggestion | sym::rustc_allocator_zeroed From 9a7614da04b5b3258b24ce64e197dd2989cff1d9 Mon Sep 17 00:00:00 2001 From: Edvin Bryntesson Date: Sun, 18 Jan 2026 19:40:19 +0100 Subject: [PATCH 113/146] Port `#[rustc_reallocator]` to attr parser --- .../src/attributes/rustc_allocator.rs | 10 ++++++++++ compiler/rustc_attr_parsing/src/context.rs | 5 ++++- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 4 +++- compiler/rustc_hir/src/attrs/data_structures.rs | 3 +++ compiler/rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 2 +- 6 files changed, 22 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs index 8eb252d3ff8d..9324f0c01156 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs @@ -19,3 +19,13 @@ impl NoArgsAttributeParser for RustcDeallocatorParser { AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]); const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDeallocator; } + +pub(crate) struct RustcReallocatorParser; + +impl NoArgsAttributeParser for RustcReallocatorParser { + const PATH: &[Symbol] = &[sym::rustc_reallocator]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = + AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcReallocator; +} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 454a2b427313..19e03f1ad3eb 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -64,7 +64,9 @@ use crate::attributes::proc_macro_attrs::{ }; use crate::attributes::prototype::CustomMirParser; use crate::attributes::repr::{AlignParser, AlignStaticParser, ReprParser}; -use crate::attributes::rustc_allocator::{RustcAllocatorParser, RustcDeallocatorParser}; +use crate::attributes::rustc_allocator::{ + RustcAllocatorParser, RustcDeallocatorParser, RustcReallocatorParser, +}; use crate::attributes::rustc_dump::{ RustcDumpDefParents, RustcDumpItemBounds, RustcDumpPredicates, RustcDumpUserArgs, RustcDumpVtable, @@ -291,6 +293,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 70328c14b19c..86ea1ac94b4e 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -341,6 +341,9 @@ fn process_builtin_attrs( AttributeKind::RustcDeallocator => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR } + AttributeKind::RustcReallocator => { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR + } _ => {} } } @@ -351,7 +354,6 @@ fn process_builtin_attrs( match name { sym::rustc_nounwind => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND, - sym::rustc_reallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR, sym::rustc_allocator_zeroed => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED } diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 6f91dd48cb5a..95c4b28f1421 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -978,6 +978,9 @@ pub enum AttributeKind { /// Represents `#[rustc_pass_indirectly_in_non_rustic_abis]` RustcPassIndirectlyInNonRusticAbis(Span), + /// Represents `#[rustc_reallocator]` + RustcReallocator, + /// Represents `#[rustc_scalable_vector(N)]` RustcScalableVector { /// The base multiple of lanes that are in a scalable vector, if provided. `element_count` diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 9fcaf77f69a4..0dd2cefc83cf 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -121,6 +121,7 @@ impl AttributeKind { RustcNoImplicitAutorefs => Yes, RustcObjectLifetimeDefault => No, RustcPassIndirectlyInNonRusticAbis(..) => No, + RustcReallocator => No, RustcScalableVector { .. } => Yes, RustcShouldNotBeCalledOnConstItems(..) => Yes, RustcSimdMonomorphizeLaneLimit(..) => Yes, // Affects layout computation, which needs to work cross-crate diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 83a4bd9f0cda..4e904b6f11ad 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -318,6 +318,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::NeedsAllocator | AttributeKind::RustcAllocator | AttributeKind::RustcDeallocator + | AttributeKind::RustcReallocator ) => { /* do nothing */ } Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); @@ -362,7 +363,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::rustc_do_not_const_check | sym::rustc_reservation_impl | sym::rustc_doc_primitive - | sym::rustc_reallocator | sym::rustc_conversion_suggestion | sym::rustc_allocator_zeroed | sym::rustc_allocator_zeroed_variant From 21c9bd7692a9ed139e12c2bfc367b9c71160fcd5 Mon Sep 17 00:00:00 2001 From: Edvin Bryntesson Date: Sun, 18 Jan 2026 19:47:09 +0100 Subject: [PATCH 114/146] Port `#[rustc_allocator_zeroed]` to attr parser --- .../src/attributes/rustc_allocator.rs | 10 ++++++++++ compiler/rustc_attr_parsing/src/context.rs | 4 +++- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 6 +++--- compiler/rustc_hir/src/attrs/data_structures.rs | 3 +++ compiler/rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 2 +- 6 files changed, 21 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs index 9324f0c01156..4622348ef1db 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs @@ -10,6 +10,16 @@ impl NoArgsAttributeParser for RustcAllocatorParser { const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcAllocator; } +pub(crate) struct RustcAllocatorZeroedParser; + +impl NoArgsAttributeParser for RustcAllocatorZeroedParser { + const PATH: &[Symbol] = &[sym::rustc_allocator_zeroed]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = + AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcAllocatorZeroed; +} + pub(crate) struct RustcDeallocatorParser; impl NoArgsAttributeParser for RustcDeallocatorParser { diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 19e03f1ad3eb..7e69cbf1ff6d 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -65,7 +65,8 @@ use crate::attributes::proc_macro_attrs::{ use crate::attributes::prototype::CustomMirParser; use crate::attributes::repr::{AlignParser, AlignStaticParser, ReprParser}; use crate::attributes::rustc_allocator::{ - RustcAllocatorParser, RustcDeallocatorParser, RustcReallocatorParser, + RustcAllocatorParser, RustcAllocatorZeroedParser, RustcDeallocatorParser, + RustcReallocatorParser, }; use crate::attributes::rustc_dump::{ RustcDumpDefParents, RustcDumpItemBounds, RustcDumpPredicates, RustcDumpUserArgs, @@ -277,6 +278,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 86ea1ac94b4e..1b0427e7e676 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -344,6 +344,9 @@ fn process_builtin_attrs( AttributeKind::RustcReallocator => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR } + AttributeKind::RustcAllocatorZeroed => { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED + } _ => {} } } @@ -354,9 +357,6 @@ fn process_builtin_attrs( match name { sym::rustc_nounwind => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND, - sym::rustc_allocator_zeroed => { - codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED - } sym::patchable_function_entry => { codegen_fn_attrs.patchable_function_entry = parse_patchable_function_entry(tcx, attr); diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 95c4b28f1421..1c0562d38d8a 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -909,6 +909,9 @@ pub enum AttributeKind { /// Represents `#[rustc_allocator]` RustcAllocator, + /// Represents `#[rustc_allocator_zeroed]` + RustcAllocatorZeroed, + /// Represents `#[rustc_builtin_macro]`. RustcBuiltinMacro { builtin_name: Option, helper_attrs: ThinVec, span: Span }, diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 0dd2cefc83cf..803aca49b406 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -98,6 +98,7 @@ impl AttributeKind { RecursionLimit { .. } => No, Repr { .. } => No, RustcAllocator => No, + RustcAllocatorZeroed => No, RustcBuiltinMacro { .. } => Yes, RustcCoherenceIsCore(..) => No, RustcDeallocator => No, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4e904b6f11ad..ca0d6b90a1c4 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -317,6 +317,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcDumpVtable(..) | AttributeKind::NeedsAllocator | AttributeKind::RustcAllocator + | AttributeKind::RustcAllocatorZeroed | AttributeKind::RustcDeallocator | AttributeKind::RustcReallocator ) => { /* do nothing */ } @@ -364,7 +365,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::rustc_reservation_impl | sym::rustc_doc_primitive | sym::rustc_conversion_suggestion - | sym::rustc_allocator_zeroed | sym::rustc_allocator_zeroed_variant | sym::rustc_deprecated_safe_2024 | sym::rustc_test_marker From 9a931e8bf2c4a329df8f32d587e056d7b127ec5a Mon Sep 17 00:00:00 2001 From: Edvin Bryntesson Date: Sun, 18 Jan 2026 20:02:41 +0100 Subject: [PATCH 115/146] Port `#[rustc_allocator_zeroed_variant]` to attr parser --- .../src/attributes/rustc_allocator.rs | 19 +++++++++++++++++++ compiler/rustc_attr_parsing/src/context.rs | 5 +++-- compiler/rustc_codegen_llvm/src/attributes.rs | 5 ++--- .../rustc_hir/src/attrs/data_structures.rs | 3 +++ .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 2 +- 6 files changed, 29 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs index 4622348ef1db..5782f9473a99 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_allocator.rs @@ -20,6 +20,25 @@ impl NoArgsAttributeParser for RustcAllocatorZeroedParser { const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcAllocatorZeroed; } +pub(crate) struct RustcAllocatorZeroedVariantParser; + +impl SingleAttributeParser for RustcAllocatorZeroedVariantParser { + const PATH: &[Symbol] = &[sym::rustc_allocator_zeroed_variant]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = + AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]); + const TEMPLATE: AttributeTemplate = template!(NameValueStr: "function"); + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; + fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option { + let Some(name) = args.name_value().and_then(NameValueParser::value_as_str) else { + cx.expected_name_value(cx.attr_span, None); + return None; + }; + + Some(AttributeKind::RustcAllocatorZeroedVariant { name }) + } +} + pub(crate) struct RustcDeallocatorParser; impl NoArgsAttributeParser for RustcDeallocatorParser { diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 7e69cbf1ff6d..7c0182c7e063 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -65,8 +65,8 @@ use crate::attributes::proc_macro_attrs::{ use crate::attributes::prototype::CustomMirParser; use crate::attributes::repr::{AlignParser, AlignStaticParser, ReprParser}; use crate::attributes::rustc_allocator::{ - RustcAllocatorParser, RustcAllocatorZeroedParser, RustcDeallocatorParser, - RustcReallocatorParser, + RustcAllocatorParser, RustcAllocatorZeroedParser, RustcAllocatorZeroedVariantParser, + RustcDeallocatorParser, RustcReallocatorParser, }; use crate::attributes::rustc_dump::{ RustcDumpDefParents, RustcDumpItemBounds, RustcDumpPredicates, RustcDumpUserArgs, @@ -227,6 +227,7 @@ attribute_parsers!( Single, Single, Single, + Single, Single, Single, Single, diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index a25ce9e5a90a..28e91a25a21a 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -1,6 +1,7 @@ //! Set and unset common attributes on LLVM values. use rustc_hir::attrs::{InlineAttr, InstructionSetAttr, OptimizeAttr, RtsanSetting}; use rustc_hir::def_id::DefId; +use rustc_hir::find_attr; use rustc_middle::middle::codegen_fn_attrs::{ CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, SanitizerFnAttrs, }; @@ -470,9 +471,7 @@ pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>( { to_add.push(create_alloc_family_attr(cx.llcx)); if let Some(instance) = instance - && let Some(zv) = - tcx.get_attr(instance.def_id(), rustc_span::sym::rustc_allocator_zeroed_variant) - && let Some(name) = zv.value_str() + && let Some(name) = find_attr!(tcx.get_all_attrs(instance.def_id()), rustc_hir::attrs::AttributeKind::RustcAllocatorZeroedVariant {name} => name) { to_add.push(llvm::CreateAttrStringValue( cx.llcx, diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 1c0562d38d8a..eff871cb8bb4 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -912,6 +912,9 @@ pub enum AttributeKind { /// Represents `#[rustc_allocator_zeroed]` RustcAllocatorZeroed, + /// Represents `#[rustc_allocator_zeroed_variant]` + RustcAllocatorZeroedVariant { name: Symbol }, + /// Represents `#[rustc_builtin_macro]`. RustcBuiltinMacro { builtin_name: Option, helper_attrs: ThinVec, span: Span }, diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 803aca49b406..28b41ac70925 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -99,6 +99,7 @@ impl AttributeKind { Repr { .. } => No, RustcAllocator => No, RustcAllocatorZeroed => No, + RustcAllocatorZeroedVariant { .. } => Yes, RustcBuiltinMacro { .. } => Yes, RustcCoherenceIsCore(..) => No, RustcDeallocator => No, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index ca0d6b90a1c4..1e723dd6b464 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -318,6 +318,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::NeedsAllocator | AttributeKind::RustcAllocator | AttributeKind::RustcAllocatorZeroed + | AttributeKind::RustcAllocatorZeroedVariant { .. } | AttributeKind::RustcDeallocator | AttributeKind::RustcReallocator ) => { /* do nothing */ } @@ -365,7 +366,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::rustc_reservation_impl | sym::rustc_doc_primitive | sym::rustc_conversion_suggestion - | sym::rustc_allocator_zeroed_variant | sym::rustc_deprecated_safe_2024 | sym::rustc_test_marker | sym::rustc_abi From 7216b035fa406b924099d1b1e8c4f392e4e02597 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 18 Jan 2026 21:27:40 +0100 Subject: [PATCH 116/146] Factor out diagnostic slug checking from `DiagnosticDerive` and `LintDiagnosticDerive` --- .../src/diagnostics/diagnostic.rs | 100 +++--------------- .../src/diagnostics/diagnostic_builder.rs | 49 +++++++++ 2 files changed, 66 insertions(+), 83 deletions(-) diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic.rs b/compiler/rustc_macros/src/diagnostics/diagnostic.rs index 185d07049669..7e784e3464e9 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -4,12 +4,10 @@ use std::cell::RefCell; use proc_macro2::TokenStream; use quote::quote; -use syn::spanned::Spanned; use synstructure::Structure; use crate::diagnostics::diagnostic_builder::DiagnosticDeriveKind; -use crate::diagnostics::error::{DiagnosticDeriveError, span_err}; -use crate::diagnostics::utils::SetOnce; +use crate::diagnostics::error::DiagnosticDeriveError; /// The central struct for constructing the `into_diag` method from an annotated struct. pub(crate) struct DiagnosticDerive<'a> { @@ -29,36 +27,16 @@ impl<'a> DiagnosticDerive<'a> { let preamble = builder.preamble(variant); let body = builder.body(variant); - let init = match builder.slug.value_ref() { - None => { - span_err(builder.span, "diagnostic slug not specified") - .help( - "specify the slug as the first argument to the `#[diag(...)]` \ - attribute, such as `#[diag(hir_analysis_example_error)]`", - ) - .emit(); - return DiagnosticDeriveError::ErrorHandled.to_compile_error(); - } - Some(slug) - if let Some(Mismatch { slug_name, crate_name, slug_prefix }) = - Mismatch::check(slug) => - { - span_err(slug.span().unwrap(), "diagnostic slug and crate name do not match") - .note(format!("slug is `{slug_name}` but the crate name is `{crate_name}`")) - .help(format!("expected a slug starting with `{slug_prefix}_...`")) - .emit(); - return DiagnosticDeriveError::ErrorHandled.to_compile_error(); - } - Some(slug) => { - slugs.borrow_mut().push(slug.clone()); - quote! { - let mut diag = rustc_errors::Diag::new( - dcx, - level, - crate::fluent_generated::#slug - ); - } - } + let Some(slug) = builder.primary_message() else { + return DiagnosticDeriveError::ErrorHandled.to_compile_error(); + }; + slugs.borrow_mut().push(slug.clone()); + let init = quote! { + let mut diag = rustc_errors::Diag::new( + dcx, + level, + crate::fluent_generated::#slug + ); }; let formatting_init = &builder.formatting_init; @@ -113,32 +91,12 @@ impl<'a> LintDiagnosticDerive<'a> { let preamble = builder.preamble(variant); let body = builder.body(variant); - let primary_message = match builder.slug.value_ref() { - None => { - span_err(builder.span, "diagnostic slug not specified") - .help( - "specify the slug as the first argument to the attribute, such as \ - `#[diag(compiletest_example)]`", - ) - .emit(); - DiagnosticDeriveError::ErrorHandled.to_compile_error() - } - Some(slug) - if let Some(Mismatch { slug_name, crate_name, slug_prefix }) = - Mismatch::check(slug) => - { - span_err(slug.span().unwrap(), "diagnostic slug and crate name do not match") - .note(format!("slug is `{slug_name}` but the crate name is `{crate_name}`")) - .help(format!("expected a slug starting with `{slug_prefix}_...`")) - .emit(); - DiagnosticDeriveError::ErrorHandled.to_compile_error() - } - Some(slug) => { - slugs.borrow_mut().push(slug.clone()); - quote! { - diag.primary_message(crate::fluent_generated::#slug); - } - } + let Some(slug) = builder.primary_message() else { + return DiagnosticDeriveError::ErrorHandled.to_compile_error(); + }; + slugs.borrow_mut().push(slug.clone()); + let primary_message = quote! { + diag.primary_message(crate::fluent_generated::#slug); }; let formatting_init = &builder.formatting_init; @@ -172,30 +130,6 @@ impl<'a> LintDiagnosticDerive<'a> { } } -struct Mismatch { - slug_name: String, - crate_name: String, - slug_prefix: String, -} - -impl Mismatch { - /// Checks whether the slug starts with the crate name it's in. - fn check(slug: &syn::Path) -> Option { - // If this is missing we're probably in a test, so bail. - let crate_name = std::env::var("CARGO_CRATE_NAME").ok()?; - - // If we're not in a "rustc_" crate, bail. - let Some(("rustc", slug_prefix)) = crate_name.split_once('_') else { return None }; - - let slug_name = slug.segments.first()?.ident.to_string(); - if !slug_name.starts_with(slug_prefix) { - Some(Mismatch { slug_name, slug_prefix: slug_prefix.to_string(), crate_name }) - } else { - None - } - } -} - /// Generates a `#[test]` that verifies that all referenced variables /// exist on this structure. fn generate_test(slug: &syn::Path, structure: &Structure<'_>) -> TokenStream { diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index 1055f27c1e48..cbc70b55d7ee 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -110,6 +110,31 @@ impl DiagnosticDeriveKind { } impl DiagnosticDeriveVariantBuilder { + pub(crate) fn primary_message(&self) -> Option<&Path> { + match self.slug.value_ref() { + None => { + span_err(self.span, "diagnostic slug not specified") + .help( + "specify the slug as the first argument to the `#[diag(...)]` \ + attribute, such as `#[diag(hir_analysis_example_error)]`", + ) + .emit(); + None + } + Some(slug) + if let Some(Mismatch { slug_name, crate_name, slug_prefix }) = + Mismatch::check(slug) => + { + span_err(slug.span().unwrap(), "diagnostic slug and crate name do not match") + .note(format!("slug is `{slug_name}` but the crate name is `{crate_name}`")) + .help(format!("expected a slug starting with `{slug_prefix}_...`")) + .emit(); + None + } + Some(slug) => Some(slug), + } + } + /// Generates calls to `code` and similar functions based on the attributes on the type or /// variant. pub(crate) fn preamble(&mut self, variant: &VariantInfo<'_>) -> TokenStream { @@ -504,3 +529,27 @@ impl DiagnosticDeriveVariantBuilder { } } } + +struct Mismatch { + slug_name: String, + crate_name: String, + slug_prefix: String, +} + +impl Mismatch { + /// Checks whether the slug starts with the crate name it's in. + fn check(slug: &syn::Path) -> Option { + // If this is missing we're probably in a test, so bail. + let crate_name = std::env::var("CARGO_CRATE_NAME").ok()?; + + // If we're not in a "rustc_" crate, bail. + let Some(("rustc", slug_prefix)) = crate_name.split_once('_') else { return None }; + + let slug_name = slug.segments.first()?.ident.to_string(); + if slug_name.starts_with(slug_prefix) { + return None; + } + + Some(Mismatch { slug_name, slug_prefix: slug_prefix.to_string(), crate_name }) + } +} From 7ec4a8e798cc37bdf4c9cac1c4a481f6c1d22a0d Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 18 Jan 2026 22:36:39 +0100 Subject: [PATCH 117/146] Update uitests --- tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr index 90ad21ef08f9..77c48aceca8e 100644 --- a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr +++ b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr @@ -384,7 +384,7 @@ error: derive(Diagnostic): diagnostic slug not specified LL | #[lint(no_crate_example, code = E0123)] | ^ | - = help: specify the slug as the first argument to the attribute, such as `#[diag(compiletest_example)]` + = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: derive(Diagnostic): attribute specified multiple times --> $DIR/diagnostic-derive.rs:613:53 From e668836c929e1a30b0c53583567e7c6cf42fe4da Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 18 Jan 2026 22:40:55 +0100 Subject: [PATCH 118/146] Fix capitalization of error messages --- compiler/rustc_attr_parsing/messages.ftl | 2 +- compiler/rustc_const_eval/messages.ftl | 12 ++++++------ compiler/rustc_lint/messages.ftl | 2 +- compiler/rustc_monomorphize/messages.ftl | 2 +- compiler/rustc_passes/messages.ftl | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_attr_parsing/messages.ftl b/compiler/rustc_attr_parsing/messages.ftl index 4b4358ab0a9c..3e4c1a9dfad8 100644 --- a/compiler/rustc_attr_parsing/messages.ftl +++ b/compiler/rustc_attr_parsing/messages.ftl @@ -230,7 +230,7 @@ attr_parsing_unstable_cfg_target_compact = compact `cfg(target(..))` is experimental and subject to change attr_parsing_unstable_feature_bound_incompatible_stability = item annotated with `#[unstable_feature_bound]` should not be stable - .help = If this item is meant to be stable, do not use any functions annotated with `#[unstable_feature_bound]`. Otherwise, mark this item as unstable with `#[unstable]` + .help = if this item is meant to be stable, do not use any functions annotated with `#[unstable_feature_bound]`. Otherwise, mark this item as unstable with `#[unstable]` attr_parsing_unsupported_instruction_set = target `{$current_target}` does not support `#[instruction_set({$instruction_set}::*)]` diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index 38ab46a7bb5b..4aa0a0b2a96f 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -140,9 +140,9 @@ const_eval_incompatible_return_types = const_eval_interior_mutable_borrow_escaping = interior mutable shared borrows of temporaries that have their lifetime extended until the end of the program are not allowed .label = this borrow of an interior mutable value refers to such a temporary - .note = Temporaries in constants and statics can have their lifetime extended until the end of the program - .note2 = To avoid accidentally creating global mutable state, such temporaries must be immutable - .help = If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + .note = temporaries in constants and statics can have their lifetime extended until the end of the program + .note2 = to avoid accidentally creating global mutable state, such temporaries must be immutable + .help = if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` const_eval_intern_kind = {$kind -> [static] static @@ -225,9 +225,9 @@ const_eval_modified_global = const_eval_mutable_borrow_escaping = mutable borrows of temporaries that have their lifetime extended until the end of the program are not allowed .label = this mutable borrow refers to such a temporary - .note = Temporaries in constants and statics can have their lifetime extended until the end of the program - .note2 = To avoid accidentally creating global mutable state, such temporaries must be immutable - .help = If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + .note = temporaries in constants and statics can have their lifetime extended until the end of the program + .note2 = to avoid accidentally creating global mutable state, such temporaries must be immutable + .help = if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` const_eval_mutable_ptr_in_final = encountered mutable pointer in final value of {const_eval_intern_kind} diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index f5b882494863..e38130aa9a29 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -542,7 +542,7 @@ lint_invalid_style = {$is_used_as_inner -> [false] crate-level attribute should be an inner attribute: add an exclamation mark: `#![{$name}]` *[other] the `#![{$name}]` attribute can only be used at the crate root } - .note = This attribute does not have an `!`, which means it is applied to this {$target} + .note = this attribute does not have an `!`, which means it is applied to this {$target} lint_invalid_target = `#[{$name}]` attribute cannot be used on {$target} .warn = {-lint_previously_accepted} diff --git a/compiler/rustc_monomorphize/messages.ftl b/compiler/rustc_monomorphize/messages.ftl index 09500ba73359..9c791208c093 100644 --- a/compiler/rustc_monomorphize/messages.ftl +++ b/compiler/rustc_monomorphize/messages.ftl @@ -62,7 +62,7 @@ monomorphize_encountered_error_while_instantiating_global_asm = monomorphize_large_assignments = moving {$size} bytes .label = value moved from here - .note = The current maximum size is {$limit}, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + .note = the current maximum size is {$limit}, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` monomorphize_no_optimized_mir = missing optimized MIR for `{$instance}` in the crate `{$crate_name}` diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 51c439b4243c..395d940ddae6 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -376,7 +376,7 @@ passes_no_main_function = } .consider_adding_main_to_file = consider adding a `main` function to `{$filename}` .consider_adding_main_at_crate = consider adding a `main` function at the crate level - .teach_note = If you don't know the basics of Rust, you can go look to the Rust Book to get started: https://doc.rust-lang.org/book/ + .teach_note = if you don't know the basics of Rust, you can go look to the Rust Book to get started: https://doc.rust-lang.org/book/ .non_function_main = non-function item at `crate::main` is found passes_non_exhaustive_with_default_field_values = From f5a1fc75ad10186b13ad34a65e176760b7306630 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 18 Jan 2026 22:41:00 +0100 Subject: [PATCH 119/146] Update uitests --- .../ui/attributes/crate-only-as-outer.stderr | 2 +- tests/ui/attributes/malformed-attrs.stderr | 2 +- tests/ui/attributes/malformed-no-std.stderr | 4 +- .../consts/const-mut-refs/issue-76510.stderr | 6 +- .../const-mut-refs/mut_ref_in_final.stderr | 36 +++++------ .../const-promoted-opaque.atomic.stderr | 6 +- .../issue-17718-const-bad-values.stderr | 6 +- .../ui/consts/issue-17718-const-borrow.stderr | 18 +++--- tests/ui/consts/partial_qualif.stderr | 6 +- tests/ui/consts/qualif_overwrite.stderr | 6 +- tests/ui/consts/qualif_overwrite_2.stderr | 6 +- tests/ui/consts/refs-to-cell-in-final.stderr | 18 +++--- .../consts/write_to_static_via_mut_ref.stderr | 6 +- tests/ui/error-codes/E0017.stderr | 12 ++-- tests/ui/error-codes/E0492.stderr | 12 ++-- .../issue-43106-gating-of-builtin-attrs.rs | 60 +++++++++---------- ...issue-43106-gating-of-builtin-attrs.stderr | 60 +++++++++---------- tests/ui/issues/issue-46604.stderr | 6 +- .../copy_into_box_rc_arc.stderr | 4 +- .../large_assignments/copy_into_fn.stderr | 6 +- .../lint/large_assignments/inline_mir.stderr | 4 +- .../large_future.attribute.stderr | 4 +- .../large_future.option.stderr | 4 +- .../move_into_box_rc_arc.stderr | 2 +- .../large_assignments/move_into_fn.stderr | 4 +- .../concat-in-crate-name-issue-137687.stderr | 2 +- .../unused/unused-attr-macro-rules.stderr | 2 +- .../statics/check-immutable-mut-slices.stderr | 6 +- ...eature_bound_incompatible_stability.stderr | 2 +- 29 files changed, 156 insertions(+), 156 deletions(-) diff --git a/tests/ui/attributes/crate-only-as-outer.stderr b/tests/ui/attributes/crate-only-as-outer.stderr index 270f02af9873..c1787a73d290 100644 --- a/tests/ui/attributes/crate-only-as-outer.stderr +++ b/tests/ui/attributes/crate-only-as-outer.stderr @@ -4,7 +4,7 @@ error: crate-level attribute should be an inner attribute: add an exclamation ma LL | #[crate_name = "owo"] | ^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this function +note: this attribute does not have an `!`, which means it is applied to this function --> $DIR/crate-only-as-outer.rs:5:1 | LL | fn main() {} diff --git a/tests/ui/attributes/malformed-attrs.stderr b/tests/ui/attributes/malformed-attrs.stderr index 04f51f54b2cd..3d51731df792 100644 --- a/tests/ui/attributes/malformed-attrs.stderr +++ b/tests/ui/attributes/malformed-attrs.stderr @@ -771,7 +771,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[crate_name] | ^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this function +note: this attribute does not have an `!`, which means it is applied to this function --> $DIR/malformed-attrs.rs:116:1 | LL | / fn test() { diff --git a/tests/ui/attributes/malformed-no-std.stderr b/tests/ui/attributes/malformed-no-std.stderr index 89d7ee410d70..e994e28e030f 100644 --- a/tests/ui/attributes/malformed-no-std.stderr +++ b/tests/ui/attributes/malformed-no-std.stderr @@ -58,7 +58,7 @@ error: crate-level attribute should be an inner attribute: add an exclamation ma LL | #[no_std] | ^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this extern crate +note: this attribute does not have an `!`, which means it is applied to this extern crate --> $DIR/malformed-no-std.rs:26:1 | LL | extern crate core; @@ -75,7 +75,7 @@ error: crate-level attribute should be an inner attribute: add an exclamation ma LL | #[no_core] | ^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this extern crate +note: this attribute does not have an `!`, which means it is applied to this extern crate --> $DIR/malformed-no-std.rs:26:1 | LL | extern crate core; diff --git a/tests/ui/consts/const-mut-refs/issue-76510.stderr b/tests/ui/consts/const-mut-refs/issue-76510.stderr index 3a6c95141e52..82c9d523e738 100644 --- a/tests/ui/consts/const-mut-refs/issue-76510.stderr +++ b/tests/ui/consts/const-mut-refs/issue-76510.stderr @@ -4,9 +4,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | const S: &'static mut str = &mut " hello "; | ^^^^^^^^^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 1 previous error diff --git a/tests/ui/consts/const-mut-refs/mut_ref_in_final.stderr b/tests/ui/consts/const-mut-refs/mut_ref_in_final.stderr index da6f2a28d5a8..8f54b4eda227 100644 --- a/tests/ui/consts/const-mut-refs/mut_ref_in_final.stderr +++ b/tests/ui/consts/const-mut-refs/mut_ref_in_final.stderr @@ -4,9 +4,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | const B: *mut i32 = &mut 4; | ^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0764]: mutable borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/mut_ref_in_final.rs:21:35 @@ -14,9 +14,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | const B3: Option<&mut i32> = Some(&mut 42); | ^^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0716]: temporary value dropped while borrowed --> $DIR/mut_ref_in_final.rs:24:42 @@ -86,9 +86,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | static RAW_MUT_CAST_S: SyncPtr = SyncPtr { x : &mut 42 as *mut _ as *const _ }; | ^^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0764]: mutable borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/mut_ref_in_final.rs:73:54 @@ -96,9 +96,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | static RAW_MUT_COERCE_S: SyncPtr = SyncPtr { x: &mut 0 }; | ^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0764]: mutable borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/mut_ref_in_final.rs:75:52 @@ -106,9 +106,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | const RAW_MUT_CAST_C: SyncPtr = SyncPtr { x : &mut 42 as *mut _ as *const _ }; | ^^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0764]: mutable borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/mut_ref_in_final.rs:77:53 @@ -116,9 +116,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | const RAW_MUT_COERCE_C: SyncPtr = SyncPtr { x: &mut 0 }; | ^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0080]: constructing invalid value at ..0: encountered a dangling reference (0x2a[noalloc] has no provenance) --> $DIR/mut_ref_in_final.rs:86:5 diff --git a/tests/ui/consts/const-promoted-opaque.atomic.stderr b/tests/ui/consts/const-promoted-opaque.atomic.stderr index 64cc7b3a3292..ac31992d0631 100644 --- a/tests/ui/consts/const-promoted-opaque.atomic.stderr +++ b/tests/ui/consts/const-promoted-opaque.atomic.stderr @@ -13,9 +13,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | const BAZ: &Foo = &FOO; | ^^^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0716]: temporary value dropped while borrowed --> $DIR/const-promoted-opaque.rs:40:26 diff --git a/tests/ui/consts/issue-17718-const-bad-values.stderr b/tests/ui/consts/issue-17718-const-bad-values.stderr index 11e11adcb5ae..eebfa5d6ea40 100644 --- a/tests/ui/consts/issue-17718-const-bad-values.stderr +++ b/tests/ui/consts/issue-17718-const-bad-values.stderr @@ -4,9 +4,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | const C1: &'static mut [usize] = &mut []; | ^^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 1 previous error diff --git a/tests/ui/consts/issue-17718-const-borrow.stderr b/tests/ui/consts/issue-17718-const-borrow.stderr index 420a2c378a25..b801498c2028 100644 --- a/tests/ui/consts/issue-17718-const-borrow.stderr +++ b/tests/ui/consts/issue-17718-const-borrow.stderr @@ -4,9 +4,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | const B: &'static UnsafeCell = &A; | ^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0492]: interior mutable shared borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/issue-17718-const-borrow.rs:9:39 @@ -14,9 +14,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | const E: &'static UnsafeCell = &D.a; | ^^^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0492]: interior mutable shared borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/issue-17718-const-borrow.rs:11:23 @@ -24,9 +24,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | const F: &'static C = &D; | ^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 3 previous errors diff --git a/tests/ui/consts/partial_qualif.stderr b/tests/ui/consts/partial_qualif.stderr index b7632eb868ac..f69fa1c46c01 100644 --- a/tests/ui/consts/partial_qualif.stderr +++ b/tests/ui/consts/partial_qualif.stderr @@ -4,9 +4,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | &{a} | ^^^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 1 previous error diff --git a/tests/ui/consts/qualif_overwrite.stderr b/tests/ui/consts/qualif_overwrite.stderr index 4aaaa4b2ca90..1dc2bf7f1231 100644 --- a/tests/ui/consts/qualif_overwrite.stderr +++ b/tests/ui/consts/qualif_overwrite.stderr @@ -4,9 +4,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | &{a} | ^^^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 1 previous error diff --git a/tests/ui/consts/qualif_overwrite_2.stderr b/tests/ui/consts/qualif_overwrite_2.stderr index bc1681418765..fb8ac601c67a 100644 --- a/tests/ui/consts/qualif_overwrite_2.stderr +++ b/tests/ui/consts/qualif_overwrite_2.stderr @@ -4,9 +4,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | &{a.0} | ^^^^^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 1 previous error diff --git a/tests/ui/consts/refs-to-cell-in-final.stderr b/tests/ui/consts/refs-to-cell-in-final.stderr index ac866dbe7210..e30b5aa24e76 100644 --- a/tests/ui/consts/refs-to-cell-in-final.stderr +++ b/tests/ui/consts/refs-to-cell-in-final.stderr @@ -4,9 +4,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | static RAW_SYNC_S: SyncPtr> = SyncPtr { x: &Cell::new(42) }; | ^^^^^^^^^^^^^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0492]: interior mutable shared borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/refs-to-cell-in-final.rs:15:53 @@ -14,9 +14,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | const RAW_SYNC_C: SyncPtr> = SyncPtr { x: &Cell::new(42) }; | ^^^^^^^^^^^^^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0492]: interior mutable shared borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/refs-to-cell-in-final.rs:41:57 @@ -31,9 +31,9 @@ LL | | x LL | | }; | |_^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 3 previous errors diff --git a/tests/ui/consts/write_to_static_via_mut_ref.stderr b/tests/ui/consts/write_to_static_via_mut_ref.stderr index ce44047f1550..be1f7178998a 100644 --- a/tests/ui/consts/write_to_static_via_mut_ref.stderr +++ b/tests/ui/consts/write_to_static_via_mut_ref.stderr @@ -4,9 +4,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | static OH_NO: &mut i32 = &mut 42; | ^^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0594]: cannot assign to `*OH_NO`, as `OH_NO` is an immutable static item --> $DIR/write_to_static_via_mut_ref.rs:4:5 diff --git a/tests/ui/error-codes/E0017.stderr b/tests/ui/error-codes/E0017.stderr index fcc57b9e5c3c..70186165d862 100644 --- a/tests/ui/error-codes/E0017.stderr +++ b/tests/ui/error-codes/E0017.stderr @@ -19,9 +19,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | const CR: &'static mut i32 = &mut C; | ^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0596]: cannot borrow immutable static item `X` as mutable --> $DIR/E0017.rs:11:39 @@ -52,9 +52,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | static CONST_REF: &'static mut i32 = &mut C; | ^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 3 previous errors; 2 warnings emitted diff --git a/tests/ui/error-codes/E0492.stderr b/tests/ui/error-codes/E0492.stderr index 43a3a872e4e7..a5057e8baedb 100644 --- a/tests/ui/error-codes/E0492.stderr +++ b/tests/ui/error-codes/E0492.stderr @@ -4,9 +4,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | const B: &'static AtomicUsize = &A; | ^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0492]: interior mutable shared borrows of temporaries that have their lifetime extended until the end of the program are not allowed --> $DIR/E0492.rs:5:34 @@ -14,9 +14,9 @@ error[E0492]: interior mutable shared borrows of temporaries that have their lif LL | static C: &'static AtomicUsize = &A; | ^^ this borrow of an interior mutable value refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 2 previous errors diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs index 3e3235e658f6..ce2f9a4e6eeb 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs @@ -525,25 +525,25 @@ mod macro_escape { #[no_std] //~^ WARN crate-level attribute should be an inner attribute mod no_std { - //~^ NOTE This attribute does not have an `!`, which means it is applied to this module + //~^ NOTE this attribute does not have an `!`, which means it is applied to this module mod inner { #![no_std] } //~^ WARN the `#![no_std]` attribute can only be used at the crate root #[no_std] fn f() { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this function + //~| NOTE this attribute does not have an `!`, which means it is applied to this function #[no_std] struct S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this struct + //~| NOTE this attribute does not have an `!`, which means it is applied to this struct #[no_std] type T = S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this type alias + //~| NOTE this attribute does not have an `!`, which means it is applied to this type alias #[no_std] impl S { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this implementation block + //~| NOTE this attribute does not have an `!`, which means it is applied to this implementation block } // At time of authorship, #[proc_macro_derive = "2500"] signals error @@ -786,25 +786,25 @@ mod must_use { #[windows_subsystem = "windows"] //~^ WARN crate-level attribute should be an inner attribute mod windows_subsystem { - //~^ NOTE This attribute does not have an `!`, which means it is applied to this module + //~^ NOTE this attribute does not have an `!`, which means it is applied to this module mod inner { #![windows_subsystem="windows"] } //~^ WARN the `#![windows_subsystem]` attribute can only be used at the crate root #[windows_subsystem = "windows"] fn f() { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this function + //~| NOTE this attribute does not have an `!`, which means it is applied to this function #[windows_subsystem = "windows"] struct S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this struct + //~| NOTE this attribute does not have an `!`, which means it is applied to this struct #[windows_subsystem = "windows"] type T = S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this type alias + //~| NOTE this attribute does not have an `!`, which means it is applied to this type alias #[windows_subsystem = "windows"] impl S { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this implementation block + //~| NOTE this attribute does not have an `!`, which means it is applied to this implementation block } // BROKEN USES OF CRATE-LEVEL BUILT-IN ATTRIBUTES @@ -812,25 +812,25 @@ mod windows_subsystem { #[crate_name = "0900"] //~^ WARN crate-level attribute should be an inner attribute mod crate_name { -//~^ NOTE This attribute does not have an `!`, which means it is applied to this module +//~^ NOTE this attribute does not have an `!`, which means it is applied to this module mod inner { #![crate_name="0900"] } //~^ WARN the `#![crate_name]` attribute can only be used at the crate root #[crate_name = "0900"] fn f() { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this function + //~| NOTE this attribute does not have an `!`, which means it is applied to this function #[crate_name = "0900"] struct S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this struct + //~| NOTE this attribute does not have an `!`, which means it is applied to this struct #[crate_name = "0900"] type T = S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this type alias + //~| NOTE this attribute does not have an `!`, which means it is applied to this type alias #[crate_name = "0900"] impl S { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this implementation block + //~| NOTE this attribute does not have an `!`, which means it is applied to this implementation block } #[crate_type = "0800"] @@ -885,25 +885,25 @@ mod feature { #[no_main] //~^ WARN crate-level attribute should be an inner attribute mod no_main_1 { - //~^ NOTE: This attribute does not have an `!`, which means it is applied to this module + //~^ NOTE: this attribute does not have an `!`, which means it is applied to this module mod inner { #![no_main] } //~^ WARN the `#![no_main]` attribute can only be used at the crate root #[no_main] fn f() { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this function + //~| NOTE this attribute does not have an `!`, which means it is applied to this function #[no_main] struct S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this struct + //~| NOTE this attribute does not have an `!`, which means it is applied to this struct #[no_main] type T = S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this type alias + //~| NOTE this attribute does not have an `!`, which means it is applied to this type alias #[no_main] impl S { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this implementation + //~| NOTE this attribute does not have an `!`, which means it is applied to this implementation } #[no_builtins] @@ -933,49 +933,49 @@ mod no_builtins { #[recursion_limit="0200"] //~^ WARN crate-level attribute should be an inner attribute mod recursion_limit { - //~^ NOTE This attribute does not have an `!`, which means it is applied to this module + //~^ NOTE this attribute does not have an `!`, which means it is applied to this module mod inner { #![recursion_limit="0200"] } //~^ WARN the `#![recursion_limit]` attribute can only be used at the crate root #[recursion_limit="0200"] fn f() { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this function + //~| NOTE this attribute does not have an `!`, which means it is applied to this function #[recursion_limit="0200"] struct S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this struct + //~| NOTE this attribute does not have an `!`, which means it is applied to this struct #[recursion_limit="0200"] type T = S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this type alias + //~| NOTE this attribute does not have an `!`, which means it is applied to this type alias #[recursion_limit="0200"] impl S { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this implementation block + //~| NOTE this attribute does not have an `!`, which means it is applied to this implementation block } #[type_length_limit="0100"] //~^ WARN crate-level attribute should be an inner attribute mod type_length_limit { - //~^ NOTE This attribute does not have an `!`, which means it is applied to this module + //~^ NOTE this attribute does not have an `!`, which means it is applied to this module mod inner { #![type_length_limit="0100"] } //~^ WARN the `#![type_length_limit]` attribute can only be used at the crate root #[type_length_limit="0100"] fn f() { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this function + //~| NOTE this attribute does not have an `!`, which means it is applied to this function #[type_length_limit="0100"] struct S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this struct + //~| NOTE this attribute does not have an `!`, which means it is applied to this struct #[type_length_limit="0100"] type T = S; //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this type alias + //~| NOTE this attribute does not have an `!`, which means it is applied to this type alias #[type_length_limit="0100"] impl S { } //~^ WARN crate-level attribute should be an inner attribute - //~| NOTE This attribute does not have an `!`, which means it is applied to this implementation block + //~| NOTE this attribute does not have an `!`, which means it is applied to this implementation block } fn main() {} diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr index d89aec222be8..cbb80ccd753c 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr @@ -935,7 +935,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_std] | ^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this module +note: this attribute does not have an `!`, which means it is applied to this module --> $DIR/issue-43106-gating-of-builtin-attrs.rs:527:1 | LL | / mod no_std { @@ -957,7 +957,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_std] fn f() { } | ^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this function +note: this attribute does not have an `!`, which means it is applied to this function --> $DIR/issue-43106-gating-of-builtin-attrs.rs:532:15 | LL | #[no_std] fn f() { } @@ -969,7 +969,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_std] struct S; | ^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this struct +note: this attribute does not have an `!`, which means it is applied to this struct --> $DIR/issue-43106-gating-of-builtin-attrs.rs:536:15 | LL | #[no_std] struct S; @@ -981,7 +981,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_std] type T = S; | ^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this type alias +note: this attribute does not have an `!`, which means it is applied to this type alias --> $DIR/issue-43106-gating-of-builtin-attrs.rs:540:15 | LL | #[no_std] type T = S; @@ -993,7 +993,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_std] impl S { } | ^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this implementation block +note: this attribute does not have an `!`, which means it is applied to this implementation block --> $DIR/issue-43106-gating-of-builtin-attrs.rs:544:15 | LL | #[no_std] impl S { } @@ -1212,7 +1212,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[windows_subsystem = "windows"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this module +note: this attribute does not have an `!`, which means it is applied to this module --> $DIR/issue-43106-gating-of-builtin-attrs.rs:788:1 | LL | / mod windows_subsystem { @@ -1234,7 +1234,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[windows_subsystem = "windows"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this function +note: this attribute does not have an `!`, which means it is applied to this function --> $DIR/issue-43106-gating-of-builtin-attrs.rs:793:38 | LL | #[windows_subsystem = "windows"] fn f() { } @@ -1246,7 +1246,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[windows_subsystem = "windows"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this struct +note: this attribute does not have an `!`, which means it is applied to this struct --> $DIR/issue-43106-gating-of-builtin-attrs.rs:797:38 | LL | #[windows_subsystem = "windows"] struct S; @@ -1258,7 +1258,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[windows_subsystem = "windows"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this type alias +note: this attribute does not have an `!`, which means it is applied to this type alias --> $DIR/issue-43106-gating-of-builtin-attrs.rs:801:38 | LL | #[windows_subsystem = "windows"] type T = S; @@ -1270,7 +1270,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[windows_subsystem = "windows"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this implementation block +note: this attribute does not have an `!`, which means it is applied to this implementation block --> $DIR/issue-43106-gating-of-builtin-attrs.rs:805:38 | LL | #[windows_subsystem = "windows"] impl S { } @@ -1282,7 +1282,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[crate_name = "0900"] | ^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this module +note: this attribute does not have an `!`, which means it is applied to this module --> $DIR/issue-43106-gating-of-builtin-attrs.rs:814:1 | LL | / mod crate_name { @@ -1304,7 +1304,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[crate_name = "0900"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this function +note: this attribute does not have an `!`, which means it is applied to this function --> $DIR/issue-43106-gating-of-builtin-attrs.rs:819:28 | LL | #[crate_name = "0900"] fn f() { } @@ -1316,7 +1316,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[crate_name = "0900"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this struct +note: this attribute does not have an `!`, which means it is applied to this struct --> $DIR/issue-43106-gating-of-builtin-attrs.rs:823:28 | LL | #[crate_name = "0900"] struct S; @@ -1328,7 +1328,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[crate_name = "0900"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this type alias +note: this attribute does not have an `!`, which means it is applied to this type alias --> $DIR/issue-43106-gating-of-builtin-attrs.rs:827:28 | LL | #[crate_name = "0900"] type T = S; @@ -1340,7 +1340,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[crate_name = "0900"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this implementation block +note: this attribute does not have an `!`, which means it is applied to this implementation block --> $DIR/issue-43106-gating-of-builtin-attrs.rs:831:28 | LL | #[crate_name = "0900"] impl S { } @@ -1352,7 +1352,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_main] | ^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this module +note: this attribute does not have an `!`, which means it is applied to this module --> $DIR/issue-43106-gating-of-builtin-attrs.rs:887:1 | LL | / mod no_main_1 { @@ -1374,7 +1374,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_main] fn f() { } | ^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this function +note: this attribute does not have an `!`, which means it is applied to this function --> $DIR/issue-43106-gating-of-builtin-attrs.rs:892:16 | LL | #[no_main] fn f() { } @@ -1386,7 +1386,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_main] struct S; | ^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this struct +note: this attribute does not have an `!`, which means it is applied to this struct --> $DIR/issue-43106-gating-of-builtin-attrs.rs:896:16 | LL | #[no_main] struct S; @@ -1398,7 +1398,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_main] type T = S; | ^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this type alias +note: this attribute does not have an `!`, which means it is applied to this type alias --> $DIR/issue-43106-gating-of-builtin-attrs.rs:900:16 | LL | #[no_main] type T = S; @@ -1410,7 +1410,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[no_main] impl S { } | ^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this implementation block +note: this attribute does not have an `!`, which means it is applied to this implementation block --> $DIR/issue-43106-gating-of-builtin-attrs.rs:904:16 | LL | #[no_main] impl S { } @@ -1422,7 +1422,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[recursion_limit="0200"] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this module +note: this attribute does not have an `!`, which means it is applied to this module --> $DIR/issue-43106-gating-of-builtin-attrs.rs:935:1 | LL | / mod recursion_limit { @@ -1444,7 +1444,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[recursion_limit="0200"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this function +note: this attribute does not have an `!`, which means it is applied to this function --> $DIR/issue-43106-gating-of-builtin-attrs.rs:940:31 | LL | #[recursion_limit="0200"] fn f() { } @@ -1456,7 +1456,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[recursion_limit="0200"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this struct +note: this attribute does not have an `!`, which means it is applied to this struct --> $DIR/issue-43106-gating-of-builtin-attrs.rs:944:31 | LL | #[recursion_limit="0200"] struct S; @@ -1468,7 +1468,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[recursion_limit="0200"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this type alias +note: this attribute does not have an `!`, which means it is applied to this type alias --> $DIR/issue-43106-gating-of-builtin-attrs.rs:948:31 | LL | #[recursion_limit="0200"] type T = S; @@ -1480,7 +1480,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[recursion_limit="0200"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this implementation block +note: this attribute does not have an `!`, which means it is applied to this implementation block --> $DIR/issue-43106-gating-of-builtin-attrs.rs:952:31 | LL | #[recursion_limit="0200"] impl S { } @@ -1492,7 +1492,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[type_length_limit="0100"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this module +note: this attribute does not have an `!`, which means it is applied to this module --> $DIR/issue-43106-gating-of-builtin-attrs.rs:959:1 | LL | / mod type_length_limit { @@ -1514,7 +1514,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[type_length_limit="0100"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this function +note: this attribute does not have an `!`, which means it is applied to this function --> $DIR/issue-43106-gating-of-builtin-attrs.rs:964:33 | LL | #[type_length_limit="0100"] fn f() { } @@ -1526,7 +1526,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[type_length_limit="0100"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this struct +note: this attribute does not have an `!`, which means it is applied to this struct --> $DIR/issue-43106-gating-of-builtin-attrs.rs:968:33 | LL | #[type_length_limit="0100"] struct S; @@ -1538,7 +1538,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[type_length_limit="0100"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this type alias +note: this attribute does not have an `!`, which means it is applied to this type alias --> $DIR/issue-43106-gating-of-builtin-attrs.rs:972:33 | LL | #[type_length_limit="0100"] type T = S; @@ -1550,7 +1550,7 @@ warning: crate-level attribute should be an inner attribute: add an exclamation LL | #[type_length_limit="0100"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this implementation block +note: this attribute does not have an `!`, which means it is applied to this implementation block --> $DIR/issue-43106-gating-of-builtin-attrs.rs:976:33 | LL | #[type_length_limit="0100"] impl S { } diff --git a/tests/ui/issues/issue-46604.stderr b/tests/ui/issues/issue-46604.stderr index abe3ad476c60..21abc498de12 100644 --- a/tests/ui/issues/issue-46604.stderr +++ b/tests/ui/issues/issue-46604.stderr @@ -4,9 +4,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | static buf: &mut [u8] = &mut [1u8,2,3,4,5,7]; | ^^^^^^^^^^^^^^^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error[E0594]: cannot assign to `buf[_]`, as `buf` is an immutable static item --> $DIR/issue-46604.rs:6:5 diff --git a/tests/ui/lint/large_assignments/copy_into_box_rc_arc.stderr b/tests/ui/lint/large_assignments/copy_into_box_rc_arc.stderr index 6e42328a1113..b8e7abf4807c 100644 --- a/tests/ui/lint/large_assignments/copy_into_box_rc_arc.stderr +++ b/tests/ui/lint/large_assignments/copy_into_box_rc_arc.stderr @@ -4,7 +4,7 @@ error: moving 9999 bytes LL | let _ = NotBox::new(data); | ^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` note: the lint level is defined here --> $DIR/copy_into_box_rc_arc.rs:1:9 | @@ -19,7 +19,7 @@ LL | | data, LL | | } | |_________^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` error: aborting due to 2 previous errors diff --git a/tests/ui/lint/large_assignments/copy_into_fn.stderr b/tests/ui/lint/large_assignments/copy_into_fn.stderr index f05fc33e17e1..a4c4800266af 100644 --- a/tests/ui/lint/large_assignments/copy_into_fn.stderr +++ b/tests/ui/lint/large_assignments/copy_into_fn.stderr @@ -4,7 +4,7 @@ error: moving 9999 bytes LL | one_arg(Data([0; 9999])); | ^^^^^^^^^^^^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` note: the lint level is defined here --> $DIR/copy_into_fn.rs:5:9 | @@ -17,7 +17,7 @@ error: moving 9999 bytes LL | many_args(Data([0; 9999]), true, Data([0; 9999])); | ^^^^^^^^^^^^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` error: moving 9999 bytes --> $DIR/copy_into_fn.rs:17:38 @@ -25,7 +25,7 @@ error: moving 9999 bytes LL | many_args(Data([0; 9999]), true, Data([0; 9999])); | ^^^^^^^^^^^^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` error: aborting due to 3 previous errors diff --git a/tests/ui/lint/large_assignments/inline_mir.stderr b/tests/ui/lint/large_assignments/inline_mir.stderr index 1a5fcb6c8fc1..b8170d8977d2 100644 --- a/tests/ui/lint/large_assignments/inline_mir.stderr +++ b/tests/ui/lint/large_assignments/inline_mir.stderr @@ -4,7 +4,7 @@ error: moving 9999 bytes LL | let cell = std::cell::UnsafeCell::new(data); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` note: the lint level is defined here --> $DIR/inline_mir.rs:2:9 | @@ -17,7 +17,7 @@ error: moving 9999 bytes LL | std::hint::black_box(cell); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` error: aborting due to 2 previous errors diff --git a/tests/ui/lint/large_assignments/large_future.attribute.stderr b/tests/ui/lint/large_assignments/large_future.attribute.stderr index 734b7ff7ba22..1580c31df3c2 100644 --- a/tests/ui/lint/large_assignments/large_future.attribute.stderr +++ b/tests/ui/lint/large_assignments/large_future.attribute.stderr @@ -4,7 +4,7 @@ error: moving 10024 bytes LL | let z = (x, 42); | ^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` note: the lint level is defined here --> $DIR/large_future.rs:1:9 | @@ -17,7 +17,7 @@ error: moving 10024 bytes LL | let a = z.0; | ^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` error: aborting due to 2 previous errors diff --git a/tests/ui/lint/large_assignments/large_future.option.stderr b/tests/ui/lint/large_assignments/large_future.option.stderr index 734b7ff7ba22..1580c31df3c2 100644 --- a/tests/ui/lint/large_assignments/large_future.option.stderr +++ b/tests/ui/lint/large_assignments/large_future.option.stderr @@ -4,7 +4,7 @@ error: moving 10024 bytes LL | let z = (x, 42); | ^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` note: the lint level is defined here --> $DIR/large_future.rs:1:9 | @@ -17,7 +17,7 @@ error: moving 10024 bytes LL | let a = z.0; | ^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` error: aborting due to 2 previous errors diff --git a/tests/ui/lint/large_assignments/move_into_box_rc_arc.stderr b/tests/ui/lint/large_assignments/move_into_box_rc_arc.stderr index a386de5e5e8e..35f30a79ad99 100644 --- a/tests/ui/lint/large_assignments/move_into_box_rc_arc.stderr +++ b/tests/ui/lint/large_assignments/move_into_box_rc_arc.stderr @@ -4,7 +4,7 @@ error: moving 9999 bytes LL | data, | ^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` note: the lint level is defined here --> $DIR/move_into_box_rc_arc.rs:1:9 | diff --git a/tests/ui/lint/large_assignments/move_into_fn.stderr b/tests/ui/lint/large_assignments/move_into_fn.stderr index 19ec6a51d2e7..4f4c710cacef 100644 --- a/tests/ui/lint/large_assignments/move_into_fn.stderr +++ b/tests/ui/lint/large_assignments/move_into_fn.stderr @@ -4,7 +4,7 @@ error: moving 9999 bytes LL | let data = Data([100; 9999]); | ^^^^^^^^^^^^^^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` note: the lint level is defined here --> $DIR/move_into_fn.rs:5:9 | @@ -17,7 +17,7 @@ error: moving 9999 bytes LL | take_data(data); | ^^^^ value moved from here | - = note: The current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` + = note: the current maximum size is 1000, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]` error: aborting due to 2 previous errors diff --git a/tests/ui/lint/unused/concat-in-crate-name-issue-137687.stderr b/tests/ui/lint/unused/concat-in-crate-name-issue-137687.stderr index b06e65af7bc7..5928eb6c58c4 100644 --- a/tests/ui/lint/unused/concat-in-crate-name-issue-137687.stderr +++ b/tests/ui/lint/unused/concat-in-crate-name-issue-137687.stderr @@ -17,7 +17,7 @@ error: crate-level attribute should be an inner attribute: add an exclamation ma LL | #[crate_name = concat !()] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this macro def +note: this attribute does not have an `!`, which means it is applied to this macro def --> $DIR/concat-in-crate-name-issue-137687.rs:5:1 | LL | / macro_rules! a { diff --git a/tests/ui/lint/unused/unused-attr-macro-rules.stderr b/tests/ui/lint/unused/unused-attr-macro-rules.stderr index e251ec65622e..75e86d3c014f 100644 --- a/tests/ui/lint/unused/unused-attr-macro-rules.stderr +++ b/tests/ui/lint/unused/unused-attr-macro-rules.stderr @@ -27,7 +27,7 @@ error: crate-level attribute should be an inner attribute: add an exclamation ma LL | #[recursion_limit="1"] | ^^^^^^^^^^^^^^^^^^^^^^ | -note: This attribute does not have an `!`, which means it is applied to this macro def +note: this attribute does not have an `!`, which means it is applied to this macro def --> $DIR/unused-attr-macro-rules.rs:12:1 | LL | / macro_rules! foo { diff --git a/tests/ui/statics/check-immutable-mut-slices.stderr b/tests/ui/statics/check-immutable-mut-slices.stderr index a9486fc9d781..1e6dfb78c93d 100644 --- a/tests/ui/statics/check-immutable-mut-slices.stderr +++ b/tests/ui/statics/check-immutable-mut-slices.stderr @@ -4,9 +4,9 @@ error[E0764]: mutable borrows of temporaries that have their lifetime extended u LL | static TEST: &'static mut [isize] = &mut []; | ^^^^^^^ this mutable borrow refers to such a temporary | - = note: Temporaries in constants and statics can have their lifetime extended until the end of the program - = note: To avoid accidentally creating global mutable state, such temporaries must be immutable - = help: If you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` + = note: temporaries in constants and statics can have their lifetime extended until the end of the program + = note: to avoid accidentally creating global mutable state, such temporaries must be immutable + = help: if you really want global mutable state, try replacing the temporary by an interior mutable `static` or a `static mut` error: aborting due to 1 previous error diff --git a/tests/ui/unstable-feature-bound/unstable_feature_bound_incompatible_stability.stderr b/tests/ui/unstable-feature-bound/unstable_feature_bound_incompatible_stability.stderr index 9f07e63e4544..e144b981f3cd 100644 --- a/tests/ui/unstable-feature-bound/unstable_feature_bound_incompatible_stability.stderr +++ b/tests/ui/unstable-feature-bound/unstable_feature_bound_incompatible_stability.stderr @@ -4,7 +4,7 @@ error: item annotated with `#[unstable_feature_bound]` should not be stable LL | fn bar() {} | ^^^^^^^^^^^ | - = help: If this item is meant to be stable, do not use any functions annotated with `#[unstable_feature_bound]`. Otherwise, mark this item as unstable with `#[unstable]` + = help: if this item is meant to be stable, do not use any functions annotated with `#[unstable_feature_bound]`. Otherwise, mark this item as unstable with `#[unstable]` error: aborting due to 1 previous error From 3a8b57715f1e762fbb78edc89c767446b7fdc0ea Mon Sep 17 00:00:00 2001 From: KaiTomotake Date: Sun, 18 Jan 2026 22:43:35 +0900 Subject: [PATCH 120/146] add lint test Co-authored-by: Redddy --- .../unused_assignments_across_match_guards.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 tests/ui/lint/unused/unused_assignments_across_match_guards.rs diff --git a/tests/ui/lint/unused/unused_assignments_across_match_guards.rs b/tests/ui/lint/unused/unused_assignments_across_match_guards.rs new file mode 100644 index 000000000000..666a529b8f85 --- /dev/null +++ b/tests/ui/lint/unused/unused_assignments_across_match_guards.rs @@ -0,0 +1,19 @@ +// Regression test for +// This test ensures that unused_assignments does not report assignments used in a match. +//@ check-pass + +fn pnk(x: usize) -> &'static str { + let mut k1 = "k1"; + let mut h1 = "h1"; + match x & 3 { + 3 if { k1 = "unused?"; false } => (), + _ if { h1 = k1; true } => (), + _ => (), + } + h1 +} + +#[deny(unused_assignments)] +fn main() { + pnk(3); +} From 3327a92b4353a03c60dbb2c58564be754e93db22 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 5 Nov 2025 20:40:15 +1100 Subject: [PATCH 121/146] Add some tests for trimmed paths in diagnostics --- .../auxiliary/doc_hidden_helper.rs | 18 +++++ tests/ui/trimmed-paths/core-unicode.rs | 19 ++++++ tests/ui/trimmed-paths/core-unicode.stderr | 14 ++++ tests/ui/trimmed-paths/doc-hidden.rs | 68 +++++++++++++++++++ tests/ui/trimmed-paths/doc-hidden.stderr | 39 +++++++++++ 5 files changed, 158 insertions(+) create mode 100644 tests/ui/trimmed-paths/auxiliary/doc_hidden_helper.rs create mode 100644 tests/ui/trimmed-paths/core-unicode.rs create mode 100644 tests/ui/trimmed-paths/core-unicode.stderr create mode 100644 tests/ui/trimmed-paths/doc-hidden.rs create mode 100644 tests/ui/trimmed-paths/doc-hidden.stderr diff --git a/tests/ui/trimmed-paths/auxiliary/doc_hidden_helper.rs b/tests/ui/trimmed-paths/auxiliary/doc_hidden_helper.rs new file mode 100644 index 000000000000..2e5e1591606e --- /dev/null +++ b/tests/ui/trimmed-paths/auxiliary/doc_hidden_helper.rs @@ -0,0 +1,18 @@ +//@ edition: 2024 + +pub struct ActuallyPub {} +#[doc(hidden)] +pub struct DocHidden {} + +pub mod pub_mod { + pub struct ActuallyPubInPubMod {} + #[doc(hidden)] + pub struct DocHiddenInPubMod {} +} + +#[doc(hidden)] +pub mod hidden_mod { + pub struct ActuallyPubInHiddenMod {} + #[doc(hidden)] + pub struct DocHiddenInHiddenMod {} +} diff --git a/tests/ui/trimmed-paths/core-unicode.rs b/tests/ui/trimmed-paths/core-unicode.rs new file mode 100644 index 000000000000..54bde92a5335 --- /dev/null +++ b/tests/ui/trimmed-paths/core-unicode.rs @@ -0,0 +1,19 @@ +//@ edition: 2024 + +// Test that the `#[doc(hidden)]` module `core::unicode` module does not +// disqualify another item named `unicode` from path trimming in diagnostics. + +use core::marker::PhantomData; + +mod inner { + #[expect(non_camel_case_types)] + pub(crate) enum unicode {} +} + +fn main() { + let PhantomData::<(inner::unicode, u32)> = PhantomData::<(u32, inner::unicode)>; + //~^ ERROR mismatched types [E0308] + //~| NOTE expected `PhantomData<(u32, unicode)>`, found `PhantomData<(unicode, u32)>` + //~| NOTE this expression has type `PhantomData<(u32, inner::unicode)>` + //~| NOTE expected struct `PhantomData<(u32, inner::unicode)>` +} diff --git a/tests/ui/trimmed-paths/core-unicode.stderr b/tests/ui/trimmed-paths/core-unicode.stderr new file mode 100644 index 000000000000..9023200d1c92 --- /dev/null +++ b/tests/ui/trimmed-paths/core-unicode.stderr @@ -0,0 +1,14 @@ +error[E0308]: mismatched types + --> $DIR/core-unicode.rs:14:9 + | +LL | let PhantomData::<(inner::unicode, u32)> = PhantomData::<(u32, inner::unicode)>; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ------------------------------------ this expression has type `PhantomData<(u32, inner::unicode)>` + | | + | expected `PhantomData<(u32, unicode)>`, found `PhantomData<(unicode, u32)>` + | + = note: expected struct `PhantomData<(u32, inner::unicode)>` + found struct `PhantomData<(inner::unicode, u32)>` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/trimmed-paths/doc-hidden.rs b/tests/ui/trimmed-paths/doc-hidden.rs new file mode 100644 index 000000000000..b73d04c3c6ae --- /dev/null +++ b/tests/ui/trimmed-paths/doc-hidden.rs @@ -0,0 +1,68 @@ +//@ edition: 2024 +//@ aux-crate: helper=doc_hidden_helper.rs + +// Test that `#[doc(hidden)]` items in other crates do not disqualify another +// item with the same name from path trimming in diagnostics. + +// Declare several modules and types whose short names match those in the aux crate. +// +// Of these, only `ActuallyPub` and `ActuallyPubInPubMod` should be disqualified +// from path trimming, because the other names only collide with `#[doc(hidden)]` +// names. +mod local { + pub(crate) struct ActuallyPub {} + pub(crate) struct DocHidden {} + + pub(crate) mod pub_mod { + pub(crate) struct ActuallyPubInPubMod {} + pub(crate) struct DocHiddenInPubMod {} + } + + pub(crate) mod hidden_mod { + pub(crate) struct ActuallyPubInHiddenMod {} + pub(crate) struct DocHiddenInHiddenMod {} + } +} + +fn main() { + uses_local(); + uses_helper(); +} + +fn uses_local() { + use local::{ActuallyPub, DocHidden}; + use local::pub_mod::{ActuallyPubInPubMod, DocHiddenInPubMod}; + use local::hidden_mod::{ActuallyPubInHiddenMod, DocHiddenInHiddenMod}; + + let _: ( + //~^ NOTE expected due to this + ActuallyPub, + DocHidden, + ActuallyPubInPubMod, + DocHiddenInPubMod, + ActuallyPubInHiddenMod, + DocHiddenInHiddenMod, + ) = 3u32; + //~^ ERROR mismatched types [E0308] + //~| NOTE expected `(ActuallyPub, ..., ..., ..., ..., ...)`, found `u32` + //~| NOTE expected tuple `(local::ActuallyPub, local::DocHidden, local::pub_mod::ActuallyPubInPubMod, local::pub_mod::DocHiddenInPubMod, local::hidden_mod::ActuallyPubInHiddenMod, local::hidden_mod::DocHiddenInHiddenMod)` +} + +fn uses_helper() { + use helper::{ActuallyPub, DocHidden}; + use helper::pub_mod::{ActuallyPubInPubMod, DocHiddenInPubMod}; + use helper::hidden_mod::{ActuallyPubInHiddenMod, DocHiddenInHiddenMod}; + + let _: ( + //~^ NOTE expected due to this + ActuallyPub, + DocHidden, + ActuallyPubInPubMod, + DocHiddenInPubMod, + ActuallyPubInHiddenMod, + DocHiddenInHiddenMod, + ) = 3u32; + //~^ ERROR mismatched types [E0308] + //~| NOTE expected `(ActuallyPub, ..., ..., ..., ..., ...)`, found `u32` + //~| NOTE expected tuple `(doc_hidden_helper::ActuallyPub, doc_hidden_helper::DocHidden, doc_hidden_helper::pub_mod::ActuallyPubInPubMod, doc_hidden_helper::pub_mod::DocHiddenInPubMod, doc_hidden_helper::hidden_mod::ActuallyPubInHiddenMod, doc_hidden_helper::hidden_mod::DocHiddenInHiddenMod)` +} diff --git a/tests/ui/trimmed-paths/doc-hidden.stderr b/tests/ui/trimmed-paths/doc-hidden.stderr new file mode 100644 index 000000000000..6f6f8f21fbe0 --- /dev/null +++ b/tests/ui/trimmed-paths/doc-hidden.stderr @@ -0,0 +1,39 @@ +error[E0308]: mismatched types + --> $DIR/doc-hidden.rs:45:9 + | +LL | let _: ( + | ____________- +LL | | +LL | | ActuallyPub, +LL | | DocHidden, +... | +LL | | DocHiddenInHiddenMod, +LL | | ) = 3u32; + | | - ^^^^ expected `(ActuallyPub, ..., ..., ..., ..., ...)`, found `u32` + | |_____| + | expected due to this + | + = note: expected tuple `(local::ActuallyPub, local::DocHidden, local::pub_mod::ActuallyPubInPubMod, local::pub_mod::DocHiddenInPubMod, local::hidden_mod::ActuallyPubInHiddenMod, local::hidden_mod::DocHiddenInHiddenMod)` + found type `u32` + +error[E0308]: mismatched types + --> $DIR/doc-hidden.rs:64:9 + | +LL | let _: ( + | ____________- +LL | | +LL | | ActuallyPub, +LL | | DocHidden, +... | +LL | | DocHiddenInHiddenMod, +LL | | ) = 3u32; + | | - ^^^^ expected `(ActuallyPub, ..., ..., ..., ..., ...)`, found `u32` + | |_____| + | expected due to this + | + = note: expected tuple `(doc_hidden_helper::ActuallyPub, doc_hidden_helper::DocHidden, doc_hidden_helper::pub_mod::ActuallyPubInPubMod, doc_hidden_helper::pub_mod::DocHiddenInPubMod, doc_hidden_helper::hidden_mod::ActuallyPubInHiddenMod, doc_hidden_helper::hidden_mod::DocHiddenInHiddenMod)` + found type `u32` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`. From 2df2c72d7ae36d11313ed730960030cc5af9fb21 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 5 Nov 2025 18:56:10 +1100 Subject: [PATCH 122/146] Ignore `#[doc(hidden)]` items when computing trimmed paths --- compiler/rustc_middle/src/ty/print/pretty.rs | 7 ++++++ ...oo-{closure#0}-{closure#0}.built.after.mir | 2 +- ...-{closure#0}-{synthetic#0}.built.after.mir | 2 +- ...0}-{closure#0}-{closure#0}.built.after.mir | 2 +- ...-{closure#0}-{synthetic#0}.built.after.mir | 2 +- ...0}-{closure#1}-{closure#0}.built.after.mir | 2 +- ...-{closure#1}-{synthetic#0}.built.after.mir | 2 +- tests/mir-opt/box_expr.rs | 2 +- .../issue_101867.main.built.after.mir | 2 +- .../boxes.main.GVN.panic-abort.diff | 4 ++-- .../boxes.main.GVN.panic-unwind.diff | 4 ++-- ..._simplification.hello.GVN.panic-abort.diff | 2 +- ...simplification.hello.GVN.panic-unwind.diff | 2 +- .../transmute.unreachable_box.GVN.32bit.diff | 2 +- .../transmute.unreachable_box.GVN.64bit.diff | 2 +- ...n.DataflowConstProp.32bit.panic-abort.diff | 10 ++++----- ....DataflowConstProp.32bit.panic-unwind.diff | 10 ++++----- ...n.DataflowConstProp.64bit.panic-abort.diff | 10 ++++----- ....DataflowConstProp.64bit.panic-unwind.diff | 10 ++++----- ...oxed_slice.main.GVN.32bit.panic-abort.diff | 12 +++++----- ...xed_slice.main.GVN.32bit.panic-unwind.diff | 12 +++++----- ...oxed_slice.main.GVN.64bit.panic-abort.diff | 12 +++++----- ...xed_slice.main.GVN.64bit.panic-unwind.diff | 12 +++++----- ...reachable_box.DataflowConstProp.32bit.diff | 2 +- ...reachable_box.DataflowConstProp.64bit.diff | 2 +- ...ng_operand.test.GVN.32bit.panic-abort.diff | 2 +- ...ng_operand.test.GVN.64bit.panic-abort.diff | 2 +- ...onential_common.GVN.32bit.panic-abort.diff | 4 ++-- ...nential_common.GVN.32bit.panic-unwind.diff | 4 ++-- ...onential_common.GVN.64bit.panic-abort.diff | 4 ++-- ...nential_common.GVN.64bit.panic-unwind.diff | 4 ++-- tests/mir-opt/gvn.slices.GVN.panic-abort.diff | 8 +++---- .../mir-opt/gvn.slices.GVN.panic-unwind.diff | 8 +++---- .../gvn.wrap_unwrap.GVN.panic-abort.diff | 2 +- .../gvn.wrap_unwrap.GVN.panic-unwind.diff | 2 +- ...inline_diverging.g.Inline.panic-abort.diff | 2 +- ...nline_diverging.g.Inline.panic-unwind.diff | 2 +- .../inline_shims.drop.Inline.panic-abort.diff | 4 ++-- ..._conditions.JumpThreading.panic-abort.diff | 8 +++---- ...conditions.JumpThreading.panic-unwind.diff | 8 +++---- ...fg-pre-optimizations.after.panic-abort.mir | 2 +- ...g-pre-optimizations.after.panic-unwind.mir | 2 +- ...ace.PreCodegen.after.32bit.panic-abort.mir | 8 +++---- ...ce.PreCodegen.after.32bit.panic-unwind.mir | 8 +++---- ...ace.PreCodegen.after.64bit.panic-abort.mir | 8 +++---- ...ce.PreCodegen.after.64bit.panic-unwind.mir | 8 +++---- .../loops.vec_move.PreCodegen.after.mir | 4 ++-- ..._to_slice.PreCodegen.after.panic-abort.mir | 4 ++-- ...to_slice.PreCodegen.after.panic-unwind.mir | 4 ++-- ...mes.foo.ScalarReplacementOfAggregates.diff | 2 +- .../async-closures/def-path.stderr | 4 ++-- .../unsizing-wfcheck-issue-126272.stderr | 2 +- tests/ui/consts/const-eval/format.rs | 2 +- tests/ui/consts/const-eval/format.stderr | 2 +- .../contract-captures-via-closure-noncopy.rs | 2 +- ...ntract-captures-via-closure-noncopy.stderr | 4 ++-- ...derives-span-Eq-enum-struct-variant.stderr | 2 +- tests/ui/derives/derives-span-Eq-enum.stderr | 2 +- .../ui/derives/derives-span-Eq-struct.stderr | 2 +- .../derives-span-Eq-tuple-struct.stderr | 2 +- tests/ui/deriving/issue-103157.stderr | 2 +- tests/ui/issues/issue-27340.stderr | 2 +- tests/ui/kindck/kindck-send-object.stderr | 2 +- tests/ui/kindck/kindck-send-object1.stderr | 2 +- tests/ui/kindck/kindck-send-object2.stderr | 2 +- tests/ui/kindck/kindck-send-owned.stderr | 2 +- .../type-length-limit-enforcement.stderr | 4 +++- tests/ui/proc-macro/bad-projection.stderr | 2 +- tests/ui/proc-macro/proc-macro-abi.stderr | 12 +++++----- ...does-not-have-iter-interpolated-dup.stderr | 2 +- .../does-not-have-iter-interpolated.stderr | 2 +- tests/ui/proc-macro/quote/not-quotable.stderr | 2 +- .../signature-proc-macro-attribute.stderr | 16 +++++++------- .../signature-proc-macro-derive.stderr | 22 +++++++++---------- .../ui/proc-macro/signature-proc-macro.stderr | 22 +++++++++---------- tests/ui/proc-macro/signature.stderr | 2 +- ...lobal-variable-promotion-error-7364.stderr | 2 +- tests/ui/traits/const-traits/issue-79450.rs | 2 +- .../ui/traits/const-traits/issue-79450.stderr | 2 +- tests/ui/traits/cycle-cache-err-60010.stderr | 4 ++-- .../negated-auto-traits-error.stderr | 8 +++---- tests/ui/trimmed-paths/core-unicode.rs | 4 ++-- tests/ui/trimmed-paths/core-unicode.stderr | 6 ++--- tests/ui/trimmed-paths/doc-hidden.rs | 2 +- tests/ui/trimmed-paths/doc-hidden.stderr | 2 +- .../panic-with-unspecified-type.stderr | 2 +- .../ui/type/pattern_types/derives_fail.stderr | 2 +- tests/ui/union/union-derive-clone.stderr | 2 +- tests/ui/union/union-derive-eq.current.stderr | 2 +- tests/ui/union/union-derive-eq.next.stderr | 2 +- 90 files changed, 209 insertions(+), 200 deletions(-) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 2a65517de403..fd0a5ca309a4 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -3421,6 +3421,13 @@ fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, N def::Res::Def(DefKind::AssocTy, _) => {} def::Res::Def(DefKind::TyAlias, _) => {} def::Res::Def(defkind, def_id) => { + // Ignore external `#[doc(hidden)]` items and their descendants. + // They shouldn't prevent other items from being considered + // unique, and should be printed with a full path if necessary. + if tcx.is_doc_hidden(def_id) { + continue; + } + if let Some(ns) = defkind.ns() { collect_fn(&child.ident, ns, def_id); } diff --git a/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#0}.built.after.mir b/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#0}.built.after.mir index 9ff1a90ab820..4c9ca11f8283 100644 --- a/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#0}.built.after.mir +++ b/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#0}.built.after.mir @@ -1,6 +1,6 @@ // MIR for `foo::{closure#0}::{closure#0}` after built -fn foo::{closure#0}::{closure#0}(_1: {async closure body@$DIR/async_closure_fake_read_for_by_move.rs:12:27: 15:6}, _2: ResumeTy) -> () +fn foo::{closure#0}::{closure#0}(_1: {async closure body@$DIR/async_closure_fake_read_for_by_move.rs:12:27: 15:6}, _2: std::future::ResumeTy) -> () yields () { debug _task_context => _2; diff --git a/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{synthetic#0}.built.after.mir b/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{synthetic#0}.built.after.mir index 4b745caf48c5..e80fdea7051d 100644 --- a/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{synthetic#0}.built.after.mir +++ b/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{synthetic#0}.built.after.mir @@ -1,6 +1,6 @@ // MIR for `foo::{closure#0}::{synthetic#0}` after built -fn foo::{closure#0}::{synthetic#0}(_1: {async closure body@$DIR/async_closure_fake_read_for_by_move.rs:12:27: 15:6}, _2: ResumeTy) -> () +fn foo::{closure#0}::{synthetic#0}(_1: {async closure body@$DIR/async_closure_fake_read_for_by_move.rs:12:27: 15:6}, _2: std::future::ResumeTy) -> () yields () { debug _task_context => _2; diff --git a/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#0}-{closure#0}.built.after.mir b/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#0}-{closure#0}.built.after.mir index 4d484b16b507..075065b4c090 100644 --- a/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#0}-{closure#0}.built.after.mir +++ b/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#0}-{closure#0}.built.after.mir @@ -1,6 +1,6 @@ // MIR for `main::{closure#0}::{closure#0}::{closure#0}` after built -fn main::{closure#0}::{closure#0}::{closure#0}(_1: {async closure body@$DIR/async_closure_shims.rs:53:53: 56:10}, _2: ResumeTy) -> () +fn main::{closure#0}::{closure#0}::{closure#0}(_1: {async closure body@$DIR/async_closure_shims.rs:53:53: 56:10}, _2: std::future::ResumeTy) -> () yields () { debug _task_context => _2; diff --git a/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#0}-{synthetic#0}.built.after.mir b/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#0}-{synthetic#0}.built.after.mir index ace780f773e8..0f4e5f3cb02f 100644 --- a/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#0}-{synthetic#0}.built.after.mir +++ b/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#0}-{synthetic#0}.built.after.mir @@ -1,6 +1,6 @@ // MIR for `main::{closure#0}::{closure#0}::{synthetic#0}` after built -fn main::{closure#0}::{closure#0}::{synthetic#0}(_1: {async closure body@$DIR/async_closure_shims.rs:53:53: 56:10}, _2: ResumeTy) -> () +fn main::{closure#0}::{closure#0}::{synthetic#0}(_1: {async closure body@$DIR/async_closure_shims.rs:53:53: 56:10}, _2: std::future::ResumeTy) -> () yields () { debug _task_context => _2; diff --git a/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#1}-{closure#0}.built.after.mir b/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#1}-{closure#0}.built.after.mir index f50ad689f447..18f4e741384f 100644 --- a/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#1}-{closure#0}.built.after.mir +++ b/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#1}-{closure#0}.built.after.mir @@ -1,6 +1,6 @@ // MIR for `main::{closure#0}::{closure#1}::{closure#0}` after built -fn main::{closure#0}::{closure#1}::{closure#0}(_1: {async closure body@$DIR/async_closure_shims.rs:62:48: 65:10}, _2: ResumeTy) -> () +fn main::{closure#0}::{closure#1}::{closure#0}(_1: {async closure body@$DIR/async_closure_shims.rs:62:48: 65:10}, _2: std::future::ResumeTy) -> () yields () { debug _task_context => _2; diff --git a/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#1}-{synthetic#0}.built.after.mir b/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#1}-{synthetic#0}.built.after.mir index 62d8adeedcb6..257586c4a080 100644 --- a/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#1}-{synthetic#0}.built.after.mir +++ b/tests/mir-opt/async_closure_shims.main-{closure#0}-{closure#1}-{synthetic#0}.built.after.mir @@ -1,6 +1,6 @@ // MIR for `main::{closure#0}::{closure#1}::{synthetic#0}` after built -fn main::{closure#0}::{closure#1}::{synthetic#0}(_1: {async closure body@$DIR/async_closure_shims.rs:62:48: 65:10}, _2: ResumeTy) -> () +fn main::{closure#0}::{closure#1}::{synthetic#0}(_1: {async closure body@$DIR/async_closure_shims.rs:62:48: 65:10}, _2: std::future::ResumeTy) -> () yields () { debug _task_context => _2; diff --git a/tests/mir-opt/box_expr.rs b/tests/mir-opt/box_expr.rs index 6299c9871809..dbb07a028a93 100644 --- a/tests/mir-opt/box_expr.rs +++ b/tests/mir-opt/box_expr.rs @@ -8,7 +8,7 @@ fn main() { // CHECK-LABEL: fn main( // CHECK: [[ptr:_.*]] = move {{_.*}} as *const S (Transmute); // CHECK: [[nonnull:_.*]] = NonNull:: { pointer: move [[ptr]] }; - // CHECK: [[unique:_.*]] = Unique:: { pointer: move [[nonnull]], _marker: const PhantomData:: }; + // CHECK: [[unique:_.*]] = std::ptr::Unique:: { pointer: move [[nonnull]], _marker: const PhantomData:: }; // CHECK: [[box:_.*]] = Box::(move [[unique]], const std::alloc::Global); // CHECK: [[ptr:_.*]] = copy (([[box]].0: std::ptr::Unique).0: std::ptr::NonNull) as *const S (Transmute); // CHECK: (*[[ptr]]) = S::new() -> [return: [[ret:bb.*]], unwind: [[unwind:bb.*]]]; diff --git a/tests/mir-opt/building/issue_101867.main.built.after.mir b/tests/mir-opt/building/issue_101867.main.built.after.mir index 83281dea44db..cef4325b9a4d 100644 --- a/tests/mir-opt/building/issue_101867.main.built.after.mir +++ b/tests/mir-opt/building/issue_101867.main.built.after.mir @@ -32,7 +32,7 @@ fn main() -> () { bb1: { StorageLive(_3); StorageLive(_4); - _4 = begin_panic::<&str>(const "explicit panic") -> bb8; + _4 = std::rt::begin_panic::<&str>(const "explicit panic") -> bb8; } bb2: { diff --git a/tests/mir-opt/const_prop/boxes.main.GVN.panic-abort.diff b/tests/mir-opt/const_prop/boxes.main.GVN.panic-abort.diff index 95eaf18b4703..ecc4b35ebcb6 100644 --- a/tests/mir-opt/const_prop/boxes.main.GVN.panic-abort.diff +++ b/tests/mir-opt/const_prop/boxes.main.GVN.panic-abort.diff @@ -29,10 +29,10 @@ StorageLive(_5); - _6 = move _4 as *const i32 (Transmute); - _7 = NonNull:: { pointer: move _6 }; -- _8 = Unique:: { pointer: move _7, _marker: const PhantomData:: }; +- _8 = std::ptr::Unique:: { pointer: move _7, _marker: const PhantomData:: }; + _6 = copy _4 as *const i32 (PtrToPtr); + _7 = NonNull:: { pointer: copy _6 }; -+ _8 = Unique:: { pointer: copy _7, _marker: const PhantomData:: }; ++ _8 = std::ptr::Unique:: { pointer: copy _7, _marker: const PhantomData:: }; _5 = Box::(move _8, const std::alloc::Global); - _9 = copy ((_5.0: std::ptr::Unique).0: std::ptr::NonNull) as *const i32 (Transmute); - (*_9) = const 42_i32; diff --git a/tests/mir-opt/const_prop/boxes.main.GVN.panic-unwind.diff b/tests/mir-opt/const_prop/boxes.main.GVN.panic-unwind.diff index 6d8d3a0dcfe2..aba1a4f1df47 100644 --- a/tests/mir-opt/const_prop/boxes.main.GVN.panic-unwind.diff +++ b/tests/mir-opt/const_prop/boxes.main.GVN.panic-unwind.diff @@ -29,10 +29,10 @@ StorageLive(_5); - _6 = move _4 as *const i32 (Transmute); - _7 = NonNull:: { pointer: move _6 }; -- _8 = Unique:: { pointer: move _7, _marker: const PhantomData:: }; +- _8 = std::ptr::Unique:: { pointer: move _7, _marker: const PhantomData:: }; + _6 = copy _4 as *const i32 (PtrToPtr); + _7 = NonNull:: { pointer: copy _6 }; -+ _8 = Unique:: { pointer: copy _7, _marker: const PhantomData:: }; ++ _8 = std::ptr::Unique:: { pointer: copy _7, _marker: const PhantomData:: }; _5 = Box::(move _8, const std::alloc::Global); - _9 = copy ((_5.0: std::ptr::Unique).0: std::ptr::NonNull) as *const i32 (Transmute); - (*_9) = const 42_i32; diff --git a/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-abort.diff b/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-abort.diff index 5df2232053fe..2ecf41638125 100644 --- a/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-abort.diff +++ b/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-abort.diff @@ -10,7 +10,7 @@ } bb1: { - _1 = begin_panic::<&str>(const "explicit panic") -> unwind unreachable; + _1 = std::rt::begin_panic::<&str>(const "explicit panic") -> unwind unreachable; } bb2: { diff --git a/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-unwind.diff b/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-unwind.diff index 788a4424943e..06287b670dd4 100644 --- a/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-unwind.diff +++ b/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-unwind.diff @@ -10,7 +10,7 @@ } bb1: { - _1 = begin_panic::<&str>(const "explicit panic") -> unwind continue; + _1 = std::rt::begin_panic::<&str>(const "explicit panic") -> unwind continue; } bb2: { diff --git a/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.32bit.diff b/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.32bit.diff index b698d8f37357..bd24af602c88 100644 --- a/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.32bit.diff +++ b/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.32bit.diff @@ -13,7 +13,7 @@ StorageLive(_1); - _1 = const 1_usize as std::boxed::Box (Transmute); - _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (Transmute); -+ _1 = const Box::(Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} }}, _marker: PhantomData:: }}, std::alloc::Global); ++ _1 = const Box::(std::ptr::Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} }}, _marker: PhantomData:: }}, std::alloc::Global); + _2 = const std::ptr::NonNull:: {{ pointer: {0x1 as *const Never} }} as *const Never (Transmute); unreachable; } diff --git a/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.64bit.diff b/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.64bit.diff index b698d8f37357..bd24af602c88 100644 --- a/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.64bit.diff +++ b/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.64bit.diff @@ -13,7 +13,7 @@ StorageLive(_1); - _1 = const 1_usize as std::boxed::Box (Transmute); - _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (Transmute); -+ _1 = const Box::(Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} }}, _marker: PhantomData:: }}, std::alloc::Global); ++ _1 = const Box::(std::ptr::Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} }}, _marker: PhantomData:: }}, std::alloc::Global); + _2 = const std::ptr::NonNull:: {{ pointer: {0x1 as *const Never} }} as *const Never (Transmute); unreachable; } diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-abort.diff index 2c89670dcf7d..7a60070b7074 100644 --- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-abort.diff +++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-abort.diff @@ -13,7 +13,7 @@ let mut _4: std::ptr::Unique<[bool; 0]>; scope 3 { } - scope 4 (inlined Unique::<[bool; 0]>::dangling) { + scope 4 (inlined std::ptr::Unique::<[bool; 0]>::dangling) { let mut _5: std::ptr::NonNull<[bool; 0]>; scope 5 (inlined NonNull::<[bool; 0]>::dangling) { let mut _6: std::num::NonZero; @@ -51,13 +51,13 @@ _5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}; StorageDead(_7); StorageDead(_6); - _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; + _4 = const std::ptr::Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; StorageDead(_5); - _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; + _3 = const std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; StorageDead(_4); - _2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); + _2 = const Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); StorageDead(_3); - _1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; + _1 = const A {{ foo: Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; StorageDead(_2); _0 = const (); drop(_1) -> [return: bb1, unwind unreachable]; diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-unwind.diff index 8fecfe224cc6..d13d0d962a69 100644 --- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-unwind.diff +++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-unwind.diff @@ -13,7 +13,7 @@ let mut _4: std::ptr::Unique<[bool; 0]>; scope 3 { } - scope 4 (inlined Unique::<[bool; 0]>::dangling) { + scope 4 (inlined std::ptr::Unique::<[bool; 0]>::dangling) { let mut _5: std::ptr::NonNull<[bool; 0]>; scope 5 (inlined NonNull::<[bool; 0]>::dangling) { let mut _6: std::num::NonZero; @@ -51,13 +51,13 @@ _5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}; StorageDead(_7); StorageDead(_6); - _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; + _4 = const std::ptr::Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; StorageDead(_5); - _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; + _3 = const std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; StorageDead(_4); - _2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); + _2 = const Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); StorageDead(_3); - _1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; + _1 = const A {{ foo: Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; StorageDead(_2); _0 = const (); drop(_1) -> [return: bb1, unwind: bb2]; diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.64bit.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.64bit.panic-abort.diff index 976ea252c2f8..8701e879e959 100644 --- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.64bit.panic-abort.diff +++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.64bit.panic-abort.diff @@ -13,7 +13,7 @@ let mut _4: std::ptr::Unique<[bool; 0]>; scope 3 { } - scope 4 (inlined Unique::<[bool; 0]>::dangling) { + scope 4 (inlined std::ptr::Unique::<[bool; 0]>::dangling) { let mut _5: std::ptr::NonNull<[bool; 0]>; scope 5 (inlined NonNull::<[bool; 0]>::dangling) { let mut _6: std::num::NonZero; @@ -51,13 +51,13 @@ _5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}; StorageDead(_7); StorageDead(_6); - _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; + _4 = const std::ptr::Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; StorageDead(_5); - _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; + _3 = const std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; StorageDead(_4); - _2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); + _2 = const Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); StorageDead(_3); - _1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; + _1 = const A {{ foo: Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; StorageDead(_2); _0 = const (); drop(_1) -> [return: bb1, unwind unreachable]; diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.64bit.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.64bit.panic-unwind.diff index 6c59f5e3e2e8..ac1c8d627baa 100644 --- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.64bit.panic-unwind.diff +++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.64bit.panic-unwind.diff @@ -13,7 +13,7 @@ let mut _4: std::ptr::Unique<[bool; 0]>; scope 3 { } - scope 4 (inlined Unique::<[bool; 0]>::dangling) { + scope 4 (inlined std::ptr::Unique::<[bool; 0]>::dangling) { let mut _5: std::ptr::NonNull<[bool; 0]>; scope 5 (inlined NonNull::<[bool; 0]>::dangling) { let mut _6: std::num::NonZero; @@ -51,13 +51,13 @@ _5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}; StorageDead(_7); StorageDead(_6); - _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; + _4 = const std::ptr::Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; StorageDead(_5); - _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; + _3 = const std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; StorageDead(_4); - _2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); + _2 = const Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); StorageDead(_3); - _1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; + _1 = const A {{ foo: Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; StorageDead(_2); _0 = const (); drop(_1) -> [return: bb1, unwind: bb2]; diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-abort.diff index 1f9cf6d6aca8..0205d0cc3d16 100644 --- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-abort.diff +++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-abort.diff @@ -13,7 +13,7 @@ let mut _4: std::ptr::Unique<[bool; 0]>; scope 3 { } - scope 4 (inlined Unique::<[bool; 0]>::dangling) { + scope 4 (inlined std::ptr::Unique::<[bool; 0]>::dangling) { let mut _5: std::ptr::NonNull<[bool; 0]>; scope 5 (inlined NonNull::<[bool; 0]>::dangling) { let mut _6: std::num::NonZero; @@ -54,17 +54,17 @@ + _5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}; StorageDead(_7); StorageDead(_6); -- _4 = Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> }; -+ _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; +- _4 = std::ptr::Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> }; ++ _4 = const std::ptr::Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; StorageDead(_5); - _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize, Implicit)); -+ _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; ++ _3 = const std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; StorageDead(_4); - _2 = Box::<[bool]>(copy _3, const std::alloc::Global); -+ _2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); ++ _2 = const Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); StorageDead(_3); - _1 = A { foo: move _2 }; -+ _1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; ++ _1 = const A {{ foo: Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; StorageDead(_2); _0 = const (); drop(_1) -> [return: bb1, unwind unreachable]; diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-unwind.diff index a8760285fac1..f6babe35b5a0 100644 --- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-unwind.diff +++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-unwind.diff @@ -13,7 +13,7 @@ let mut _4: std::ptr::Unique<[bool; 0]>; scope 3 { } - scope 4 (inlined Unique::<[bool; 0]>::dangling) { + scope 4 (inlined std::ptr::Unique::<[bool; 0]>::dangling) { let mut _5: std::ptr::NonNull<[bool; 0]>; scope 5 (inlined NonNull::<[bool; 0]>::dangling) { let mut _6: std::num::NonZero; @@ -54,17 +54,17 @@ + _5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}; StorageDead(_7); StorageDead(_6); -- _4 = Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> }; -+ _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; +- _4 = std::ptr::Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> }; ++ _4 = const std::ptr::Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; StorageDead(_5); - _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize, Implicit)); -+ _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; ++ _3 = const std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; StorageDead(_4); - _2 = Box::<[bool]>(copy _3, const std::alloc::Global); -+ _2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); ++ _2 = const Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); StorageDead(_3); - _1 = A { foo: move _2 }; -+ _1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; ++ _1 = const A {{ foo: Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; StorageDead(_2); _0 = const (); drop(_1) -> [return: bb1, unwind: bb2]; diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-abort.diff index c398ae70a1a3..204e59415c6b 100644 --- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-abort.diff +++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-abort.diff @@ -13,7 +13,7 @@ let mut _4: std::ptr::Unique<[bool; 0]>; scope 3 { } - scope 4 (inlined Unique::<[bool; 0]>::dangling) { + scope 4 (inlined std::ptr::Unique::<[bool; 0]>::dangling) { let mut _5: std::ptr::NonNull<[bool; 0]>; scope 5 (inlined NonNull::<[bool; 0]>::dangling) { let mut _6: std::num::NonZero; @@ -54,17 +54,17 @@ + _5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}; StorageDead(_7); StorageDead(_6); -- _4 = Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> }; -+ _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; +- _4 = std::ptr::Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> }; ++ _4 = const std::ptr::Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; StorageDead(_5); - _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize, Implicit)); -+ _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; ++ _3 = const std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; StorageDead(_4); - _2 = Box::<[bool]>(copy _3, const std::alloc::Global); -+ _2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); ++ _2 = const Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); StorageDead(_3); - _1 = A { foo: move _2 }; -+ _1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; ++ _1 = const A {{ foo: Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; StorageDead(_2); _0 = const (); drop(_1) -> [return: bb1, unwind unreachable]; diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-unwind.diff index 02934c02587d..0cf3f43c0464 100644 --- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-unwind.diff +++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-unwind.diff @@ -13,7 +13,7 @@ let mut _4: std::ptr::Unique<[bool; 0]>; scope 3 { } - scope 4 (inlined Unique::<[bool; 0]>::dangling) { + scope 4 (inlined std::ptr::Unique::<[bool; 0]>::dangling) { let mut _5: std::ptr::NonNull<[bool; 0]>; scope 5 (inlined NonNull::<[bool; 0]>::dangling) { let mut _6: std::num::NonZero; @@ -54,17 +54,17 @@ + _5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}; StorageDead(_7); StorageDead(_6); -- _4 = Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> }; -+ _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; +- _4 = std::ptr::Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> }; ++ _4 = const std::ptr::Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }}; StorageDead(_5); - _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize, Implicit)); -+ _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; ++ _3 = const std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}; StorageDead(_4); - _2 = Box::<[bool]>(copy _3, const std::alloc::Global); -+ _2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); ++ _2 = const Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global); StorageDead(_3); - _1 = A { foo: move _2 }; -+ _1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; ++ _1 = const A {{ foo: Box::<[bool]>(std::ptr::Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }}; StorageDead(_2); _0 = const (); drop(_1) -> [return: bb1, unwind: bb2]; diff --git a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.32bit.diff b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.32bit.diff index fa6c2e29e072..3bc5f8507590 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.32bit.diff +++ b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.32bit.diff @@ -12,7 +12,7 @@ bb0: { StorageLive(_1); - _1 = const 1_usize as std::boxed::Box (Transmute); -+ _1 = const Box::(Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} }}, _marker: PhantomData:: }}, std::alloc::Global); ++ _1 = const Box::(std::ptr::Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} }}, _marker: PhantomData:: }}, std::alloc::Global); _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (Transmute); unreachable; } diff --git a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.64bit.diff b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.64bit.diff index fa6c2e29e072..3bc5f8507590 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.64bit.diff +++ b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.64bit.diff @@ -12,7 +12,7 @@ bb0: { StorageLive(_1); - _1 = const 1_usize as std::boxed::Box (Transmute); -+ _1 = const Box::(Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} }}, _marker: PhantomData:: }}, std::alloc::Global); ++ _1 = const Box::(std::ptr::Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} }}, _marker: PhantomData:: }}, std::alloc::Global); _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (Transmute); unreachable; } diff --git a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-abort.diff b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-abort.diff index bcf0ad7c165f..2e428b778504 100644 --- a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-abort.diff +++ b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-abort.diff @@ -133,7 +133,7 @@ - _13 = copy _12 as *const () (PtrToPtr); + _13 = copy _25 as *const () (PtrToPtr); _14 = NonNull::<()> { pointer: copy _13 }; - _15 = Unique::<()> { pointer: copy _14, _marker: const PhantomData::<()> }; + _15 = std::ptr::Unique::<()> { pointer: copy _14, _marker: const PhantomData::<()> }; _3 = Box::<()>(move _15, const std::alloc::Global); - (*_13) = move _4; + (*_13) = const (); diff --git a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-abort.diff b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-abort.diff index 1b75a2bcba8b..4531720ee501 100644 --- a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-abort.diff +++ b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-abort.diff @@ -133,7 +133,7 @@ - _13 = copy _12 as *const () (PtrToPtr); + _13 = copy _25 as *const () (PtrToPtr); _14 = NonNull::<()> { pointer: copy _13 }; - _15 = Unique::<()> { pointer: copy _14, _marker: const PhantomData::<()> }; + _15 = std::ptr::Unique::<()> { pointer: copy _14, _marker: const PhantomData::<()> }; _3 = Box::<()>(move _15, const std::alloc::Global); - (*_13) = move _4; + (*_13) = const (); diff --git a/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.32bit.panic-abort.diff b/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.32bit.panic-abort.diff index 2b77aa380a0f..88c77832a4e1 100644 --- a/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.32bit.panic-abort.diff +++ b/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.32bit.panic-abort.diff @@ -56,8 +56,8 @@ } bb1: { -- _5 = MinusPlus; -+ _5 = const MinusPlus; +- _5 = core::num::flt2dec::Sign::MinusPlus; ++ _5 = const core::num::flt2dec::Sign::MinusPlus; goto -> bb3; } diff --git a/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.32bit.panic-unwind.diff b/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.32bit.panic-unwind.diff index ba6d2f3e155c..8a6e7fd35ccd 100644 --- a/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.32bit.panic-unwind.diff +++ b/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.32bit.panic-unwind.diff @@ -56,8 +56,8 @@ } bb1: { -- _5 = MinusPlus; -+ _5 = const MinusPlus; +- _5 = core::num::flt2dec::Sign::MinusPlus; ++ _5 = const core::num::flt2dec::Sign::MinusPlus; goto -> bb3; } diff --git a/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.64bit.panic-abort.diff b/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.64bit.panic-abort.diff index bf6d9d864d57..ce10f4bb247a 100644 --- a/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.64bit.panic-abort.diff +++ b/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.64bit.panic-abort.diff @@ -56,8 +56,8 @@ } bb1: { -- _5 = MinusPlus; -+ _5 = const MinusPlus; +- _5 = core::num::flt2dec::Sign::MinusPlus; ++ _5 = const core::num::flt2dec::Sign::MinusPlus; goto -> bb3; } diff --git a/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.64bit.panic-unwind.diff b/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.64bit.panic-unwind.diff index 01c87fd5317a..b19f2438d022 100644 --- a/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.64bit.panic-unwind.diff +++ b/tests/mir-opt/funky_arms.float_to_exponential_common.GVN.64bit.panic-unwind.diff @@ -56,8 +56,8 @@ } bb1: { -- _5 = MinusPlus; -+ _5 = const MinusPlus; +- _5 = core::num::flt2dec::Sign::MinusPlus; ++ _5 = const core::num::flt2dec::Sign::MinusPlus; goto -> bb3; } diff --git a/tests/mir-opt/gvn.slices.GVN.panic-abort.diff b/tests/mir-opt/gvn.slices.GVN.panic-abort.diff index b7872fc9952b..247ddc73ec36 100644 --- a/tests/mir-opt/gvn.slices.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.slices.GVN.panic-abort.diff @@ -210,9 +210,9 @@ _26 = &(*_27); StorageLive(_28); - _28 = Option::>::None; -- _22 = assert_failed::<*const u8, *const u8>(move _23, move _24, move _26, move _28) -> unwind unreachable; +- _22 = core::panicking::assert_failed::<*const u8, *const u8>(move _23, move _24, move _26, move _28) -> unwind unreachable; + _28 = const Option::>::None; -+ _22 = assert_failed::<*const u8, *const u8>(const core::panicking::AssertKind::Eq, move _24, move _26, const Option::>::None) -> unwind unreachable; ++ _22 = core::panicking::assert_failed::<*const u8, *const u8>(const core::panicking::AssertKind::Eq, move _24, move _26, const Option::>::None) -> unwind unreachable; } bb7: { @@ -313,9 +313,9 @@ _52 = &(*_53); StorageLive(_54); - _54 = Option::>::None; -- _48 = assert_failed::<*const u8, *const u8>(move _49, move _50, move _52, move _54) -> unwind unreachable; +- _48 = core::panicking::assert_failed::<*const u8, *const u8>(move _49, move _50, move _52, move _54) -> unwind unreachable; + _54 = const Option::>::None; -+ _48 = assert_failed::<*const u8, *const u8>(const core::panicking::AssertKind::Eq, move _50, move _52, const Option::>::None) -> unwind unreachable; ++ _48 = core::panicking::assert_failed::<*const u8, *const u8>(const core::panicking::AssertKind::Eq, move _50, move _52, const Option::>::None) -> unwind unreachable; } } diff --git a/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff b/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff index 37817b48c199..f15c16f1ce0f 100644 --- a/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff @@ -210,9 +210,9 @@ _26 = &(*_27); StorageLive(_28); - _28 = Option::>::None; -- _22 = assert_failed::<*const u8, *const u8>(move _23, move _24, move _26, move _28) -> unwind continue; +- _22 = core::panicking::assert_failed::<*const u8, *const u8>(move _23, move _24, move _26, move _28) -> unwind continue; + _28 = const Option::>::None; -+ _22 = assert_failed::<*const u8, *const u8>(const core::panicking::AssertKind::Eq, move _24, move _26, const Option::>::None) -> unwind continue; ++ _22 = core::panicking::assert_failed::<*const u8, *const u8>(const core::panicking::AssertKind::Eq, move _24, move _26, const Option::>::None) -> unwind continue; } bb7: { @@ -313,9 +313,9 @@ _52 = &(*_53); StorageLive(_54); - _54 = Option::>::None; -- _48 = assert_failed::<*const u8, *const u8>(move _49, move _50, move _52, move _54) -> unwind continue; +- _48 = core::panicking::assert_failed::<*const u8, *const u8>(move _49, move _50, move _52, move _54) -> unwind continue; + _54 = const Option::>::None; -+ _48 = assert_failed::<*const u8, *const u8>(const core::panicking::AssertKind::Eq, move _50, move _52, const Option::>::None) -> unwind continue; ++ _48 = core::panicking::assert_failed::<*const u8, *const u8>(const core::panicking::AssertKind::Eq, move _50, move _52, const Option::>::None) -> unwind continue; } } diff --git a/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff b/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff index 3bbfd3a891eb..c3eb5d9092be 100644 --- a/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff @@ -32,7 +32,7 @@ bb2: { StorageLive(_6); - _6 = begin_panic::<&str>(const "explicit panic") -> unwind unreachable; + _6 = std::rt::begin_panic::<&str>(const "explicit panic") -> unwind unreachable; } bb3: { diff --git a/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff b/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff index 03464f43f81e..ea1878be8cf6 100644 --- a/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff @@ -32,7 +32,7 @@ bb2: { StorageLive(_6); - _6 = begin_panic::<&str>(const "explicit panic") -> unwind continue; + _6 = std::rt::begin_panic::<&str>(const "explicit panic") -> unwind continue; } bb3: { diff --git a/tests/mir-opt/inline/inline_diverging.g.Inline.panic-abort.diff b/tests/mir-opt/inline/inline_diverging.g.Inline.panic-abort.diff index 423de59e5754..66b1bc29877a 100644 --- a/tests/mir-opt/inline/inline_diverging.g.Inline.panic-abort.diff +++ b/tests/mir-opt/inline/inline_diverging.g.Inline.panic-abort.diff @@ -36,7 +36,7 @@ StorageLive(_6); - _6 = panic() -> unwind unreachable; + StorageLive(_7); -+ _7 = begin_panic::<&str>(const "explicit panic") -> unwind unreachable; ++ _7 = std::rt::begin_panic::<&str>(const "explicit panic") -> unwind unreachable; } + } + diff --git a/tests/mir-opt/inline/inline_diverging.g.Inline.panic-unwind.diff b/tests/mir-opt/inline/inline_diverging.g.Inline.panic-unwind.diff index 3689744dcb04..68dd9530137d 100644 --- a/tests/mir-opt/inline/inline_diverging.g.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline/inline_diverging.g.Inline.panic-unwind.diff @@ -36,7 +36,7 @@ StorageLive(_6); - _6 = panic() -> unwind continue; + StorageLive(_7); -+ _7 = begin_panic::<&str>(const "explicit panic") -> unwind continue; ++ _7 = std::rt::begin_panic::<&str>(const "explicit panic") -> unwind continue; } + } + diff --git a/tests/mir-opt/inline/inline_shims.drop.Inline.panic-abort.diff b/tests/mir-opt/inline/inline_shims.drop.Inline.panic-abort.diff index 9509739413b7..a74309e16e88 100644 --- a/tests/mir-opt/inline/inline_shims.drop.Inline.panic-abort.diff +++ b/tests/mir-opt/inline/inline_shims.drop.Inline.panic-abort.diff @@ -20,13 +20,13 @@ + scope 5 (inlined alloc::raw_vec::RawVecInner::ptr::) { + scope 6 (inlined alloc::raw_vec::RawVecInner::non_null::) { + let mut _11: std::ptr::NonNull; -+ scope 7 (inlined Unique::::cast::) { ++ scope 7 (inlined std::ptr::Unique::::cast::) { + scope 8 (inlined NonNull::::cast::) { + scope 9 (inlined NonNull::::as_ptr) { + } + } + } -+ scope 10 (inlined Unique::::as_non_null_ptr) { ++ scope 10 (inlined std::ptr::Unique::::as_non_null_ptr) { + } + } + scope 11 (inlined NonNull::::as_ptr) { diff --git a/tests/mir-opt/jump_threading.chained_conditions.JumpThreading.panic-abort.diff b/tests/mir-opt/jump_threading.chained_conditions.JumpThreading.panic-abort.diff index 3cf28f4b60af..6c9cf0cf623b 100644 --- a/tests/mir-opt/jump_threading.chained_conditions.JumpThreading.panic-abort.diff +++ b/tests/mir-opt/jump_threading.chained_conditions.JumpThreading.panic-abort.diff @@ -57,13 +57,13 @@ scope 11 (inlined alloc::raw_vec::RawVecInner::ptr::) { scope 12 (inlined alloc::raw_vec::RawVecInner::non_null::) { let mut _34: std::ptr::NonNull; - scope 13 (inlined Unique::::cast::) { + scope 13 (inlined std::ptr::Unique::::cast::) { scope 14 (inlined NonNull::::cast::) { scope 15 (inlined NonNull::::as_ptr) { } } } - scope 16 (inlined Unique::::as_non_null_ptr) { + scope 16 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 17 (inlined NonNull::::as_ptr) { @@ -115,13 +115,13 @@ scope 34 (inlined alloc::raw_vec::RawVecInner::ptr::) { scope 35 (inlined alloc::raw_vec::RawVecInner::non_null::) { let mut _46: std::ptr::NonNull; - scope 36 (inlined Unique::::cast::) { + scope 36 (inlined std::ptr::Unique::::cast::) { scope 37 (inlined NonNull::::cast::) { scope 38 (inlined NonNull::::as_ptr) { } } } - scope 39 (inlined Unique::::as_non_null_ptr) { + scope 39 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 40 (inlined NonNull::::as_ptr) { diff --git a/tests/mir-opt/jump_threading.chained_conditions.JumpThreading.panic-unwind.diff b/tests/mir-opt/jump_threading.chained_conditions.JumpThreading.panic-unwind.diff index 2f0d83f92792..49cd68577a12 100644 --- a/tests/mir-opt/jump_threading.chained_conditions.JumpThreading.panic-unwind.diff +++ b/tests/mir-opt/jump_threading.chained_conditions.JumpThreading.panic-unwind.diff @@ -57,13 +57,13 @@ scope 11 (inlined alloc::raw_vec::RawVecInner::ptr::) { scope 12 (inlined alloc::raw_vec::RawVecInner::non_null::) { let mut _34: std::ptr::NonNull; - scope 13 (inlined Unique::::cast::) { + scope 13 (inlined std::ptr::Unique::::cast::) { scope 14 (inlined NonNull::::cast::) { scope 15 (inlined NonNull::::as_ptr) { } } } - scope 16 (inlined Unique::::as_non_null_ptr) { + scope 16 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 17 (inlined NonNull::::as_ptr) { @@ -115,13 +115,13 @@ scope 34 (inlined alloc::raw_vec::RawVecInner::ptr::) { scope 35 (inlined alloc::raw_vec::RawVecInner::non_null::) { let mut _46: std::ptr::NonNull; - scope 36 (inlined Unique::::cast::) { + scope 36 (inlined std::ptr::Unique::::cast::) { scope 37 (inlined NonNull::::cast::) { scope 38 (inlined NonNull::::as_ptr) { } } } - scope 39 (inlined Unique::::as_non_null_ptr) { + scope 39 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 40 (inlined NonNull::::as_ptr) { diff --git a/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-abort.mir b/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-abort.mir index 6e5f6dc9ea89..7933a36c92c2 100644 --- a/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-abort.mir +++ b/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-abort.mir @@ -24,7 +24,7 @@ fn unwrap(_1: Option) -> T { bb2: { StorageLive(_4); - _4 = begin_panic::<&str>(const "explicit panic") -> unwind unreachable; + _4 = std::rt::begin_panic::<&str>(const "explicit panic") -> unwind unreachable; } bb3: { diff --git a/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-unwind.mir b/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-unwind.mir index 758aa45f2a2b..04176b82ccd5 100644 --- a/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-unwind.mir +++ b/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-unwind.mir @@ -24,7 +24,7 @@ fn unwrap(_1: Option) -> T { bb2: { StorageLive(_4); - _4 = begin_panic::<&str>(const "explicit panic") -> bb4; + _4 = std::rt::begin_panic::<&str>(const "explicit panic") -> bb4; } bb3: { diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir index 013361d1d2fb..9202814adec7 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir @@ -14,14 +14,14 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { scope 4 { scope 12 (inlined Layout::size) { } - scope 13 (inlined Unique::<[T]>::cast::) { + scope 13 (inlined std::ptr::Unique::<[T]>::cast::) { scope 14 (inlined NonNull::<[T]>::cast::) { scope 15 (inlined NonNull::<[T]>::as_ptr) { } } } - scope 16 (inlined as From>>::from) { - scope 17 (inlined Unique::::as_non_null_ptr) { + scope 16 (inlined as From>>::from) { + scope 17 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 18 (inlined ::deallocate) { @@ -45,7 +45,7 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { } } } - scope 5 (inlined Unique::<[T]>::as_ptr) { + scope 5 (inlined std::ptr::Unique::<[T]>::as_ptr) { scope 6 (inlined NonNull::<[T]>::as_ptr) { } } diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir index 013361d1d2fb..9202814adec7 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir @@ -14,14 +14,14 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { scope 4 { scope 12 (inlined Layout::size) { } - scope 13 (inlined Unique::<[T]>::cast::) { + scope 13 (inlined std::ptr::Unique::<[T]>::cast::) { scope 14 (inlined NonNull::<[T]>::cast::) { scope 15 (inlined NonNull::<[T]>::as_ptr) { } } } - scope 16 (inlined as From>>::from) { - scope 17 (inlined Unique::::as_non_null_ptr) { + scope 16 (inlined as From>>::from) { + scope 17 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 18 (inlined ::deallocate) { @@ -45,7 +45,7 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { } } } - scope 5 (inlined Unique::<[T]>::as_ptr) { + scope 5 (inlined std::ptr::Unique::<[T]>::as_ptr) { scope 6 (inlined NonNull::<[T]>::as_ptr) { } } diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir index 013361d1d2fb..9202814adec7 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir @@ -14,14 +14,14 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { scope 4 { scope 12 (inlined Layout::size) { } - scope 13 (inlined Unique::<[T]>::cast::) { + scope 13 (inlined std::ptr::Unique::<[T]>::cast::) { scope 14 (inlined NonNull::<[T]>::cast::) { scope 15 (inlined NonNull::<[T]>::as_ptr) { } } } - scope 16 (inlined as From>>::from) { - scope 17 (inlined Unique::::as_non_null_ptr) { + scope 16 (inlined as From>>::from) { + scope 17 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 18 (inlined ::deallocate) { @@ -45,7 +45,7 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { } } } - scope 5 (inlined Unique::<[T]>::as_ptr) { + scope 5 (inlined std::ptr::Unique::<[T]>::as_ptr) { scope 6 (inlined NonNull::<[T]>::as_ptr) { } } diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir index 013361d1d2fb..9202814adec7 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir @@ -14,14 +14,14 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { scope 4 { scope 12 (inlined Layout::size) { } - scope 13 (inlined Unique::<[T]>::cast::) { + scope 13 (inlined std::ptr::Unique::<[T]>::cast::) { scope 14 (inlined NonNull::<[T]>::cast::) { scope 15 (inlined NonNull::<[T]>::as_ptr) { } } } - scope 16 (inlined as From>>::from) { - scope 17 (inlined Unique::::as_non_null_ptr) { + scope 16 (inlined as From>>::from) { + scope 17 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 18 (inlined ::deallocate) { @@ -45,7 +45,7 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { } } } - scope 5 (inlined Unique::<[T]>::as_ptr) { + scope 5 (inlined std::ptr::Unique::<[T]>::as_ptr) { scope 6 (inlined NonNull::<[T]>::as_ptr) { } } diff --git a/tests/mir-opt/pre-codegen/loops.vec_move.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/loops.vec_move.PreCodegen.after.mir index 6ab4b7712306..c8b9ff1dbed9 100644 --- a/tests/mir-opt/pre-codegen/loops.vec_move.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/loops.vec_move.PreCodegen.after.mir @@ -139,14 +139,14 @@ fn vec_move(_1: Vec) -> () { debug self => _31; scope 23 (inlined alloc::raw_vec::RawVecInner::non_null::) { let mut _5: std::ptr::NonNull; - scope 24 (inlined Unique::::cast::) { + scope 24 (inlined std::ptr::Unique::::cast::) { scope 25 (inlined NonNull::::cast::) { let mut _6: *const impl Sized; scope 26 (inlined NonNull::::as_ptr) { } } } - scope 27 (inlined Unique::::as_non_null_ptr) { + scope 27 (inlined std::ptr::Unique::::as_non_null_ptr) { } } } diff --git a/tests/mir-opt/pre-codegen/vec_deref.vec_deref_to_slice.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/vec_deref.vec_deref_to_slice.PreCodegen.after.panic-abort.mir index 8308ecbad716..730aedf4f1a3 100644 --- a/tests/mir-opt/pre-codegen/vec_deref.vec_deref_to_slice.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/vec_deref.vec_deref_to_slice.PreCodegen.after.panic-abort.mir @@ -16,13 +16,13 @@ fn vec_deref_to_slice(_1: &Vec) -> &[u8] { scope 5 (inlined alloc::raw_vec::RawVecInner::ptr::) { scope 6 (inlined alloc::raw_vec::RawVecInner::non_null::) { let mut _2: std::ptr::NonNull; - scope 7 (inlined Unique::::cast::) { + scope 7 (inlined std::ptr::Unique::::cast::) { scope 8 (inlined NonNull::::cast::) { scope 9 (inlined NonNull::::as_ptr) { } } } - scope 10 (inlined Unique::::as_non_null_ptr) { + scope 10 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 11 (inlined NonNull::::as_ptr) { diff --git a/tests/mir-opt/pre-codegen/vec_deref.vec_deref_to_slice.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/vec_deref.vec_deref_to_slice.PreCodegen.after.panic-unwind.mir index 8308ecbad716..730aedf4f1a3 100644 --- a/tests/mir-opt/pre-codegen/vec_deref.vec_deref_to_slice.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/vec_deref.vec_deref_to_slice.PreCodegen.after.panic-unwind.mir @@ -16,13 +16,13 @@ fn vec_deref_to_slice(_1: &Vec) -> &[u8] { scope 5 (inlined alloc::raw_vec::RawVecInner::ptr::) { scope 6 (inlined alloc::raw_vec::RawVecInner::non_null::) { let mut _2: std::ptr::NonNull; - scope 7 (inlined Unique::::cast::) { + scope 7 (inlined std::ptr::Unique::::cast::) { scope 8 (inlined NonNull::::cast::) { scope 9 (inlined NonNull::::as_ptr) { } } } - scope 10 (inlined Unique::::as_non_null_ptr) { + scope 10 (inlined std::ptr::Unique::::as_non_null_ptr) { } } scope 11 (inlined NonNull::::as_ptr) { diff --git a/tests/mir-opt/sroa/lifetimes.foo.ScalarReplacementOfAggregates.diff b/tests/mir-opt/sroa/lifetimes.foo.ScalarReplacementOfAggregates.diff index 7012cc5aa7f6..f9965a529ebc 100644 --- a/tests/mir-opt/sroa/lifetimes.foo.ScalarReplacementOfAggregates.diff +++ b/tests/mir-opt/sroa/lifetimes.foo.ScalarReplacementOfAggregates.diff @@ -152,7 +152,7 @@ StorageDead(_22); StorageDead(_21); StorageDead(_20); - _10 = _eprint(move _11) -> [return: bb6, unwind unreachable]; + _10 = std::io::_eprint(move _11) -> [return: bb6, unwind unreachable]; } bb6: { diff --git a/tests/ui/async-await/async-closures/def-path.stderr b/tests/ui/async-await/async-closures/def-path.stderr index a507fa697604..e140e9b94b30 100644 --- a/tests/ui/async-await/async-closures/def-path.stderr +++ b/tests/ui/async-await/async-closures/def-path.stderr @@ -5,11 +5,11 @@ LL | let x = async || {}; | -- the expected `async` closure body LL | LL | let () = x(); - | ^^ --- this expression has type `{static main::{closure#0}::{closure#0} upvar_tys=?14t resume_ty=ResumeTy yield_ty=() return_ty=()}` + | ^^ --- this expression has type `{static main::{closure#0}::{closure#0} upvar_tys=?14t resume_ty=std::future::ResumeTy yield_ty=() return_ty=()}` | | | expected `async` closure body, found `()` | - = note: expected `async` closure body `{static main::{closure#0}::{closure#0} upvar_tys=?14t resume_ty=ResumeTy yield_ty=() return_ty=()}` + = note: expected `async` closure body `{static main::{closure#0}::{closure#0} upvar_tys=?14t resume_ty=std::future::ResumeTy yield_ty=() return_ty=()}` found unit type `()` error: aborting due to 1 previous error diff --git a/tests/ui/const-generics/adt_const_params/unsizing-wfcheck-issue-126272.stderr b/tests/ui/const-generics/adt_const_params/unsizing-wfcheck-issue-126272.stderr index af29eaa35cb6..aecd97ef7763 100644 --- a/tests/ui/const-generics/adt_const_params/unsizing-wfcheck-issue-126272.stderr +++ b/tests/ui/const-generics/adt_const_params/unsizing-wfcheck-issue-126272.stderr @@ -99,7 +99,7 @@ LL | #[derive(Debug, PartialEq, Eq, ConstParamTy)] | ^^ unsatisfied trait bound introduced in this `derive` macro = note: 1 redundant requirement hidden = note: required for `&'static Bar` to implement `Eq` -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL error[E0277]: the size for values of type `dyn Debug` cannot be known at compilation time diff --git a/tests/ui/consts/const-eval/format.rs b/tests/ui/consts/const-eval/format.rs index a8085a786e18..f25c7018f826 100644 --- a/tests/ui/consts/const-eval/format.rs +++ b/tests/ui/consts/const-eval/format.rs @@ -6,7 +6,7 @@ const fn failure() { const fn print() { println!("{:?}", 0); //~^ ERROR cannot call non-const formatting macro in constant functions - //~| ERROR cannot call non-const function `_print` in constant functions + //~| ERROR cannot call non-const function `std::io::_print` in constant functions } const fn format_args() { diff --git a/tests/ui/consts/const-eval/format.stderr b/tests/ui/consts/const-eval/format.stderr index ea191eb5c098..06bada8da011 100644 --- a/tests/ui/consts/const-eval/format.stderr +++ b/tests/ui/consts/const-eval/format.stderr @@ -15,7 +15,7 @@ LL | println!("{:?}", 0); = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants = note: this error originates in the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0015]: cannot call non-const function `_print` in constant functions +error[E0015]: cannot call non-const function `std::io::_print` in constant functions --> $DIR/format.rs:7:5 | LL | println!("{:?}", 0); diff --git a/tests/ui/contracts/contract-captures-via-closure-noncopy.rs b/tests/ui/contracts/contract-captures-via-closure-noncopy.rs index c7aa72d2b0f6..5153a7b48dcd 100644 --- a/tests/ui/contracts/contract-captures-via-closure-noncopy.rs +++ b/tests/ui/contracts/contract-captures-via-closure-noncopy.rs @@ -13,7 +13,7 @@ struct Baz { #[core::contracts::ensures({let old = x; move |ret:&Baz| ret.baz == old.baz*2 })] // Relevant thing is this: ^^^^^^^^^^^ // because we are capturing state that is non-Copy. -//~^^^ ERROR trait bound `Baz: std::marker::Copy` is not satisfied +//~^^^ ERROR trait bound `Baz: Copy` is not satisfied fn doubler(x: Baz) -> Baz { Baz { baz: x.baz + 10 } } diff --git a/tests/ui/contracts/contract-captures-via-closure-noncopy.stderr b/tests/ui/contracts/contract-captures-via-closure-noncopy.stderr index 5f55faed80c8..20c220e98bcc 100644 --- a/tests/ui/contracts/contract-captures-via-closure-noncopy.stderr +++ b/tests/ui/contracts/contract-captures-via-closure-noncopy.stderr @@ -1,4 +1,4 @@ -error[E0277]: the trait bound `Baz: std::marker::Copy` is not satisfied in `{closure@$DIR/contract-captures-via-closure-noncopy.rs:13:42: 13:57}` +error[E0277]: the trait bound `Baz: Copy` is not satisfied in `{closure@$DIR/contract-captures-via-closure-noncopy.rs:13:42: 13:57}` --> $DIR/contract-captures-via-closure-noncopy.rs:13:1 | LL | #[core::contracts::ensures({let old = x; move |ret:&Baz| ret.baz == old.baz*2 })] @@ -9,7 +9,7 @@ LL | #[core::contracts::ensures({let old = x; move |ret:&Baz| ret.baz == old.baz | unsatisfied trait bound | required by a bound introduced by this call | - = help: within `{closure@$DIR/contract-captures-via-closure-noncopy.rs:13:42: 13:57}`, the trait `std::marker::Copy` is not implemented for `Baz` + = help: within `{closure@$DIR/contract-captures-via-closure-noncopy.rs:13:42: 13:57}`, the trait `Copy` is not implemented for `Baz` note: required because it's used within this closure --> $DIR/contract-captures-via-closure-noncopy.rs:13:42 | diff --git a/tests/ui/derives/derives-span-Eq-enum-struct-variant.stderr b/tests/ui/derives/derives-span-Eq-enum-struct-variant.stderr index e0cb3c1b43da..42dc8d46b575 100644 --- a/tests/ui/derives/derives-span-Eq-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-Eq-enum-struct-variant.stderr @@ -7,7 +7,7 @@ LL | #[derive(Eq,PartialEq)] LL | x: Error | ^^^^^^^^ the trait `Eq` is not implemented for `Error` | -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL help: consider annotating `Error` with `#[derive(Eq)]` | diff --git a/tests/ui/derives/derives-span-Eq-enum.stderr b/tests/ui/derives/derives-span-Eq-enum.stderr index 2f09b9ea385f..ef1d9e3242ad 100644 --- a/tests/ui/derives/derives-span-Eq-enum.stderr +++ b/tests/ui/derives/derives-span-Eq-enum.stderr @@ -7,7 +7,7 @@ LL | #[derive(Eq,PartialEq)] LL | Error | ^^^^^ the trait `Eq` is not implemented for `Error` | -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL help: consider annotating `Error` with `#[derive(Eq)]` | diff --git a/tests/ui/derives/derives-span-Eq-struct.stderr b/tests/ui/derives/derives-span-Eq-struct.stderr index c16d9118e10f..bae7bb0361df 100644 --- a/tests/ui/derives/derives-span-Eq-struct.stderr +++ b/tests/ui/derives/derives-span-Eq-struct.stderr @@ -7,7 +7,7 @@ LL | struct Struct { LL | x: Error | ^^^^^^^^ the trait `Eq` is not implemented for `Error` | -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL help: consider annotating `Error` with `#[derive(Eq)]` | diff --git a/tests/ui/derives/derives-span-Eq-tuple-struct.stderr b/tests/ui/derives/derives-span-Eq-tuple-struct.stderr index dac295eed919..13396cb27246 100644 --- a/tests/ui/derives/derives-span-Eq-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-Eq-tuple-struct.stderr @@ -7,7 +7,7 @@ LL | struct Struct( LL | Error | ^^^^^ the trait `Eq` is not implemented for `Error` | -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL help: consider annotating `Error` with `#[derive(Eq)]` | diff --git a/tests/ui/deriving/issue-103157.stderr b/tests/ui/deriving/issue-103157.stderr index 51d4d0a89745..0e4a3f75db3f 100644 --- a/tests/ui/deriving/issue-103157.stderr +++ b/tests/ui/deriving/issue-103157.stderr @@ -18,7 +18,7 @@ LL | Float(Option), u16 and 4 others = note: required for `Option` to implement `Eq` -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL error: aborting due to 1 previous error diff --git a/tests/ui/issues/issue-27340.stderr b/tests/ui/issues/issue-27340.stderr index d5ff29a618b0..7cde901ffd95 100644 --- a/tests/ui/issues/issue-27340.stderr +++ b/tests/ui/issues/issue-27340.stderr @@ -16,7 +16,7 @@ LL | LL | struct Bar(Foo); | ^^^ the trait `Clone` is not implemented for `Foo` | -note: required by a bound in `AssertParamIsClone` +note: required by a bound in `std::clone::AssertParamIsClone` --> $SRC_DIR/core/src/clone.rs:LL:COL help: consider annotating `Foo` with `#[derive(Clone)]` | diff --git a/tests/ui/kindck/kindck-send-object.stderr b/tests/ui/kindck/kindck-send-object.stderr index 0e2ff1730c8d..b71d4029350e 100644 --- a/tests/ui/kindck/kindck-send-object.stderr +++ b/tests/ui/kindck/kindck-send-object.stderr @@ -19,7 +19,7 @@ LL | assert_send::>(); | ^^^^^^^^^^^^^^ `dyn Dummy` cannot be sent between threads safely | = help: the trait `Send` is not implemented for `dyn Dummy` - = note: required for `Unique` to implement `Send` + = note: required for `std::ptr::Unique` to implement `Send` note: required because it appears within the type `Box` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL note: required by a bound in `assert_send` diff --git a/tests/ui/kindck/kindck-send-object1.stderr b/tests/ui/kindck/kindck-send-object1.stderr index e3ff2eb9ff4c..2184ae704673 100644 --- a/tests/ui/kindck/kindck-send-object1.stderr +++ b/tests/ui/kindck/kindck-send-object1.stderr @@ -19,7 +19,7 @@ LL | assert_send::>(); | ^^^^^^^^^^^^^^^^^^^ `(dyn Dummy + 'a)` cannot be sent between threads safely | = help: the trait `Send` is not implemented for `(dyn Dummy + 'a)` - = note: required for `Unique<(dyn Dummy + 'a)>` to implement `Send` + = note: required for `std::ptr::Unique<(dyn Dummy + 'a)>` to implement `Send` note: required because it appears within the type `Box<(dyn Dummy + 'a)>` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL note: required by a bound in `assert_send` diff --git a/tests/ui/kindck/kindck-send-object2.stderr b/tests/ui/kindck/kindck-send-object2.stderr index 8898bf5b3fab..52a7055b4229 100644 --- a/tests/ui/kindck/kindck-send-object2.stderr +++ b/tests/ui/kindck/kindck-send-object2.stderr @@ -19,7 +19,7 @@ LL | assert_send::>(); | ^^^^^^^^^^^^^^ `dyn Dummy` cannot be sent between threads safely | = help: the trait `Send` is not implemented for `dyn Dummy` - = note: required for `Unique` to implement `Send` + = note: required for `std::ptr::Unique` to implement `Send` note: required because it appears within the type `Box` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL note: required by a bound in `assert_send` diff --git a/tests/ui/kindck/kindck-send-owned.stderr b/tests/ui/kindck/kindck-send-owned.stderr index 860a9391bbb0..c433d80cf140 100644 --- a/tests/ui/kindck/kindck-send-owned.stderr +++ b/tests/ui/kindck/kindck-send-owned.stderr @@ -5,7 +5,7 @@ LL | assert_send::>(); | ^^^^^^^^^^^^ `*mut u8` cannot be sent between threads safely | = help: the trait `Send` is not implemented for `*mut u8` - = note: required for `Unique<*mut u8>` to implement `Send` + = note: required for `std::ptr::Unique<*mut u8>` to implement `Send` note: required because it appears within the type `Box<*mut u8>` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL note: required by a bound in `assert_send` diff --git a/tests/ui/limits/type-length-limit-enforcement.stderr b/tests/ui/limits/type-length-limit-enforcement.stderr index bfea0b5a4482..82855bd75528 100644 --- a/tests/ui/limits/type-length-limit-enforcement.stderr +++ b/tests/ui/limits/type-length-limit-enforcement.stderr @@ -8,9 +8,11 @@ LL | drop::>(None); = note: the full name for the type has been written to '$TEST_BUILD_DIR/type-length-limit-enforcement.long-type-$LONG_TYPE_HASH.txt' = note: consider using `--verbose` to print the full type name to the console -error: reached the type-length limit while instantiating `<{closure@rt::lang_start<()>::{closure#0}} as FnMut<()>>::call_mut` +error: reached the type-length limit while instantiating `<{closure@...} as FnMut<()>>::call_mut` | = help: consider adding a `#![type_length_limit="10"]` attribute to your crate + = note: the full name for the type has been written to '$TEST_BUILD_DIR/type-length-limit-enforcement.long-type-$LONG_TYPE_HASH.txt' + = note: consider using `--verbose` to print the full type name to the console error: aborting due to 2 previous errors diff --git a/tests/ui/proc-macro/bad-projection.stderr b/tests/ui/proc-macro/bad-projection.stderr index f2981499367b..5b472d407044 100644 --- a/tests/ui/proc-macro/bad-projection.stderr +++ b/tests/ui/proc-macro/bad-projection.stderr @@ -33,7 +33,7 @@ LL | pub fn uwu() -> <() as Project>::Assoc {} | takes 0 arguments | required by a bound introduced by this call | -note: required by a bound in `ProcMacro::bang` +note: required by a bound in `proc_macro::bridge::client::ProcMacro::bang` --> $SRC_DIR/proc_macro/src/bridge/client.rs:LL:COL error[E0277]: the trait bound `(): Project` is not satisfied diff --git a/tests/ui/proc-macro/proc-macro-abi.stderr b/tests/ui/proc-macro/proc-macro-abi.stderr index ccc72e5187ed..ccefdbfa3a86 100644 --- a/tests/ui/proc-macro/proc-macro-abi.stderr +++ b/tests/ui/proc-macro/proc-macro-abi.stderr @@ -4,8 +4,8 @@ error: function-like proc macro has incorrect signature LL | pub extern "C" fn abi(a: TokenStream) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected "Rust" fn, found "C" fn | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `extern "C" fn(proc_macro::TokenStream) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `extern "C" fn(TokenStream) -> TokenStream` error: function-like proc macro has incorrect signature --> $DIR/proc-macro-abi.rs:17:1 @@ -13,8 +13,8 @@ error: function-like proc macro has incorrect signature LL | pub extern "system" fn abi2(a: TokenStream) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected "Rust" fn, found "system" fn | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `extern "system" fn(proc_macro::TokenStream) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `extern "system" fn(TokenStream) -> TokenStream` error: function-like proc macro has incorrect signature --> $DIR/proc-macro-abi.rs:23:1 @@ -22,8 +22,8 @@ error: function-like proc macro has incorrect signature LL | pub extern fn abi3(a: TokenStream) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected "Rust" fn, found "C" fn | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `extern "C" fn(proc_macro::TokenStream) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `extern "C" fn(TokenStream) -> TokenStream` error: aborting due to 3 previous errors diff --git a/tests/ui/proc-macro/quote/does-not-have-iter-interpolated-dup.stderr b/tests/ui/proc-macro/quote/does-not-have-iter-interpolated-dup.stderr index 0bcea9b85f47..86a00713a456 100644 --- a/tests/ui/proc-macro/quote/does-not-have-iter-interpolated-dup.stderr +++ b/tests/ui/proc-macro/quote/does-not-have-iter-interpolated-dup.stderr @@ -5,7 +5,7 @@ LL | quote!($($nonrep $nonrep)*); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` - | here the type of `has_iter` is inferred to be `ThereIsNoIteratorInRepetition` + | here the type of `has_iter` is inferred to be `proc_macro::ThereIsNoIteratorInRepetition` error: aborting due to 1 previous error diff --git a/tests/ui/proc-macro/quote/does-not-have-iter-interpolated.stderr b/tests/ui/proc-macro/quote/does-not-have-iter-interpolated.stderr index d945ab41a12e..325e50f9796a 100644 --- a/tests/ui/proc-macro/quote/does-not-have-iter-interpolated.stderr +++ b/tests/ui/proc-macro/quote/does-not-have-iter-interpolated.stderr @@ -5,7 +5,7 @@ LL | quote!($($nonrep)*); | ^^^^^^^^^^^^^^^^^^^ | | | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` - | here the type of `has_iter` is inferred to be `ThereIsNoIteratorInRepetition` + | here the type of `has_iter` is inferred to be `proc_macro::ThereIsNoIteratorInRepetition` error: aborting due to 1 previous error diff --git a/tests/ui/proc-macro/quote/not-quotable.stderr b/tests/ui/proc-macro/quote/not-quotable.stderr index b00d029946d6..4177d9c672b5 100644 --- a/tests/ui/proc-macro/quote/not-quotable.stderr +++ b/tests/ui/proc-macro/quote/not-quotable.stderr @@ -11,11 +11,11 @@ LL | let _ = quote! { $ip }; &T &mut T Box + CStr CString Cow<'_, T> Option Rc - bool and 24 others error: aborting due to 1 previous error diff --git a/tests/ui/proc-macro/signature-proc-macro-attribute.stderr b/tests/ui/proc-macro/signature-proc-macro-attribute.stderr index ce832eaa5c7a..9dfb081a10e6 100644 --- a/tests/ui/proc-macro/signature-proc-macro-attribute.stderr +++ b/tests/ui/proc-macro/signature-proc-macro-attribute.stderr @@ -4,8 +4,8 @@ error: attribute proc macro has incorrect signature LL | pub fn bad_input(input: String) -> TokenStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ incorrect number of function parameters | - = note: expected signature `fn(proc_macro::TokenStream, proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(std::string::String) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream, TokenStream) -> TokenStream` + found signature `fn(String) -> TokenStream` error: attribute proc macro has incorrect signature --> $DIR/signature-proc-macro-attribute.rs:16:1 @@ -13,8 +13,8 @@ error: attribute proc macro has incorrect signature LL | pub fn bad_output(input: TokenStream) -> String { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ incorrect number of function parameters | - = note: expected signature `fn(proc_macro::TokenStream, proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(proc_macro::TokenStream) -> std::string::String` + = note: expected signature `fn(TokenStream, TokenStream) -> TokenStream` + found signature `fn(TokenStream) -> String` error: attribute proc macro has incorrect signature --> $DIR/signature-proc-macro-attribute.rs:22:1 @@ -22,8 +22,8 @@ error: attribute proc macro has incorrect signature LL | pub fn bad_everything(input: String) -> String { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ incorrect number of function parameters | - = note: expected signature `fn(proc_macro::TokenStream, proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(std::string::String) -> std::string::String` + = note: expected signature `fn(TokenStream, TokenStream) -> TokenStream` + found signature `fn(String) -> String` error: attribute proc macro has incorrect signature --> $DIR/signature-proc-macro-attribute.rs:28:52 @@ -31,8 +31,8 @@ error: attribute proc macro has incorrect signature LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { | ^^^^^^ incorrect number of function parameters | - = note: expected signature `fn(proc_macro::TokenStream, proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(proc_macro::TokenStream, proc_macro::TokenStream, std::string::String) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream, TokenStream) -> TokenStream` + found signature `fn(TokenStream, TokenStream, String) -> TokenStream` error: aborting due to 4 previous errors diff --git a/tests/ui/proc-macro/signature-proc-macro-derive.stderr b/tests/ui/proc-macro/signature-proc-macro-derive.stderr index 03c6abad17d9..3539ae7c2e17 100644 --- a/tests/ui/proc-macro/signature-proc-macro-derive.stderr +++ b/tests/ui/proc-macro/signature-proc-macro-derive.stderr @@ -2,28 +2,28 @@ error: derive proc macro has incorrect signature --> $DIR/signature-proc-macro-derive.rs:10:25 | LL | pub fn bad_input(input: String) -> TokenStream { - | ^^^^^^ expected `proc_macro::TokenStream`, found `std::string::String` + | ^^^^^^ expected `TokenStream`, found `String` | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(std::string::String) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `fn(String) -> TokenStream` error: derive proc macro has incorrect signature --> $DIR/signature-proc-macro-derive.rs:16:42 | LL | pub fn bad_output(input: TokenStream) -> String { - | ^^^^^^ expected `proc_macro::TokenStream`, found `std::string::String` + | ^^^^^^ expected `TokenStream`, found `String` | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(proc_macro::TokenStream) -> std::string::String` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `fn(TokenStream) -> String` error: derive proc macro has incorrect signature --> $DIR/signature-proc-macro-derive.rs:22:30 | LL | pub fn bad_everything(input: String) -> String { - | ^^^^^^ expected `proc_macro::TokenStream`, found `std::string::String` + | ^^^^^^ expected `TokenStream`, found `String` | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(std::string::String) -> std::string::String` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `fn(String) -> String` error: derive proc macro has incorrect signature --> $DIR/signature-proc-macro-derive.rs:28:36 @@ -31,8 +31,8 @@ error: derive proc macro has incorrect signature LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { | ^^^^^^^^^^^ incorrect number of function parameters | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(proc_macro::TokenStream, proc_macro::TokenStream, std::string::String) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `fn(TokenStream, TokenStream, String) -> TokenStream` error: aborting due to 4 previous errors diff --git a/tests/ui/proc-macro/signature-proc-macro.stderr b/tests/ui/proc-macro/signature-proc-macro.stderr index dd2cb0570daa..1959d8c6d615 100644 --- a/tests/ui/proc-macro/signature-proc-macro.stderr +++ b/tests/ui/proc-macro/signature-proc-macro.stderr @@ -2,28 +2,28 @@ error: function-like proc macro has incorrect signature --> $DIR/signature-proc-macro.rs:10:25 | LL | pub fn bad_input(input: String) -> TokenStream { - | ^^^^^^ expected `proc_macro::TokenStream`, found `std::string::String` + | ^^^^^^ expected `TokenStream`, found `String` | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(std::string::String) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `fn(String) -> TokenStream` error: function-like proc macro has incorrect signature --> $DIR/signature-proc-macro.rs:16:42 | LL | pub fn bad_output(input: TokenStream) -> String { - | ^^^^^^ expected `proc_macro::TokenStream`, found `std::string::String` + | ^^^^^^ expected `TokenStream`, found `String` | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(proc_macro::TokenStream) -> std::string::String` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `fn(TokenStream) -> String` error: function-like proc macro has incorrect signature --> $DIR/signature-proc-macro.rs:22:30 | LL | pub fn bad_everything(input: String) -> String { - | ^^^^^^ expected `proc_macro::TokenStream`, found `std::string::String` + | ^^^^^^ expected `TokenStream`, found `String` | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(std::string::String) -> std::string::String` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `fn(String) -> String` error: function-like proc macro has incorrect signature --> $DIR/signature-proc-macro.rs:28:36 @@ -31,8 +31,8 @@ error: function-like proc macro has incorrect signature LL | pub fn too_many(a: TokenStream, b: TokenStream, c: String) -> TokenStream { | ^^^^^^^^^^^ incorrect number of function parameters | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` - found signature `fn(proc_macro::TokenStream, proc_macro::TokenStream, std::string::String) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream) -> TokenStream` + found signature `fn(TokenStream, TokenStream, String) -> TokenStream` error: aborting due to 4 previous errors diff --git a/tests/ui/proc-macro/signature.stderr b/tests/ui/proc-macro/signature.stderr index fd679442b6af..2c1973eb6e6d 100644 --- a/tests/ui/proc-macro/signature.stderr +++ b/tests/ui/proc-macro/signature.stderr @@ -4,7 +4,7 @@ error: derive proc macro has incorrect signature LL | pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected safe fn, found unsafe fn | - = note: expected signature `fn(proc_macro::TokenStream) -> proc_macro::TokenStream` + = note: expected signature `fn(TokenStream) -> TokenStream` found signature `unsafe extern "C" fn(i32, u32) -> u32` error: aborting due to 1 previous error diff --git a/tests/ui/static/global-variable-promotion-error-7364.stderr b/tests/ui/static/global-variable-promotion-error-7364.stderr index b9d75676bef8..9f0026621c13 100644 --- a/tests/ui/static/global-variable-promotion-error-7364.stderr +++ b/tests/ui/static/global-variable-promotion-error-7364.stderr @@ -6,7 +6,7 @@ LL | static boxed: Box> = Box::new(RefCell::new(0)); | = help: the trait `Sync` is not implemented for `RefCell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead - = note: required for `Unique>` to implement `Sync` + = note: required for `std::ptr::Unique>` to implement `Sync` note: required because it appears within the type `Box>` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL = note: shared static variables must have a type that implements `Sync` diff --git a/tests/ui/traits/const-traits/issue-79450.rs b/tests/ui/traits/const-traits/issue-79450.rs index e74da811fc80..c6234f8616d7 100644 --- a/tests/ui/traits/const-traits/issue-79450.rs +++ b/tests/ui/traits/const-traits/issue-79450.rs @@ -5,7 +5,7 @@ const trait Tr { fn req(&self); fn prov(&self) { - println!("lul"); //~ ERROR: cannot call non-const function `_print` in constant functions + println!("lul"); //~ ERROR: cannot call non-const function `std::io::_print` in constant functions self.req(); } } diff --git a/tests/ui/traits/const-traits/issue-79450.stderr b/tests/ui/traits/const-traits/issue-79450.stderr index c10023e9f0ef..702e93a76a8f 100644 --- a/tests/ui/traits/const-traits/issue-79450.stderr +++ b/tests/ui/traits/const-traits/issue-79450.stderr @@ -1,4 +1,4 @@ -error[E0015]: cannot call non-const function `_print` in constant functions +error[E0015]: cannot call non-const function `std::io::_print` in constant functions --> $DIR/issue-79450.rs:8:9 | LL | println!("lul"); diff --git a/tests/ui/traits/cycle-cache-err-60010.stderr b/tests/ui/traits/cycle-cache-err-60010.stderr index 4f5e31818321..9665d5badf59 100644 --- a/tests/ui/traits/cycle-cache-err-60010.stderr +++ b/tests/ui/traits/cycle-cache-err-60010.stderr @@ -6,7 +6,7 @@ LL | _parse: >::Data, | note: required because it appears within the type `PhantomData` --> $SRC_DIR/core/src/marker.rs:LL:COL -note: required because it appears within the type `Unique` +note: required because it appears within the type `std::ptr::Unique` --> $SRC_DIR/core/src/ptr/unique.rs:LL:COL note: required because it appears within the type `Box` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL @@ -45,7 +45,7 @@ LL | type Storage = SalsaStorage; | note: required because it appears within the type `PhantomData` --> $SRC_DIR/core/src/marker.rs:LL:COL -note: required because it appears within the type `Unique` +note: required because it appears within the type `std::ptr::Unique` --> $SRC_DIR/core/src/ptr/unique.rs:LL:COL note: required because it appears within the type `Box` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL diff --git a/tests/ui/traits/negative-impls/negated-auto-traits-error.stderr b/tests/ui/traits/negative-impls/negated-auto-traits-error.stderr index f450f786f608..b7d8484e1041 100644 --- a/tests/ui/traits/negative-impls/negated-auto-traits-error.stderr +++ b/tests/ui/traits/negative-impls/negated-auto-traits-error.stderr @@ -77,12 +77,12 @@ error[E0277]: `dummy2::TestType` cannot be sent between threads safely --> $DIR/negated-auto-traits-error.rs:48:13 | LL | is_send(Box::new(TestType)); - | ------- ^^^^^^^^^^^^^^^^^^ the trait `Send` is not implemented for `Unique` + | ------- ^^^^^^^^^^^^^^^^^^ the trait `Send` is not implemented for `std::ptr::Unique` | | | required by a bound introduced by this call | - = note: the trait bound `Unique: Send` is not satisfied - = note: required for `Unique` to implement `Send` + = note: the trait bound `std::ptr::Unique: Send` is not satisfied + = note: required for `std::ptr::Unique` to implement `Send` note: required because it appears within the type `Box` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL note: required by a bound in `is_send` @@ -113,7 +113,7 @@ note: required because it appears within the type `Outer2` | LL | struct Outer2(T); | ^^^^^^ - = note: required for `Unique>` to implement `Send` + = note: required for `std::ptr::Unique>` to implement `Send` note: required because it appears within the type `Box>` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL note: required by a bound in `is_send` diff --git a/tests/ui/trimmed-paths/core-unicode.rs b/tests/ui/trimmed-paths/core-unicode.rs index 54bde92a5335..4a3eeca62970 100644 --- a/tests/ui/trimmed-paths/core-unicode.rs +++ b/tests/ui/trimmed-paths/core-unicode.rs @@ -14,6 +14,6 @@ fn main() { let PhantomData::<(inner::unicode, u32)> = PhantomData::<(u32, inner::unicode)>; //~^ ERROR mismatched types [E0308] //~| NOTE expected `PhantomData<(u32, unicode)>`, found `PhantomData<(unicode, u32)>` - //~| NOTE this expression has type `PhantomData<(u32, inner::unicode)>` - //~| NOTE expected struct `PhantomData<(u32, inner::unicode)>` + //~| NOTE this expression has type `PhantomData<(u32, unicode)>` + //~| NOTE expected struct `PhantomData<(u32, unicode)>` } diff --git a/tests/ui/trimmed-paths/core-unicode.stderr b/tests/ui/trimmed-paths/core-unicode.stderr index 9023200d1c92..7351896b0b54 100644 --- a/tests/ui/trimmed-paths/core-unicode.stderr +++ b/tests/ui/trimmed-paths/core-unicode.stderr @@ -2,12 +2,12 @@ error[E0308]: mismatched types --> $DIR/core-unicode.rs:14:9 | LL | let PhantomData::<(inner::unicode, u32)> = PhantomData::<(u32, inner::unicode)>; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ------------------------------------ this expression has type `PhantomData<(u32, inner::unicode)>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ------------------------------------ this expression has type `PhantomData<(u32, unicode)>` | | | expected `PhantomData<(u32, unicode)>`, found `PhantomData<(unicode, u32)>` | - = note: expected struct `PhantomData<(u32, inner::unicode)>` - found struct `PhantomData<(inner::unicode, u32)>` + = note: expected struct `PhantomData<(u32, unicode)>` + found struct `PhantomData<(unicode, u32)>` error: aborting due to 1 previous error diff --git a/tests/ui/trimmed-paths/doc-hidden.rs b/tests/ui/trimmed-paths/doc-hidden.rs index b73d04c3c6ae..c3125385c7e4 100644 --- a/tests/ui/trimmed-paths/doc-hidden.rs +++ b/tests/ui/trimmed-paths/doc-hidden.rs @@ -45,7 +45,7 @@ fn uses_local() { ) = 3u32; //~^ ERROR mismatched types [E0308] //~| NOTE expected `(ActuallyPub, ..., ..., ..., ..., ...)`, found `u32` - //~| NOTE expected tuple `(local::ActuallyPub, local::DocHidden, local::pub_mod::ActuallyPubInPubMod, local::pub_mod::DocHiddenInPubMod, local::hidden_mod::ActuallyPubInHiddenMod, local::hidden_mod::DocHiddenInHiddenMod)` + //~| NOTE expected tuple `(local::ActuallyPub, DocHidden, local::pub_mod::ActuallyPubInPubMod, DocHiddenInPubMod, ActuallyPubInHiddenMod, DocHiddenInHiddenMod)` } fn uses_helper() { diff --git a/tests/ui/trimmed-paths/doc-hidden.stderr b/tests/ui/trimmed-paths/doc-hidden.stderr index 6f6f8f21fbe0..167c92c50a35 100644 --- a/tests/ui/trimmed-paths/doc-hidden.stderr +++ b/tests/ui/trimmed-paths/doc-hidden.stderr @@ -13,7 +13,7 @@ LL | | ) = 3u32; | |_____| | expected due to this | - = note: expected tuple `(local::ActuallyPub, local::DocHidden, local::pub_mod::ActuallyPubInPubMod, local::pub_mod::DocHiddenInPubMod, local::hidden_mod::ActuallyPubInHiddenMod, local::hidden_mod::DocHiddenInHiddenMod)` + = note: expected tuple `(local::ActuallyPub, DocHidden, local::pub_mod::ActuallyPubInPubMod, DocHiddenInPubMod, ActuallyPubInHiddenMod, DocHiddenInHiddenMod)` found type `u32` error[E0308]: mismatched types diff --git a/tests/ui/type-inference/panic-with-unspecified-type.stderr b/tests/ui/type-inference/panic-with-unspecified-type.stderr index 5f08a7552632..cd8485f392bc 100644 --- a/tests/ui/type-inference/panic-with-unspecified-type.stderr +++ b/tests/ui/type-inference/panic-with-unspecified-type.stderr @@ -8,7 +8,7 @@ LL | panic!(std::default::Default::default()); | required by a bound introduced by this call | = note: cannot satisfy `_: Any` -note: required by a bound in `begin_panic` +note: required by a bound in `std::rt::begin_panic` --> $SRC_DIR/std/src/panicking.rs:LL:COL error: aborting due to 1 previous error diff --git a/tests/ui/type/pattern_types/derives_fail.stderr b/tests/ui/type/pattern_types/derives_fail.stderr index 6b2e27494f0e..45c9bae1f280 100644 --- a/tests/ui/type/pattern_types/derives_fail.stderr +++ b/tests/ui/type/pattern_types/derives_fail.stderr @@ -16,7 +16,7 @@ LL | #[repr(transparent)] LL | struct Nanoseconds(NanoI32); | ^^^^^^^ the trait `Eq` is not implemented for `(i32) is 0..=999999999` | -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL error[E0277]: `(i32) is 0..=999999999` doesn't implement `Debug` diff --git a/tests/ui/union/union-derive-clone.stderr b/tests/ui/union/union-derive-clone.stderr index 679ab6a38e49..18f862aaa7d6 100644 --- a/tests/ui/union/union-derive-clone.stderr +++ b/tests/ui/union/union-derive-clone.stderr @@ -4,7 +4,7 @@ error[E0277]: the trait bound `U1: Copy` is not satisfied LL | #[derive(Clone)] | ^^^^^ the trait `Copy` is not implemented for `U1` | -note: required by a bound in `AssertParamIsCopy` +note: required by a bound in `std::clone::AssertParamIsCopy` --> $SRC_DIR/core/src/clone.rs:LL:COL help: consider annotating `U1` with `#[derive(Copy)]` | diff --git a/tests/ui/union/union-derive-eq.current.stderr b/tests/ui/union/union-derive-eq.current.stderr index a0339687dad4..df8e6db887bc 100644 --- a/tests/ui/union/union-derive-eq.current.stderr +++ b/tests/ui/union/union-derive-eq.current.stderr @@ -7,7 +7,7 @@ LL | union U2 { LL | a: PartialEqNotEq, | ^^^^^^^^^^^^^^^^^ the trait `Eq` is not implemented for `PartialEqNotEq` | -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL help: consider annotating `PartialEqNotEq` with `#[derive(Eq)]` | diff --git a/tests/ui/union/union-derive-eq.next.stderr b/tests/ui/union/union-derive-eq.next.stderr index a0339687dad4..df8e6db887bc 100644 --- a/tests/ui/union/union-derive-eq.next.stderr +++ b/tests/ui/union/union-derive-eq.next.stderr @@ -7,7 +7,7 @@ LL | union U2 { LL | a: PartialEqNotEq, | ^^^^^^^^^^^^^^^^^ the trait `Eq` is not implemented for `PartialEqNotEq` | -note: required by a bound in `AssertParamIsEq` +note: required by a bound in `std::cmp::AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL help: consider annotating `PartialEqNotEq` with `#[derive(Eq)]` | From 40691d0ca6a20bae367533fb2b58320251b4ad17 Mon Sep 17 00:00:00 2001 From: tiif Date: Mon, 19 Jan 2026 01:46:08 +0000 Subject: [PATCH 123/146] Add myself to the review rotation --- triagebot.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/triagebot.toml b/triagebot.toml index e51622f1e5a9..a25c2a0a388c 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1465,6 +1465,7 @@ compiler = [ "@oli-obk", "@petrochenkov", "@SparrowLii", + "@tiif", "@WaffleLapkin", "@wesleywiser", ] From 37135122179974e9073f4a885b70044cedfa3f80 Mon Sep 17 00:00:00 2001 From: mu001999 Date: Sat, 17 Jan 2026 22:53:08 +0800 Subject: [PATCH 124/146] Parse ident with allowing recovery when trying to recover in diagnosing --- .../rustc_parse/src/parser/diagnostics.rs | 2 +- compiler/rustc_parse/src/parser/item.rs | 3 +- compiler/rustc_parse/src/parser/mod.rs | 2 +- .../kw-in-const-item-pos-recovery-149692.rs | 3 +- ...w-in-const-item-pos-recovery-149692.stderr | 19 ++++++-- .../macro/kw-in-item-pos-recovery-149692.rs | 9 ++-- .../kw-in-item-pos-recovery-149692.stderr | 48 +++++++++++++++---- .../macro/kw-in-item-pos-recovery-151238.rs | 13 +++++ .../kw-in-item-pos-recovery-151238.stderr | 25 ++++++++++ 9 files changed, 102 insertions(+), 22 deletions(-) create mode 100644 tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs create mode 100644 tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 2fd1d146b1f6..60e12fa05adf 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -2264,7 +2264,7 @@ impl<'a> Parser<'a> { && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseParen) { // `fn foo(String s) {}` - let ident = self.parse_ident().unwrap(); + let ident = self.parse_ident_common(true).unwrap(); let span = pat.span.with_hi(ident.span.hi()); err.span_suggestion( diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index bc76418429aa..c7d09b834540 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -408,12 +408,11 @@ impl<'a> Parser<'a> { let insert_span = ident_span.shrink_to_lo(); let ident = if self.token.is_ident() - && self.token.is_non_reserved_ident() && (!is_const || self.look_ahead(1, |t| *t == token::OpenParen)) && self.look_ahead(1, |t| { matches!(t.kind, token::Lt | token::OpenBrace | token::OpenParen) }) { - self.parse_ident().unwrap() + self.parse_ident_common(true).unwrap() } else { return Ok(()); }; diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index d6e99bc540f7..c39e8351f0bd 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -469,7 +469,7 @@ impl<'a> Parser<'a> { self.parse_ident_common(self.may_recover()) } - fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { + pub(crate) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { let (ident, is_raw) = self.ident_or_err(recover)?; if is_raw == IdentIsRaw::No && ident.is_reserved() { diff --git a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs index 58bb62bc4bf8..8619856cad67 100644 --- a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs +++ b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs @@ -6,6 +6,7 @@ macro_rules! m { } m!(const Self()); -//~^ ERROR expected one of `!` or `::`, found `(` +//~^ ERROR expected identifier, found keyword `Self` +//~^^ ERROR missing `fn` or `struct` for function or struct definition fn main() {} diff --git a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr index f9b73109dbb4..d412c59c4372 100644 --- a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr +++ b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr @@ -1,11 +1,22 @@ -error: expected one of `!` or `::`, found `(` - --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:14 +error: expected identifier, found keyword `Self` + --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:10 + | +LL | m!(const Self()); + | ^^^^ expected identifier, found keyword + +error: missing `fn` or `struct` for function or struct definition + --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:10 | LL | (const $id:item()) => {} | -------- while parsing argument for this `item` macro fragment ... LL | m!(const Self()); - | ^ expected one of `!` or `::` + | ^^^^ + | +help: if you meant to call a macro, try + | +LL | m!(const Self!()); + | + -error: aborting due to 1 previous error +error: aborting due to 2 previous errors diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs index 223864e33296..77372ced09c4 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs @@ -8,12 +8,15 @@ macro_rules! m { } m!(Self()); -//~^ ERROR expected one of `!` or `::`, found `(` +//~^ ERROR expected identifier, found keyword `Self` +//~^^ ERROR missing `fn` or `struct` for function or struct definition m!(Self{}); -//~^ ERROR expected one of `!` or `::`, found `{` +//~^ ERROR expected identifier, found keyword `Self` +//~^^ ERROR missing `enum` or `struct` for enum or struct definition m!(crate()); -//~^ ERROR expected one of `!` or `::`, found `(` +//~^ ERROR expected identifier, found keyword `crate` +//~^^ ERROR missing `fn` or `struct` for function or struct definition fn main() {} diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr index a65214b0d1f9..39f3e2d3a9ea 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr @@ -1,29 +1,57 @@ -error: expected one of `!` or `::`, found `(` - --> $DIR/kw-in-item-pos-recovery-149692.rs:10:8 +error: expected identifier, found keyword `Self` + --> $DIR/kw-in-item-pos-recovery-149692.rs:10:4 + | +LL | m!(Self()); + | ^^^^ expected identifier, found keyword + +error: missing `fn` or `struct` for function or struct definition + --> $DIR/kw-in-item-pos-recovery-149692.rs:10:4 | LL | ($id:item()) => {} | -------- while parsing argument for this `item` macro fragment ... LL | m!(Self()); - | ^ expected one of `!` or `::` + | ^^^^ + | +help: if you meant to call a macro, try + | +LL | m!(Self!()); + | + -error: expected one of `!` or `::`, found `{` - --> $DIR/kw-in-item-pos-recovery-149692.rs:13:8 +error: expected identifier, found keyword `Self` + --> $DIR/kw-in-item-pos-recovery-149692.rs:14:4 + | +LL | m!(Self{}); + | ^^^^ expected identifier, found keyword + +error: missing `enum` or `struct` for enum or struct definition + --> $DIR/kw-in-item-pos-recovery-149692.rs:14:4 | LL | ($id:item()) => {} | -------- while parsing argument for this `item` macro fragment ... LL | m!(Self{}); - | ^ expected one of `!` or `::` + | ^^^^ -error: expected one of `!` or `::`, found `(` - --> $DIR/kw-in-item-pos-recovery-149692.rs:16:9 +error: expected identifier, found keyword `crate` + --> $DIR/kw-in-item-pos-recovery-149692.rs:18:4 + | +LL | m!(crate()); + | ^^^^^ expected identifier, found keyword + +error: missing `fn` or `struct` for function or struct definition + --> $DIR/kw-in-item-pos-recovery-149692.rs:18:4 | LL | ($id:item()) => {} | -------- while parsing argument for this `item` macro fragment ... LL | m!(crate()); - | ^ expected one of `!` or `::` + | ^^^^^ + | +help: if you meant to call a macro, try + | +LL | m!(crate!()); + | + -error: aborting due to 3 previous errors +error: aborting due to 6 previous errors diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs new file mode 100644 index 000000000000..bd1785ba5b3c --- /dev/null +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs @@ -0,0 +1,13 @@ +//@ edition: 2021 + +macro_rules! x { + ($ty : item) => {}; +} +x! { + trait MyTrait { fn bar(c self) } + //~^ ERROR expected identifier, found keyword `self` + //~^^ ERROR expected one of `:`, `@`, or `|`, found keyword `self` + //~^^^ ERROR expected one of `->`, `;`, `where`, or `{`, found `}` +} + +fn main() {} diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr new file mode 100644 index 000000000000..81151edaf0c0 --- /dev/null +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr @@ -0,0 +1,25 @@ +error: expected identifier, found keyword `self` + --> $DIR/kw-in-item-pos-recovery-151238.rs:7:28 + | +LL | trait MyTrait { fn bar(c self) } + | ^^^^ expected identifier, found keyword + +error: expected one of `:`, `@`, or `|`, found keyword `self` + --> $DIR/kw-in-item-pos-recovery-151238.rs:7:28 + | +LL | trait MyTrait { fn bar(c self) } + | --^^^^ + | | | + | | expected one of `:`, `@`, or `|` + | help: declare the type after the parameter binding: `: ` + +error: expected one of `->`, `;`, `where`, or `{`, found `}` + --> $DIR/kw-in-item-pos-recovery-151238.rs:7:34 + | +LL | trait MyTrait { fn bar(c self) } + | --- ^ expected one of `->`, `;`, `where`, or `{` + | | + | while parsing this `fn` + +error: aborting due to 3 previous errors + From 0895c4cbe6ff960b23626a538d1691d2ebf51311 Mon Sep 17 00:00:00 2001 From: Jamie Hill-Daniel Date: Mon, 19 Jan 2026 04:48:23 +0000 Subject: [PATCH 125/146] ci: Move lockfile updates to a script --- .github/workflows/dependencies.yml | 16 +++------------- src/tools/update-lockfile.sh | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 13 deletions(-) create mode 100755 src/tools/update-lockfile.sh diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml index 80ffd67e04e1..7c721c7abeaa 100644 --- a/.github/workflows/dependencies.yml +++ b/.github/workflows/dependencies.yml @@ -62,19 +62,9 @@ jobs: rustup toolchain install --no-self-update --profile minimal $TOOLCHAIN rustup default $TOOLCHAIN - - name: cargo update compiler & tools - # Remove first line that always just says "Updating crates.io index" - run: | - echo -e "\ncompiler & tools dependencies:" >> cargo_update.log - cargo update 2>&1 | sed '/crates.io index/d' | tee -a cargo_update.log - - name: cargo update library - run: | - echo -e "\nlibrary dependencies:" >> cargo_update.log - cargo update --manifest-path library/Cargo.toml 2>&1 | sed '/crates.io index/d' | tee -a cargo_update.log - - name: cargo update rustbook - run: | - echo -e "\nrustbook dependencies:" >> cargo_update.log - cargo update --manifest-path src/tools/rustbook/Cargo.toml 2>&1 | sed '/crates.io index/d' | tee -a cargo_update.log + - name: cargo update + run: ./src/tools/update-lockfile.sh + - name: upload Cargo.lock artifact for use in PR uses: actions/upload-artifact@v4 with: diff --git a/src/tools/update-lockfile.sh b/src/tools/update-lockfile.sh new file mode 100755 index 000000000000..a968d83d8152 --- /dev/null +++ b/src/tools/update-lockfile.sh @@ -0,0 +1,18 @@ +#!/bin/sh + +# Updates the workspaces in `.`, `library` and `src/tools/rustbook` +# Logs are written to `cargo_update.log` +# Used as part of regular dependency bumps + +set -euo pipefail + +echo -e "\ncompiler & tools dependencies:" > cargo_update.log +# Remove first line that always just says "Updating crates.io index" +cargo update 2>&1 | sed '/crates.io index/d' | \ + tee -a cargo_update.log +echo -e "\nlibrary dependencies:" >> cargo_update.log +cargo update --manifest-path library/Cargo.toml 2>&1 | sed '/crates.io index/d' | \ + tee -a cargo_update.log +echo -e "\nrustbook dependencies:" >> cargo_update.log +cargo update --manifest-path src/tools/rustbook/Cargo.toml 2>&1 | sed '/crates.io index/d' | \ + tee -a cargo_update.log From 7ec34defe9e62a1a6946d3e700b5903d8dc89ece Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 19 Jan 2026 14:46:38 +1100 Subject: [PATCH 126/146] Temporarily re-export `assert_matches!` to reduce stabilization churn --- compiler/rustc_abi/src/extern_abi/tests.rs | 3 ++- compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs | 3 +-- compiler/rustc_borrowck/src/type_check/input_output.rs | 3 +-- compiler/rustc_builtin_macros/src/test.rs | 2 +- compiler/rustc_codegen_llvm/src/asm.rs | 3 +-- compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs | 2 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 2 +- compiler/rustc_codegen_ssa/src/back/write.rs | 2 +- compiler/rustc_codegen_ssa/src/traits/builder.rs | 2 +- compiler/rustc_const_eval/src/check_consts/check.rs | 2 +- compiler/rustc_const_eval/src/interpret/call.rs | 2 +- compiler/rustc_const_eval/src/interpret/cast.rs | 3 +-- compiler/rustc_const_eval/src/interpret/eval_context.rs | 3 +-- compiler/rustc_const_eval/src/interpret/intrinsics.rs | 3 +-- compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs | 3 ++- compiler/rustc_const_eval/src/interpret/memory.rs | 2 +- compiler/rustc_const_eval/src/interpret/operand.rs | 3 +-- compiler/rustc_const_eval/src/interpret/place.rs | 3 +-- compiler/rustc_data_structures/src/graph/scc/mod.rs | 2 +- compiler/rustc_data_structures/src/lib.rs | 5 +++++ compiler/rustc_errors/src/lib.rs | 3 +-- compiler/rustc_hir_analysis/src/collect.rs | 2 +- compiler/rustc_hir_analysis/src/collect/generics_of.rs | 2 +- compiler/rustc_hir_analysis/src/collect/predicates_of.rs | 3 +-- compiler/rustc_hir_analysis/src/delegation.rs | 3 +-- compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs | 2 +- compiler/rustc_hir_analysis/src/impl_wf_check.rs | 3 +-- compiler/rustc_hir_typeck/src/method/probe.rs | 2 +- compiler/rustc_infer/src/infer/outlives/verify.rs | 3 +-- compiler/rustc_infer/src/infer/snapshot/undo_log.rs | 3 +-- compiler/rustc_lint/src/impl_trait_overcaptures.rs | 2 +- compiler/rustc_middle/src/ty/consts/kind.rs | 3 +-- compiler/rustc_middle/src/ty/context.rs | 3 +-- compiler/rustc_middle/src/ty/instance.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 2 +- compiler/rustc_middle/src/ty/sty.rs | 2 +- compiler/rustc_mir_build/src/builder/coverageinfo.rs | 2 +- compiler/rustc_mir_build/src/builder/expr/as_place.rs | 2 +- compiler/rustc_mir_build/src/builder/matches/mod.rs | 2 +- compiler/rustc_mir_build/src/builder/matches/user_ty.rs | 2 +- compiler/rustc_mir_build/src/thir/pattern/mod.rs | 2 +- compiler/rustc_mir_build/src/thir/util.rs | 3 +-- compiler/rustc_mir_dataflow/src/impls/initialized.rs | 3 +-- compiler/rustc_mir_dataflow/src/value_analysis.rs | 2 +- compiler/rustc_mir_transform/src/dataflow_const_prop.rs | 2 +- compiler/rustc_mir_transform/src/inline.rs | 2 +- compiler/rustc_mir_transform/src/promote_consts.rs | 2 +- compiler/rustc_mir_transform/src/shim.rs | 2 +- compiler/rustc_parse/src/parser/mod.rs | 2 +- compiler/rustc_parse/src/parser/tests.rs | 2 +- compiler/rustc_query_system/src/dep_graph/graph.rs | 3 +-- compiler/rustc_resolve/src/late.rs | 2 +- compiler/rustc_symbol_mangling/src/export.rs | 3 +-- .../src/error_reporting/traits/suggestions.rs | 2 +- compiler/rustc_trait_selection/src/solve/inspect/analyse.rs | 3 +-- compiler/rustc_trait_selection/src/traits/select/mod.rs | 2 +- compiler/rustc_ty_utils/src/abi.rs | 2 +- compiler/rustc_ty_utils/src/layout/invariant.rs | 3 +-- 58 files changed, 64 insertions(+), 79 deletions(-) diff --git a/compiler/rustc_abi/src/extern_abi/tests.rs b/compiler/rustc_abi/src/extern_abi/tests.rs index fc546a6570f0..8b9353ccae97 100644 --- a/compiler/rustc_abi/src/extern_abi/tests.rs +++ b/compiler/rustc_abi/src/extern_abi/tests.rs @@ -1,6 +1,7 @@ -use std::assert_matches::assert_matches; use std::str::FromStr; +use rustc_data_structures::assert_matches; + use super::*; #[allow(non_snake_case)] diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index 743a28822eb9..8f643d8f460f 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -3,8 +3,7 @@ #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::untranslatable_diagnostic)] -use std::assert_matches::assert_matches; - +use rustc_data_structures::assert_matches; use rustc_errors::{Applicability, Diag, EmissionGuarantee}; use rustc_hir as hir; use rustc_hir::intravisit::Visitor; diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index eb31b5de05d2..f3b9dcc90a84 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -7,9 +7,8 @@ //! `RETURN_PLACE` the MIR arguments) are always fully normalized (and //! contain revealed `impl Trait` values). -use std::assert_matches::assert_matches; - use itertools::Itertools; +use rustc_data_structures::assert_matches; use rustc_hir as hir; use rustc_infer::infer::{BoundRegionConversionTime, RegionVariableOrigin}; use rustc_middle::mir::*; diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 6f14385d5d30..d5f774865a9e 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -1,12 +1,12 @@ //! The expansion from a test function to the appropriate test struct for libtest //! Ideally, this code would be in libtest but for efficiency and error messages it lives here. -use std::assert_matches::assert_matches; use std::iter; use rustc_ast::{self as ast, GenericParamKind, HasNodeId, attr, join_path_idents}; use rustc_ast_pretty::pprust; use rustc_attr_parsing::AttributeParser; +use rustc_data_structures::assert_matches; use rustc_errors::{Applicability, Diag, Level}; use rustc_expand::base::*; use rustc_hir::Attribute; diff --git a/compiler/rustc_codegen_llvm/src/asm.rs b/compiler/rustc_codegen_llvm/src/asm.rs index ee1b6d45e149..7f02518d6c0d 100644 --- a/compiler/rustc_codegen_llvm/src/asm.rs +++ b/compiler/rustc_codegen_llvm/src/asm.rs @@ -1,9 +1,8 @@ -use std::assert_matches::assert_matches; - use rustc_abi::{BackendRepr, Float, Integer, Primitive, Scalar}; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_codegen_ssa::mir::operand::OperandValue; use rustc_codegen_ssa::traits::*; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxHashMap; use rustc_middle::ty::Instance; use rustc_middle::ty::layout::TyAndLayout; diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index a728f3ea1e66..b27b1a88f133 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -1,9 +1,9 @@ -use std::assert_matches::assert_matches; use std::sync::Arc; use itertools::Itertools; use rustc_abi::Align; use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, ConstCodegenMethods}; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxIndexMap; use rustc_index::IndexVec; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index c6aae89f1e51..565db7d298bc 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -1,4 +1,3 @@ -use std::assert_matches::assert_matches; use std::cmp::Ordering; use std::ffi::c_uint; use std::ptr; @@ -13,6 +12,7 @@ use rustc_codegen_ssa::errors::{ExpectedPointerMutability, InvalidMonomorphizati use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue}; use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue}; use rustc_codegen_ssa::traits::*; +use rustc_data_structures::assert_matches; use rustc_hir::def_id::LOCAL_CRATE; use rustc_hir::{self as hir}; use rustc_middle::mir::BinOp; diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 3e36bd8552b1..53121fc6275b 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -1,4 +1,3 @@ -use std::assert_matches::assert_matches; use std::marker::PhantomData; use std::panic::AssertUnwindSafe; use std::path::{Path, PathBuf}; @@ -8,6 +7,7 @@ use std::{fs, io, mem, str, thread}; use rustc_abi::Size; use rustc_ast::attr; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::jobserver::{self, Acquired}; use rustc_data_structures::memmap::Mmap; diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 4f45c614e003..ba36188f05d1 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -1,7 +1,7 @@ -use std::assert_matches::assert_matches; use std::ops::Deref; use rustc_abi::{Align, Scalar, Size, WrappingRange}; +use rustc_data_structures::assert_matches; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::mir; use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout}; diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 3a85ca3760d2..95dbf42d4d44 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -1,11 +1,11 @@ //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations. -use std::assert_matches::assert_matches; use std::borrow::Cow; use std::mem; use std::num::NonZero; use std::ops::Deref; +use rustc_data_structures::assert_matches; use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 94c6fd1b3238..9c8ca44c5e8f 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -1,10 +1,10 @@ //! Manages calling a concrete function (with known MIR body) with argument passing, //! and returning the return value to the caller. -use std::assert_matches::assert_matches; use std::borrow::Cow; use either::{Left, Right}; use rustc_abi::{self as abi, ExternAbi, FieldIdx, Integer, VariantIdx}; +use rustc_data_structures::assert_matches; use rustc_hir::def_id::DefId; use rustc_middle::ty::layout::{IntegerExt, TyAndLayout}; use rustc_middle::ty::{self, AdtDef, Instance, Ty, VariantDef}; diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index 3485a5c625ba..43de2e7f078a 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -1,8 +1,7 @@ -use std::assert_matches::assert_matches; - use rustc_abi::{FieldIdx, Integer}; use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::{Float, FloatConvert}; +use rustc_data_structures::assert_matches; use rustc_middle::mir::CastKind; use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar}; use rustc_middle::ty::adjustment::PointerCoercion; diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index d23369caffa4..aeadf0257ea8 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -1,7 +1,6 @@ -use std::assert_matches::debug_assert_matches; - use either::{Left, Right}; use rustc_abi::{Align, HasDataLayout, Size, TargetDataLayout}; +use rustc_data_structures::debug_assert_matches; use rustc_errors::DiagCtxtHandle; use rustc_hir::def_id::DefId; use rustc_hir::limit::Limit; diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index fe1dd1b6eb35..e526f6120689 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -4,10 +4,9 @@ mod simd; -use std::assert_matches::assert_matches; - use rustc_abi::{FIRST_VARIANT, FieldIdx, HasDataLayout, Size, VariantIdx}; use rustc_apfloat::ieee::{Double, Half, Quad, Single}; +use rustc_data_structures::assert_matches; use rustc_hir::def_id::CRATE_DEF_ID; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint}; diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs index 33a115384a88..d7fe7801fb08 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs @@ -2,6 +2,7 @@ use either::Either; use rustc_abi::{BackendRepr, Endian}; use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::{Float, Round}; +use rustc_data_structures::assert_matches; use rustc_middle::mir::interpret::{InterpErrorKind, Pointer, UndefinedBehaviorInfo}; use rustc_middle::ty::{FloatTy, ScalarInt, SimdAlign}; use rustc_middle::{bug, err_ub_format, mir, span_bug, throw_unsup_format, ty}; @@ -10,7 +11,7 @@ use tracing::trace; use super::{ ImmTy, InterpCx, InterpResult, Machine, MinMax, MulAddType, OpTy, PlaceTy, Provenance, Scalar, - Size, TyAndLayout, assert_matches, interp_ok, throw_ub_format, + Size, TyAndLayout, interp_ok, throw_ub_format, }; use crate::interpret::Writeable; diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 862fe4779080..a6c8b28cce9f 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -6,7 +6,6 @@ //! integer. It is crucial that these operations call `check_align` *before* //! short-circuiting the empty case! -use std::assert_matches::assert_matches; use std::borrow::{Borrow, Cow}; use std::cell::Cell; use std::collections::VecDeque; @@ -14,6 +13,7 @@ use std::{fmt, ptr}; use rustc_abi::{Align, HasDataLayout, Size}; use rustc_ast::Mutability; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_middle::mir::display_allocation; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 9a956259ba57..e8e77de8eb3e 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -1,11 +1,10 @@ //! Functions concerning immediate values and operands, and reading from operands. //! All high-level functions to read from memory work on operands as sources. -use std::assert_matches::assert_matches; - use either::{Either, Left, Right}; use rustc_abi as abi; use rustc_abi::{BackendRepr, HasDataLayout, Size}; +use rustc_data_structures::assert_matches; use rustc_hir::def::Namespace; use rustc_middle::mir::interpret::ScalarSizeMismatch; use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, TyAndLayout}; diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index a409c7fad417..d472c14253b5 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -2,10 +2,9 @@ //! into a place. //! All high-level functions to write to memory work on places as destinations. -use std::assert_matches::assert_matches; - use either::{Either, Left, Right}; use rustc_abi::{BackendRepr, HasDataLayout, Size}; +use rustc_data_structures::assert_matches; use rustc_middle::ty::Ty; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::{bug, mir, span_bug}; diff --git a/compiler/rustc_data_structures/src/graph/scc/mod.rs b/compiler/rustc_data_structures/src/graph/scc/mod.rs index 1882e6e835a4..91cbe3c533bb 100644 --- a/compiler/rustc_data_structures/src/graph/scc/mod.rs +++ b/compiler/rustc_data_structures/src/graph/scc/mod.rs @@ -8,7 +8,6 @@ //! Typical examples would include: minimum element in SCC, maximum element //! reachable from it, etc. -use std::assert_matches::debug_assert_matches; use std::fmt::Debug; use std::marker::PhantomData; use std::ops::Range; @@ -16,6 +15,7 @@ use std::ops::Range; use rustc_index::{Idx, IndexSlice, IndexVec}; use tracing::{debug, instrument, trace}; +use crate::debug_assert_matches; use crate::fx::FxHashSet; use crate::graph::vec_graph::VecGraph; use crate::graph::{DirectedGraph, NumEdges, Successors}; diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index ff1dd41c82cc..8377213850b8 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -38,6 +38,11 @@ #![feature(unwrap_infallible)] // tidy-alphabetical-end +// Temporarily re-export `assert_matches!`, so that the rest of the compiler doesn't +// have to worry about it being moved to a different module in std during stabilization. +// FIXME(#151359): Remove this when `feature(assert_matches)` is stable in stage0. +// (This doesn't necessarily need to be fixed during the beta bump itself.) +pub use std::assert_matches::{assert_matches, debug_assert_matches}; use std::fmt; pub use atomic_ref::AtomicRef; diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 148368045f4f..ce40f3ae8bf8 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -23,7 +23,6 @@ extern crate self as rustc_errors; -use std::assert_matches::assert_matches; use std::backtrace::{Backtrace, BacktraceStatus}; use std::borrow::Cow; use std::cell::Cell; @@ -55,10 +54,10 @@ pub use diagnostic_impls::{ }; pub use emitter::ColorConfig; use emitter::{ConfusionType, DynEmitter, Emitter, detect_confusion_type, is_different}; -use rustc_data_structures::AtomicRef; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::stable_hasher::StableHasher; use rustc_data_structures::sync::{DynSend, Lock}; +use rustc_data_structures::{AtomicRef, assert_matches}; pub use rustc_error_messages::{ DiagArg, DiagArgFromDisplay, DiagArgName, DiagArgValue, DiagMessage, FluentBundle, IntoDiagArg, LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagMessage, diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 2c0253409387..9c0b638c1482 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -14,13 +14,13 @@ //! At present, however, we do run collection across all items in the //! crate as a kind of pass. This should eventually be factored away. -use std::assert_matches::assert_matches; use std::cell::Cell; use std::iter; use std::ops::Bound; use rustc_abi::{ExternAbi, Size}; use rustc_ast::Recovered; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::{ Applicability, Diag, DiagCtxtHandle, E0228, ErrorGuaranteed, StashKey, struct_span_code_err, diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 3d2f0466cad0..511d513216eb 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -1,6 +1,6 @@ -use std::assert_matches::assert_matches; use std::ops::ControlFlow; +use rustc_data_structures::assert_matches; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor, VisitorExt}; diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 178c47b09c84..a2236b426305 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -1,6 +1,5 @@ -use std::assert_matches::assert_matches; - use hir::Node; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; use rustc_hir::attrs::AttributeKind; diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs index cf0533c39e73..f64341d755f8 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -2,8 +2,7 @@ //! //! For more information about delegation design, see the tracking issue #118212. -use std::assert_matches::debug_assert_matches; - +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; 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 6e1e6c157a91..924967b65c19 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -19,10 +19,10 @@ mod dyn_trait; pub mod errors; pub mod generics; -use std::assert_matches::assert_matches; use std::slice; use rustc_ast::LitKind; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_errors::codes::*; use rustc_errors::{ diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check.rs b/compiler/rustc_hir_analysis/src/impl_wf_check.rs index cadbc54c3410..f5c77c680000 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check.rs @@ -8,9 +8,8 @@ //! specialization errors. These things can (and probably should) be //! fixed, but for the moment it's easier to do these checks early. -use std::assert_matches::debug_assert_matches; - use min_specialization::check_min_specialization; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_errors::codes::*; diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index beb0337d8c59..ed71ad2119c9 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1,8 +1,8 @@ -use std::assert_matches::debug_assert_matches; use std::cell::{Cell, RefCell}; use std::cmp::max; use std::ops::Deref; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::sso::SsoHashSet; use rustc_errors::Applicability; diff --git a/compiler/rustc_infer/src/infer/outlives/verify.rs b/compiler/rustc_infer/src/infer/outlives/verify.rs index f67b99cb3f84..affeb01e6d05 100644 --- a/compiler/rustc_infer/src/infer/outlives/verify.rs +++ b/compiler/rustc_infer/src/infer/outlives/verify.rs @@ -1,5 +1,4 @@ -use std::assert_matches::assert_matches; - +use rustc_data_structures::assert_matches; use rustc_middle::ty::outlives::{Component, compute_alias_components_recursive}; use rustc_middle::ty::{self, OutlivesPredicate, Ty, TyCtxt}; use smallvec::smallvec; diff --git a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs index c859d64133c4..a6f324b70471 100644 --- a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs +++ b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs @@ -1,8 +1,7 @@ -use std::assert_matches::assert_matches; use std::marker::PhantomData; use rustc_data_structures::undo_log::{Rollback, UndoLogs}; -use rustc_data_structures::{snapshot_vec as sv, unify as ut}; +use rustc_data_structures::{assert_matches, snapshot_vec as sv, unify as ut}; use rustc_middle::ty::{self, OpaqueTypeKey, ProvisionalHiddenType}; use tracing::debug; diff --git a/compiler/rustc_lint/src/impl_trait_overcaptures.rs b/compiler/rustc_lint/src/impl_trait_overcaptures.rs index 2fc9d562dc56..f6c2e5946079 100644 --- a/compiler/rustc_lint/src/impl_trait_overcaptures.rs +++ b/compiler/rustc_lint/src/impl_trait_overcaptures.rs @@ -1,6 +1,6 @@ -use std::assert_matches::debug_assert_matches; use std::cell::LazyCell; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::unord::UnordSet; use rustc_errors::{LintDiagnostic, Subdiagnostic}; diff --git a/compiler/rustc_middle/src/ty/consts/kind.rs b/compiler/rustc_middle/src/ty/consts/kind.rs index b3436550e8e0..c9ccb9bd0b3e 100644 --- a/compiler/rustc_middle/src/ty/consts/kind.rs +++ b/compiler/rustc_middle/src/ty/consts/kind.rs @@ -1,5 +1,4 @@ -use std::assert_matches::assert_matches; - +use rustc_data_structures::assert_matches; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; use super::Const; diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index e9fa3f14358e..a5aead9829f1 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -4,7 +4,6 @@ pub mod tls; -use std::assert_matches::debug_assert_matches; use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; use std::env::VarError; @@ -17,7 +16,6 @@ use std::{fmt, iter, mem}; use rustc_abi::{ExternAbi, FieldIdx, Layout, LayoutData, TargetDataLayout, VariantIdx}; use rustc_ast as ast; -use rustc_data_structures::defer; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; @@ -29,6 +27,7 @@ use rustc_data_structures::steal::Steal; use rustc_data_structures::sync::{ self, DynSend, DynSync, FreezeReadGuard, Lock, RwLock, WorkerLocal, }; +use rustc_data_structures::{debug_assert_matches, defer}; use rustc_errors::{ Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, LintDiagnostic, MultiSpan, }; diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index c27d47fcc0d8..0e9dd7dd169c 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -1,6 +1,6 @@ -use std::assert_matches::assert_matches; use std::fmt; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxHashMap; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 8eee114ead02..ce713dcf42f5 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -11,7 +11,6 @@ #![allow(rustc::usage_of_ty_tykind)] -use std::assert_matches::assert_matches; use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; @@ -31,6 +30,7 @@ use rustc_ast::AttrVec; use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree}; use rustc_ast::node_id::NodeMap; pub use rustc_ast_ir::{Movability, Mutability, try_visit}; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index c282f2211f65..34aca8adb4a0 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -2,12 +2,12 @@ #![allow(rustc::usage_of_ty_tykind)] -use std::assert_matches::debug_assert_matches; use std::borrow::Cow; use std::ops::{ControlFlow, Range}; use hir::def::{CtorKind, DefKind}; use rustc_abi::{FIRST_VARIANT, FieldIdx, ScalableElt, VariantIdx}; +use rustc_data_structures::debug_assert_matches; use rustc_errors::{ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; use rustc_hir::LangItem; diff --git a/compiler/rustc_mir_build/src/builder/coverageinfo.rs b/compiler/rustc_mir_build/src/builder/coverageinfo.rs index 091b9dad5bc1..ae36b2fb7f38 100644 --- a/compiler/rustc_mir_build/src/builder/coverageinfo.rs +++ b/compiler/rustc_mir_build/src/builder/coverageinfo.rs @@ -1,6 +1,6 @@ -use std::assert_matches::assert_matches; use std::collections::hash_map::Entry; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxHashMap; use rustc_middle::mir::coverage::{BlockMarkerId, BranchSpan, CoverageInfoHi, CoverageKind}; use rustc_middle::mir::{self, BasicBlock, SourceInfo, UnOp}; diff --git a/compiler/rustc_mir_build/src/builder/expr/as_place.rs b/compiler/rustc_mir_build/src/builder/expr/as_place.rs index 139c6da29d44..172dbf7c31b5 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_place.rs @@ -1,9 +1,9 @@ //! See docs in build/expr/mod.rs -use std::assert_matches::assert_matches; use std::iter; use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; +use rustc_data_structures::assert_matches; use rustc_hir::def_id::LocalDefId; use rustc_middle::hir::place::{Projection as HirProjection, ProjectionKind as HirProjectionKind}; use rustc_middle::mir::AssertKind::BoundsCheck; diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 11a181cfa8ce..2f9486c2d552 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -5,13 +5,13 @@ //! This also includes code for pattern bindings in `let` statements and //! function parameters. -use std::assert_matches::debug_assert_matches; use std::borrow::Borrow; use std::mem; use std::sync::Arc; use itertools::{Itertools, Position}; use rustc_abi::{FIRST_VARIANT, VariantIdx}; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::{BindingMode, ByRef, LangItem, LetStmt, LocalSource, Node}; diff --git a/compiler/rustc_mir_build/src/builder/matches/user_ty.rs b/compiler/rustc_mir_build/src/builder/matches/user_ty.rs index 2dcfd3772902..6ba5e360ef82 100644 --- a/compiler/rustc_mir_build/src/builder/matches/user_ty.rs +++ b/compiler/rustc_mir_build/src/builder/matches/user_ty.rs @@ -4,10 +4,10 @@ //! This avoids having to repeatedly clone a partly-built [`UserTypeProjections`] //! at every step of the traversal, which is what the previous code was doing. -use std::assert_matches::assert_matches; use std::iter; use rustc_abi::{FieldIdx, VariantIdx}; +use rustc_data_structures::assert_matches; use rustc_data_structures::smallvec::SmallVec; use rustc_middle::mir::{ProjectionElem, UserTypeProjection, UserTypeProjections}; use rustc_middle::ty::{AdtDef, UserTypeAnnotationIndex}; diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 650650cbaac9..d0abb6396145 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -4,11 +4,11 @@ mod check_match; mod const_to_pat; mod migration; -use std::assert_matches::assert_matches; use std::cmp::Ordering; use std::sync::Arc; use rustc_abi::{FieldIdx, Integer}; +use rustc_data_structures::assert_matches; use rustc_errors::codes::*; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::pat_util::EnumerateAndAdjustIterator; diff --git a/compiler/rustc_mir_build/src/thir/util.rs b/compiler/rustc_mir_build/src/thir/util.rs index 457957f5fce9..0093bb762110 100644 --- a/compiler/rustc_mir_build/src/thir/util.rs +++ b/compiler/rustc_mir_build/src/thir/util.rs @@ -1,5 +1,4 @@ -use std::assert_matches::assert_matches; - +use rustc_data_structures::assert_matches; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_middle::bug; diff --git a/compiler/rustc_mir_dataflow/src/impls/initialized.rs b/compiler/rustc_mir_dataflow/src/impls/initialized.rs index 9216106b6edd..6a0881ec2bcb 100644 --- a/compiler/rustc_mir_dataflow/src/impls/initialized.rs +++ b/compiler/rustc_mir_dataflow/src/impls/initialized.rs @@ -1,6 +1,5 @@ -use std::assert_matches::assert_matches; - use rustc_abi::VariantIdx; +use rustc_data_structures::assert_matches; use rustc_index::Idx; use rustc_index::bit_set::{DenseBitSet, MixedBitSet}; use rustc_middle::bug; diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index ac94ee5c8104..f102b7bb50f5 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -1,8 +1,8 @@ -use std::assert_matches::debug_assert_matches; use std::fmt::{Debug, Formatter}; use std::ops::Range; use rustc_abi::{FieldIdx, VariantIdx}; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::{FxHashMap, FxIndexSet, StdEntry}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_index::IndexVec; diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index 5254f60a1503..604f1da1a3ab 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -2,7 +2,6 @@ //! //! Currently, this pass only propagates scalar values. -use std::assert_matches::assert_matches; use std::cell::RefCell; use std::fmt::Formatter; @@ -11,6 +10,7 @@ use rustc_const_eval::const_eval::{DummyMachine, throw_machine_stop_str}; use rustc_const_eval::interpret::{ ImmTy, Immediate, InterpCx, OpTy, PlaceTy, Projectable, interp_ok, }; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::DefKind; use rustc_middle::bug; diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 1e9665f4337d..179ada36be75 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -1,10 +1,10 @@ //! Inlining pass for MIR functions. -use std::assert_matches::debug_assert_matches; use std::iter; use std::ops::{Range, RangeFrom}; use rustc_abi::{ExternAbi, FieldIdx}; +use rustc_data_structures::debug_assert_matches; use rustc_hir::attrs::{InlineAttr, OptimizeAttr}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; diff --git a/compiler/rustc_mir_transform/src/promote_consts.rs b/compiler/rustc_mir_transform/src/promote_consts.rs index 11266ccc2832..2cc8e9d6739c 100644 --- a/compiler/rustc_mir_transform/src/promote_consts.rs +++ b/compiler/rustc_mir_transform/src/promote_consts.rs @@ -10,12 +10,12 @@ //! otherwise silence errors, if move analysis runs after promotion on broken //! MIR. -use std::assert_matches::assert_matches; use std::cell::Cell; use std::{cmp, iter, mem}; use either::{Left, Right}; use rustc_const_eval::check_consts::{ConstCx, qualifs}; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_index::{IndexSlice, IndexVec}; diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 85e340c0a02a..cc1cb3d4f3ff 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -1,7 +1,7 @@ -use std::assert_matches::assert_matches; use std::{fmt, iter}; use rustc_abi::{ExternAbi, FIRST_VARIANT, FieldIdx, VariantIdx}; +use rustc_data_structures::assert_matches; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index d6e99bc540f7..c1ab8d76380a 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -16,7 +16,6 @@ mod ty; pub mod asm; pub mod cfg_select; -use std::assert_matches::debug_assert_matches; use std::{fmt, mem, slice}; use attr_wrapper::{AttrWrapper, UsePreAttrPos}; @@ -40,6 +39,7 @@ use rustc_ast::{ Mutability, Recovered, Safety, StrLit, Visibility, VisibilityKind, }; use rustc_ast_pretty::pprust; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Applicability, Diag, FatalError, MultiSpan, PResult}; use rustc_index::interval::IntervalSet; diff --git a/compiler/rustc_parse/src/parser/tests.rs b/compiler/rustc_parse/src/parser/tests.rs index 62e97c0c308c..2e1acca9e9af 100644 --- a/compiler/rustc_parse/src/parser/tests.rs +++ b/compiler/rustc_parse/src/parser/tests.rs @@ -1,5 +1,4 @@ #![allow(rustc::symbol_intern_string_literal)] -use std::assert_matches::assert_matches; use std::io::prelude::*; use std::iter::Peekable; use std::path::PathBuf; @@ -11,6 +10,7 @@ use rustc_ast::token::{self, Delimiter, Token}; use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; use rustc_ast::{self as ast, PatKind, visit}; use rustc_ast_pretty::pprust::item_to_string; +use rustc_data_structures::assert_matches; use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter; use rustc_errors::emitter::{HumanEmitter, OutputTheme}; use rustc_errors::translation::Translator; diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 0b50d376b552..f32f3f78c04b 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -1,4 +1,3 @@ -use std::assert_matches::assert_matches; use std::fmt::Debug; use std::hash::Hash; use std::marker::PhantomData; @@ -7,12 +6,12 @@ use std::sync::atomic::{AtomicU32, Ordering}; use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_data_structures::outline; use rustc_data_structures::profiling::QueryInvocationId; use rustc_data_structures::sharded::{self, ShardedHashMap}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::{AtomicU64, Lock}; use rustc_data_structures::unord::UnordMap; +use rustc_data_structures::{assert_matches, outline}; use rustc_errors::DiagInner; use rustc_index::IndexVec; use rustc_macros::{Decodable, Encodable}; diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 6557e1dea1a1..963bee369f6b 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -6,7 +6,6 @@ //! If you wonder why there's no `early.rs`, that's because it's split into three files - //! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`. -use std::assert_matches::debug_assert_matches; use std::borrow::Cow; use std::collections::hash_map::Entry; use std::mem::{replace, swap, take}; @@ -16,6 +15,7 @@ use rustc_ast::visit::{ AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list, }; use rustc_ast::*; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::codes::*; diff --git a/compiler/rustc_symbol_mangling/src/export.rs b/compiler/rustc_symbol_mangling/src/export.rs index 3896e06a627b..c99ba1d58f31 100644 --- a/compiler/rustc_symbol_mangling/src/export.rs +++ b/compiler/rustc_symbol_mangling/src/export.rs @@ -1,6 +1,5 @@ -use std::assert_matches::debug_assert_matches; - use rustc_abi::IntegerType; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::stable_hasher::StableHasher; use rustc_hashes::Hash128; use rustc_hir::def::DefKind; 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 ef50dafec950..1c08b5e33142 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -1,12 +1,12 @@ // ignore-tidy-filelength -use std::assert_matches::debug_assert_matches; use std::borrow::Cow; use std::iter; use std::path::PathBuf; use itertools::{EitherOrBoth, Itertools}; use rustc_abi::ExternAbi; +use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::codes::*; diff --git a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs index 944d57bf95d1..ea8360c10b6f 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs @@ -9,8 +9,7 @@ //! coherence right now and was annoying to implement, so I am leaving it //! as is until we start using it for something else. -use std::assert_matches::assert_matches; - +use rustc_data_structures::assert_matches; use rustc_infer::infer::InferCtxt; use rustc_infer::traits::Obligation; use rustc_macros::extension; diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index d6c9adfb2817..787dd4ea6254 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2,13 +2,13 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection -use std::assert_matches::assert_matches; use std::cell::{Cell, RefCell}; use std::cmp; use std::fmt::{self, Display}; use std::ops::ControlFlow; use hir::def::DefKind; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{Diag, EmissionGuarantee}; diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index ad621c67772c..34c080c4938f 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -1,8 +1,8 @@ -use std::assert_matches::assert_matches; use std::iter; use rustc_abi::Primitive::Pointer; use rustc_abi::{BackendRepr, ExternAbi, PointerKind, Scalar, Size}; +use rustc_data_structures::assert_matches; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_middle::bug; diff --git a/compiler/rustc_ty_utils/src/layout/invariant.rs b/compiler/rustc_ty_utils/src/layout/invariant.rs index b013902f3fe3..97c98d0c2403 100644 --- a/compiler/rustc_ty_utils/src/layout/invariant.rs +++ b/compiler/rustc_ty_utils/src/layout/invariant.rs @@ -1,6 +1,5 @@ -use std::assert_matches::assert_matches; - use rustc_abi::{BackendRepr, FieldsShape, Scalar, Size, TagEncoding, Variants}; +use rustc_data_structures::assert_matches; use rustc_middle::bug; use rustc_middle::ty::layout::{HasTyCtxt, LayoutCx, TyAndLayout}; From 03b8b68073bd9273b9614830aaefe5b7f5d603c3 Mon Sep 17 00:00:00 2001 From: Edvin Bryntesson Date: Sun, 18 Jan 2026 20:30:48 +0100 Subject: [PATCH 127/146] Port `#[rustc_nounwind]` to attr parser --- .../src/attributes/rustc_internal.rs | 15 +++++++++++++++ compiler/rustc_attr_parsing/src/context.rs | 5 +++-- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 4 +++- compiler/rustc_hir/src/attrs/data_structures.rs | 3 +++ .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 2 +- 6 files changed, 26 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 834b1d988cb4..f8ee011f559b 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -320,3 +320,18 @@ impl NoArgsAttributeParser for RustcHasIncoherentInherentImplsParse ]); const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcHasIncoherentInherentImpls; } + +pub(crate) struct RustcNounwindParser; + +impl NoArgsAttributeParser for RustcNounwindParser { + const PATH: &[Symbol] = &[sym::rustc_nounwind]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[ + Allow(Target::Fn), + Allow(Target::ForeignFn), + Allow(Target::Method(MethodKind::Inherent)), + Allow(Target::Method(MethodKind::TraitImpl)), + Allow(Target::Method(MethodKind::Trait { body: true })), + ]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcNounwind; +} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 1a06f4edeaa6..e62dbc124eab 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -78,8 +78,8 @@ use crate::attributes::rustc_internal::{ RustcLintDiagnosticsParser, RustcLintOptDenyFieldAccessParser, RustcLintOptTyParser, RustcLintQueryInstabilityParser, RustcLintUntrackedQueryInformationParser, RustcMainParser, RustcMustImplementOneOfParser, RustcNeverReturnsNullPointerParser, - RustcNoImplicitAutorefsParser, RustcObjectLifetimeDefaultParser, RustcScalableVectorParser, - RustcSimdMonomorphizeLaneLimitParser, + RustcNoImplicitAutorefsParser, RustcNounwindParser, RustcObjectLifetimeDefaultParser, + RustcScalableVectorParser, RustcSimdMonomorphizeLaneLimitParser, }; use crate::attributes::semantics::MayDangleParser; use crate::attributes::stability::{ @@ -296,6 +296,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 1b0427e7e676..e29ba9c8725f 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -347,6 +347,9 @@ fn process_builtin_attrs( AttributeKind::RustcAllocatorZeroed => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED } + AttributeKind::RustcNounwind => { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND + } _ => {} } } @@ -356,7 +359,6 @@ fn process_builtin_attrs( }; match name { - sym::rustc_nounwind => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND, sym::patchable_function_entry => { codegen_fn_attrs.patchable_function_entry = parse_patchable_function_entry(tcx, attr); diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 5cd508acc567..379ebf648f47 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -981,6 +981,9 @@ pub enum AttributeKind { /// Represents `#[rustc_no_implicit_autorefs]` RustcNoImplicitAutorefs, + /// Represents `#[rustc_nounwind]` + RustcNounwind, + /// Represents `#[rustc_object_lifetime_default]`. RustcObjectLifetimeDefault, diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 19243c7d8468..44f040e5fdc8 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -122,6 +122,7 @@ impl AttributeKind { RustcMustImplementOneOf { .. } => No, RustcNeverReturnsNullPointer => Yes, RustcNoImplicitAutorefs => Yes, + RustcNounwind => No, RustcObjectLifetimeDefault => No, RustcPassIndirectlyInNonRusticAbis(..) => No, RustcReallocator => No, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 3a086ba5ff78..74edff7badba 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -322,6 +322,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcAllocatorZeroedVariant { .. } | AttributeKind::RustcDeallocator | AttributeKind::RustcReallocator + | AttributeKind::RustcNounwind ) => { /* do nothing */ } Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); @@ -390,7 +391,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::rustc_partition_reused | sym::rustc_partition_codegened | sym::rustc_expected_cgu_reuse - | sym::rustc_nounwind // crate-level attrs, are checked below | sym::feature | sym::register_tool From 3e731f7e84301a898a36e46ee5e4845ff9bda98a Mon Sep 17 00:00:00 2001 From: Edvin Bryntesson Date: Sun, 18 Jan 2026 20:41:29 +0100 Subject: [PATCH 128/146] Port `#[rustc_offload_kernel]` to attr parser --- .../rustc_attr_parsing/src/attributes/rustc_internal.rs | 9 +++++++++ compiler/rustc_attr_parsing/src/context.rs | 3 ++- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 6 +++--- compiler/rustc_hir/src/attrs/data_structures.rs | 3 +++ compiler/rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 1 + 6 files changed, 19 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index f8ee011f559b..51792b7aff72 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -335,3 +335,12 @@ impl NoArgsAttributeParser for RustcNounwindParser { ]); const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcNounwind; } + +pub(crate) struct RustcOffloadKernelParser; + +impl NoArgsAttributeParser for RustcOffloadKernelParser { + const PATH: &[Symbol] = &[sym::rustc_offload_kernel]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcOffloadKernel; +} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index e62dbc124eab..0c882fee01c8 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -79,7 +79,7 @@ use crate::attributes::rustc_internal::{ RustcLintQueryInstabilityParser, RustcLintUntrackedQueryInformationParser, RustcMainParser, RustcMustImplementOneOfParser, RustcNeverReturnsNullPointerParser, RustcNoImplicitAutorefsParser, RustcNounwindParser, RustcObjectLifetimeDefaultParser, - RustcScalableVectorParser, RustcSimdMonomorphizeLaneLimitParser, + RustcOffloadKernelParser, RustcScalableVectorParser, RustcSimdMonomorphizeLaneLimitParser, }; use crate::attributes::semantics::MayDangleParser; use crate::attributes::stability::{ @@ -297,6 +297,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index e29ba9c8725f..e35d884b6711 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -350,6 +350,9 @@ fn process_builtin_attrs( AttributeKind::RustcNounwind => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND } + AttributeKind::RustcOffloadKernel => { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL + } _ => {} } } @@ -363,9 +366,6 @@ fn process_builtin_attrs( codegen_fn_attrs.patchable_function_entry = parse_patchable_function_entry(tcx, attr); } - sym::rustc_offload_kernel => { - codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL - } _ => {} } } diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 379ebf648f47..314f36d6132d 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -987,6 +987,9 @@ pub enum AttributeKind { /// Represents `#[rustc_object_lifetime_default]`. RustcObjectLifetimeDefault, + /// Represents `#[rustc_offload_kernel]` + RustcOffloadKernel, + /// Represents `#[rustc_pass_indirectly_in_non_rustic_abis]` RustcPassIndirectlyInNonRusticAbis(Span), diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 44f040e5fdc8..b55a5d0e29e1 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -124,6 +124,7 @@ impl AttributeKind { RustcNoImplicitAutorefs => Yes, RustcNounwind => No, RustcObjectLifetimeDefault => No, + RustcOffloadKernel => Yes, RustcPassIndirectlyInNonRusticAbis(..) => No, RustcReallocator => No, RustcScalableVector { .. } => Yes, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 74edff7badba..8074ae429892 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -323,6 +323,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcDeallocator | AttributeKind::RustcReallocator | AttributeKind::RustcNounwind + | AttributeKind::RustcOffloadKernel ) => { /* do nothing */ } Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); From eeed3376e25905b6b1b42ee1fa1af2e75f4482f0 Mon Sep 17 00:00:00 2001 From: KaiTomotake Date: Mon, 19 Jan 2026 17:06:07 +0900 Subject: [PATCH 129/146] add test program A test for the issue where the variable meta is mistakenly treated as a reserved keyword. --- tests/ui/reserved/meta-is-not-reserved.rs | 7 +++++++ tests/ui/reserved/meta-is-not-reserved.stderr | 9 +++++++++ 2 files changed, 16 insertions(+) create mode 100644 tests/ui/reserved/meta-is-not-reserved.rs create mode 100644 tests/ui/reserved/meta-is-not-reserved.stderr diff --git a/tests/ui/reserved/meta-is-not-reserved.rs b/tests/ui/reserved/meta-is-not-reserved.rs new file mode 100644 index 000000000000..ceefe345ff0c --- /dev/null +++ b/tests/ui/reserved/meta-is-not-reserved.rs @@ -0,0 +1,7 @@ +// Regression test for +// A test for the issue where the variable meta is mistakenly treated as a reserved keyword. + +fn main() { + let xyz = meta; + //~^ ERROR cannot find value `meta` in this scope [E0425] +} diff --git a/tests/ui/reserved/meta-is-not-reserved.stderr b/tests/ui/reserved/meta-is-not-reserved.stderr new file mode 100644 index 000000000000..33f8fd82df85 --- /dev/null +++ b/tests/ui/reserved/meta-is-not-reserved.stderr @@ -0,0 +1,9 @@ +error[E0425]: cannot find value `meta` in this scope + --> $DIR/meta-is-not-reserved.rs:5:15 + | +LL | let xyz = meta; + | ^^^^ not found in this scope + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0425`. From 67c45b739af089b9c8d96f0706c22b899a2ac324 Mon Sep 17 00:00:00 2001 From: JayanAXHF Date: Sat, 10 Jan 2026 01:37:51 +0530 Subject: [PATCH 130/146] feat: added syntax highlighting for code blocks in `rustc --explain` This commit adds a heuristics-based syntax highlighter for the `rustc --explain` command. It uses `rsutc_lexer`'s lexer to parse input in tokens, and matches on them to determine their color. --- Cargo.lock | 2 + compiler/rustc_driver_impl/Cargo.toml | 2 + compiler/rustc_driver_impl/src/highlighter.rs | 159 ++++++++++++++++++ compiler/rustc_driver_impl/src/lib.rs | 7 +- compiler/rustc_errors/src/markdown/mod.rs | 11 +- compiler/rustc_errors/src/markdown/term.rs | 41 +++-- .../src/markdown/tests/output.stdout | 10 +- .../rustc_errors/src/markdown/tests/term.rs | 2 +- tests/ui-fulldeps/explain_highlighter.rs | 29 ++++ .../explain_highlighter.run.stdout | 12 ++ 10 files changed, 249 insertions(+), 26 deletions(-) create mode 100644 compiler/rustc_driver_impl/src/highlighter.rs create mode 100644 tests/ui-fulldeps/explain_highlighter.rs create mode 100644 tests/ui-fulldeps/explain_highlighter.run.stdout diff --git a/Cargo.lock b/Cargo.lock index 470b38d5a91c..2d23541b4314 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3809,6 +3809,7 @@ dependencies = [ name = "rustc_driver_impl" version = "0.0.0" dependencies = [ + "anstyle", "ctrlc", "jiff", "libc", @@ -3834,6 +3835,7 @@ dependencies = [ "rustc_index", "rustc_infer", "rustc_interface", + "rustc_lexer", "rustc_lint", "rustc_log", "rustc_macros", diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml index 531b9e0c8ff7..c160240a18a7 100644 --- a/compiler/rustc_driver_impl/Cargo.toml +++ b/compiler/rustc_driver_impl/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [dependencies] # tidy-alphabetical-start +anstyle = "1.0.13" jiff = { version = "0.2.5", default-features = false, features = ["std"] } rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } @@ -28,6 +29,7 @@ rustc_incremental = { path = "../rustc_incremental" } rustc_index = { path = "../rustc_index" } rustc_infer = { path = "../rustc_infer" } rustc_interface = { path = "../rustc_interface" } +rustc_lexer = { path = "../rustc_lexer" } rustc_lint = { path = "../rustc_lint" } rustc_log = { path = "../rustc_log" } rustc_macros = { path = "../rustc_macros" } diff --git a/compiler/rustc_driver_impl/src/highlighter.rs b/compiler/rustc_driver_impl/src/highlighter.rs new file mode 100644 index 000000000000..70b73cc29b72 --- /dev/null +++ b/compiler/rustc_driver_impl/src/highlighter.rs @@ -0,0 +1,159 @@ +//! This module provides a syntax highlighter for Rust code. +//! It is used by the `rustc --explain` command. +//! +//! The syntax highlighter uses `rustc_lexer`'s `tokenize` +//! function to parse the Rust code into a `Vec` of tokens. +//! The highlighter then highlights the tokens in the `Vec`, +//! and writes the highlighted output to the buffer. +use std::io::{self, Write}; + +use anstyle::{AnsiColor, Color, Effects, Style}; +use rustc_lexer::{LiteralKind, strip_shebang, tokenize}; + +const PRIMITIVE_TYPES: &'static [&str] = &[ + "i8", "i16", "i32", "i64", "i128", "isize", // signed integers + "u8", "u16", "u32", "u64", "u128", "usize", // unsigned integers + "f32", "f64", // floating point + "char", "bool", // others +]; + +const KEYWORDS: &'static [&str] = &[ + "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "as", + "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", + "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", + "ref", +]; + +const STR_LITERAL_COLOR: AnsiColor = AnsiColor::Green; +const OTHER_LITERAL_COLOR: AnsiColor = AnsiColor::BrightRed; +const DERIVE_COLOR: AnsiColor = AnsiColor::BrightRed; +const KEYWORD_COLOR: AnsiColor = AnsiColor::BrightMagenta; +const TYPE_COLOR: AnsiColor = AnsiColor::Yellow; +const FUNCTION_COLOR: AnsiColor = AnsiColor::Blue; +const USE_COLOR: AnsiColor = AnsiColor::BrightMagenta; +const PRIMITIVE_TYPE_COLOR: AnsiColor = AnsiColor::Cyan; + +/// Highlight a Rust code string and write the highlighted +/// output to the buffer. It serves as a wrapper around +/// `Highlighter::highlight_rustc_lexer`. It is passed to +/// `write_anstream_buf` in the `lib.rs` file. +pub fn highlight(code: &str, buf: &mut Vec) -> io::Result<()> { + let mut highlighter = Highlighter::default(); + highlighter.highlight_rustc_lexer(code, buf) +} + +/// A syntax highlighter for Rust code +/// It is used by the `rustc --explain` command. +#[derive(Default)] +pub struct Highlighter { + /// Used to track if the previous token was a token + /// that warrants the next token to be colored differently + /// + /// For example, the keyword `fn` requires the next token + /// (the function name) to be colored differently. + prev_was_special: bool, + /// Used to track the length of tokens that have been + /// written so far. This is used to find the original + /// lexeme for a token from the code string. + len_accum: usize, +} + +impl Highlighter { + /// Create a new highlighter + pub fn new() -> Self { + Self::default() + } + + /// Highlight a Rust code string and write the highlighted + /// output to the buffer. + pub fn highlight_rustc_lexer(&mut self, code: &str, buf: &mut Vec) -> io::Result<()> { + use rustc_lexer::TokenKind; + + // Remove shebang from code string + let stripped_idx = strip_shebang(code).unwrap_or(0); + let stripped_code = &code[stripped_idx..]; + self.len_accum = stripped_idx; + let len_accum = &mut self.len_accum; + let tokens = tokenize(stripped_code, rustc_lexer::FrontmatterAllowed::No); + for token in tokens { + let len = token.len as usize; + // If the previous token was a special token, and this token is + // not a whitespace token, then it should be colored differently + let token_str = &code[*len_accum..*len_accum + len]; + if self.prev_was_special { + if token_str != " " { + self.prev_was_special = false; + } + let style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Blue))); + write!(buf, "{style}{token_str}{style:#}")?; + *len_accum += len; + continue; + } + match token.kind { + TokenKind::Ident => { + let mut style = Style::new(); + // Match if an identifier is a (well-known) keyword + if KEYWORDS.contains(&token_str) { + if token_str == "fn" { + self.prev_was_special = true; + } + style = style.fg_color(Some(Color::Ansi(KEYWORD_COLOR))); + } + // The `use` keyword is colored differently + if matches!(token_str, "use") { + style = style.fg_color(Some(Color::Ansi(USE_COLOR))); + } + // This heuristic test is to detect if the identifier is + // a function call. If it is, then the function identifier is + // colored differently. + if code[*len_accum..*len_accum + len + 1].ends_with('(') { + style = style.fg_color(Some(Color::Ansi(FUNCTION_COLOR))); + } + // The `derive` keyword is colored differently. + if token_str == "derive" { + style = style.fg_color(Some(Color::Ansi(DERIVE_COLOR))); + } + // This heuristic test is to detect if the identifier is + // a type. If it is, then the identifier is colored differently. + if matches!(token_str.chars().next().map(|c| c.is_uppercase()), Some(true)) { + style = style.fg_color(Some(Color::Ansi(TYPE_COLOR))); + } + // This if statement is to detect if the identifier is a primitive type. + if PRIMITIVE_TYPES.contains(&token_str) { + style = style.fg_color(Some(Color::Ansi(PRIMITIVE_TYPE_COLOR))); + } + write!(buf, "{style}{token_str}{style:#}")?; + } + + // Color literals + TokenKind::Literal { kind, suffix_start: _ } => { + // Strings -> Green + // Chars -> Green + // Raw strings -> Green + // C strings -> Green + // Byte Strings -> Green + // Other literals -> Bright Red (Orage-esque) + let style = match kind { + LiteralKind::Str { terminated: _ } + | LiteralKind::Char { terminated: _ } + | LiteralKind::RawStr { n_hashes: _ } + | LiteralKind::CStr { terminated: _ } => { + Style::new().fg_color(Some(Color::Ansi(STR_LITERAL_COLOR))) + } + _ => Style::new().fg_color(Some(Color::Ansi(OTHER_LITERAL_COLOR))), + }; + write!(buf, "{style}{token_str}{style:#}")?; + } + _ => { + // All other tokens are dimmed + let style = Style::new() + .fg_color(Some(Color::Ansi(AnsiColor::BrightWhite))) + .effects(Effects::DIMMED); + write!(buf, "{style}{token_str}{style:#}")?; + } + } + *len_accum += len; + } + Ok(()) + } +} diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 7820198f2dcf..045292338e58 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -86,6 +86,7 @@ pub mod args; pub mod pretty; #[macro_use] mod print; +pub mod highlighter; mod session_diagnostics; // Keep the OS parts of this `cfg` in sync with the `cfg` on the `libc` @@ -521,7 +522,11 @@ fn show_md_content_with_pager(content: &str, color: ColorConfig) { let mdstream = markdown::MdStream::parse_str(content); let bufwtr = markdown::create_stdout_bufwtr(); let mut mdbuf = Vec::new(); - if mdstream.write_anstream_buf(&mut mdbuf).is_ok() { Some((bufwtr, mdbuf)) } else { None } + if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() { + Some((bufwtr, mdbuf)) + } else { + None + } }; // Try to print via the pager, pretty output if possible. diff --git a/compiler/rustc_errors/src/markdown/mod.rs b/compiler/rustc_errors/src/markdown/mod.rs index 4f5e2328234d..9993407b05c0 100644 --- a/compiler/rustc_errors/src/markdown/mod.rs +++ b/compiler/rustc_errors/src/markdown/mod.rs @@ -18,9 +18,14 @@ impl<'a> MdStream<'a> { parse::entrypoint(s) } - /// Write formatted output to an anstream buffer - pub fn write_anstream_buf(&self, buf: &mut Vec) -> io::Result<()> { - term::entrypoint(self, buf) + /// Write formatted output to a stdout buffer, optionally with + /// a formatter for code blocks + pub fn write_anstream_buf( + &self, + buf: &mut Vec, + formatter: Option<&(dyn Fn(&str, &mut Vec) -> io::Result<()> + 'static)>, + ) -> io::Result<()> { + term::entrypoint(self, buf, formatter) } } diff --git a/compiler/rustc_errors/src/markdown/term.rs b/compiler/rustc_errors/src/markdown/term.rs index b0ce01548f00..b94cd06b30ef 100644 --- a/compiler/rustc_errors/src/markdown/term.rs +++ b/compiler/rustc_errors/src/markdown/term.rs @@ -12,29 +12,33 @@ thread_local! { static CURSOR: Cell = const { Cell::new(0) }; /// Width of the terminal static WIDTH: Cell = const { Cell::new(DEFAULT_COLUMN_WIDTH) }; + } -/// Print to terminal output to a buffer -pub(crate) fn entrypoint(stream: &MdStream<'_>, buf: &mut Vec) -> io::Result<()> { - #[cfg(not(test))] - if let Some((w, _)) = termize::dimensions() { - WIDTH.set(std::cmp::min(w, DEFAULT_COLUMN_WIDTH)); - } - write_stream(stream, buf, None, 0)?; +/// Print to the terminal output to a buffer +/// optionally with a formatter for code blocks +pub(crate) fn entrypoint( + stream: &MdStream<'_>, + buf: &mut Vec, + formatter: Option<&(dyn Fn(&str, &mut Vec) -> io::Result<()> + 'static)>, +) -> io::Result<()> { + write_stream(stream, buf, None, 0, formatter)?; buf.write_all(b"\n") } -/// Write the buffer, reset to the default style after each + +/// Write the buffer, reset to the default style after each, +/// optionally with a formatter for code blocks fn write_stream( MdStream(stream): &MdStream<'_>, buf: &mut Vec, + default: Option