From c59b70841c36277464b51161e3fcf12dfcb667e0 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Fri, 7 Mar 2025 10:13:30 +0800 Subject: [PATCH 01/24] Emit warning while outputs is not exe and prints linkage info Signed-off-by: xizheyin --- compiler/rustc_codegen_ssa/src/back/link.rs | 19 +++++++++++++++++++ ...rning-print-link-info-without-staticlib.rs | 5 +++++ ...g-print-link-info-without-staticlib.stderr | 6 ++++++ ...t-warning-while-exe-and-print-link-info.rs | 3 +++ ...rning-while-exe-and-print-link-info.stderr | 4 ++++ tests/ui/print-request/stability.rs | 1 + 6 files changed, 38 insertions(+) create mode 100644 tests/ui/print-request/emit-warning-print-link-info-without-staticlib.rs create mode 100644 tests/ui/print-request/emit-warning-print-link-info-without-staticlib.stderr create mode 100644 tests/ui/print-request/emit-warning-while-exe-and-print-link-info.rs create mode 100644 tests/ui/print-request/emit-warning-while-exe-and-print-link-info.stderr diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 323538969d73b..ffa888a17d0c7 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -68,6 +68,23 @@ pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) { } } +fn check_link_info_print_request(sess: &Session, crate_type: CrateType) { + let print_native_static_libs = + sess.opts.prints.iter().any(|p| p.kind == PrintKind::NativeStaticLibs); + if print_native_static_libs { + if crate_type != CrateType::Staticlib { + sess.dcx() + .warn(format!("cannot output linkage information without staticlib crate-type")); + sess.dcx() + .note(format!("consider `--crate-type staticlib` to print linkage information")); + } else if !sess.opts.output_types.should_link() { + sess.dcx().warn(format!( + "skipping link step due to conflict: cannot output linkage information without emitting link" + )); + } + } +} + /// Performs the linkage portion of the compilation phase. This will generate all /// of the requested outputs for this compilation session. pub fn link_binary( @@ -178,6 +195,8 @@ pub fn link_binary( tempfiles_for_stdout_output.push(out_filename); } } + + check_link_info_print_request(sess, crate_type); } // Remove the temporary object file and metadata if we aren't saving temps. diff --git a/tests/ui/print-request/emit-warning-print-link-info-without-staticlib.rs b/tests/ui/print-request/emit-warning-print-link-info-without-staticlib.rs new file mode 100644 index 0000000000000..b100c062bba4c --- /dev/null +++ b/tests/ui/print-request/emit-warning-print-link-info-without-staticlib.rs @@ -0,0 +1,5 @@ +//@ compile-flags: --print native-static-libs +//@ check-pass +//~? WARN cannot output linkage information without staticlib crate-type + +fn main() {} diff --git a/tests/ui/print-request/emit-warning-print-link-info-without-staticlib.stderr b/tests/ui/print-request/emit-warning-print-link-info-without-staticlib.stderr new file mode 100644 index 0000000000000..ceff08baa13a4 --- /dev/null +++ b/tests/ui/print-request/emit-warning-print-link-info-without-staticlib.stderr @@ -0,0 +1,6 @@ +warning: cannot output linkage information without staticlib crate-type + +note: consider `--crate-type staticlib` to print linkage information + +warning: 1 warning emitted + diff --git a/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.rs b/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.rs new file mode 100644 index 0000000000000..48f5475c88491 --- /dev/null +++ b/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.rs @@ -0,0 +1,3 @@ +//@ compile-flags: --print native-static-libs --crate-type staticlib --emit metadata +//@ check-pass +//~? WARN skipping link step due to conflict: cannot output linkage information without emitting link diff --git a/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.stderr b/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.stderr new file mode 100644 index 0000000000000..0b46d2f684815 --- /dev/null +++ b/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.stderr @@ -0,0 +1,4 @@ +warning: skipping link step due to conflict: cannot output linkage information without emitting link + +warning: 1 warning emitted + diff --git a/tests/ui/print-request/stability.rs b/tests/ui/print-request/stability.rs index 54142ce78cefb..fbcdf916cc7cd 100644 --- a/tests/ui/print-request/stability.rs +++ b/tests/ui/print-request/stability.rs @@ -110,3 +110,4 @@ fn main() {} //[check_cfg]~? ERROR the `-Z unstable-options` flag must also be passed to enable the `check-cfg` print option //[supported_crate_types]~? ERROR the `-Z unstable-options` flag must also be passed to enable the `supported-crate-types` print option //[target_spec_json]~? ERROR the `-Z unstable-options` flag must also be passed to enable the `target-spec-json` print option +//[native_static_libs]~? WARNING cannot output linkage information without staticlib crate-type From 98bb597c05c32365abbd6898f278b097352774ed Mon Sep 17 00:00:00 2001 From: xizheyin Date: Fri, 2 May 2025 22:37:33 +0800 Subject: [PATCH 02/24] Update compiler/rustc_codegen_ssa/src/back/link.rs Co-authored-by: bjorn3 <17426603+bjorn3@users.noreply.github.com> --- compiler/rustc_codegen_ssa/src/back/link.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index ffa888a17d0c7..28c7b5b274542 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -79,7 +79,7 @@ fn check_link_info_print_request(sess: &Session, crate_type: CrateType) { .note(format!("consider `--crate-type staticlib` to print linkage information")); } else if !sess.opts.output_types.should_link() { sess.dcx().warn(format!( - "skipping link step due to conflict: cannot output linkage information without emitting link" + "cannot output linkage information when --emit link is not passed" )); } } From 72a9219e82c157041bfc8dfd378c9cb2b09c0650 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Fri, 2 May 2025 22:56:27 +0800 Subject: [PATCH 03/24] check all crate-type to find staticlib Signed-off-by: xizheyin --- compiler/rustc_codegen_ssa/src/back/link.rs | 12 ++++++------ .../emit-warning-while-exe-and-print-link-info.rs | 2 +- ...emit-warning-while-exe-and-print-link-info.stderr | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 28c7b5b274542..1e9d9338b1359 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -68,19 +68,19 @@ pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) { } } -fn check_link_info_print_request(sess: &Session, crate_type: CrateType) { +fn check_link_info_print_request(sess: &Session, crate_types: &[CrateType]) { let print_native_static_libs = sess.opts.prints.iter().any(|p| p.kind == PrintKind::NativeStaticLibs); + let has_staticlib = crate_types.iter().any(|ct| *ct == CrateType::Staticlib); if print_native_static_libs { - if crate_type != CrateType::Staticlib { + if !has_staticlib { sess.dcx() .warn(format!("cannot output linkage information without staticlib crate-type")); sess.dcx() .note(format!("consider `--crate-type staticlib` to print linkage information")); } else if !sess.opts.output_types.should_link() { - sess.dcx().warn(format!( - "cannot output linkage information when --emit link is not passed" - )); + sess.dcx() + .warn(format!("cannot output linkage information when --emit link is not passed")); } } } @@ -196,7 +196,7 @@ pub fn link_binary( } } - check_link_info_print_request(sess, crate_type); + check_link_info_print_request(sess, &codegen_results.crate_info.crate_types); } // Remove the temporary object file and metadata if we aren't saving temps. diff --git a/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.rs b/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.rs index 48f5475c88491..3e9ca457a9c9b 100644 --- a/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.rs +++ b/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.rs @@ -1,3 +1,3 @@ //@ compile-flags: --print native-static-libs --crate-type staticlib --emit metadata //@ check-pass -//~? WARN skipping link step due to conflict: cannot output linkage information without emitting link +//~? WARN cannot output linkage information when --emit link is not passed diff --git a/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.stderr b/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.stderr index 0b46d2f684815..b32e1437d6b50 100644 --- a/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.stderr +++ b/tests/ui/print-request/emit-warning-while-exe-and-print-link-info.stderr @@ -1,4 +1,4 @@ -warning: skipping link step due to conflict: cannot output linkage information without emitting link +warning: cannot output linkage information when --emit link is not passed warning: 1 warning emitted From f66787a08d57dc1296619b314d2be596085bfeef Mon Sep 17 00:00:00 2001 From: xizheyin Date: Fri, 2 May 2025 23:14:18 +0800 Subject: [PATCH 04/24] Update compiler/rustc_codegen_ssa/src/back/link.rs Co-authored-by: bjorn3 <17426603+bjorn3@users.noreply.github.com> Signed-off-by: xizheyin --- compiler/rustc_codegen_ssa/src/back/link.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 1e9d9338b1359..62c389ec79150 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -195,10 +195,10 @@ pub fn link_binary( tempfiles_for_stdout_output.push(out_filename); } } - - check_link_info_print_request(sess, &codegen_results.crate_info.crate_types); } + check_link_info_print_request(sess, &codegen_results.crate_info.crate_types); + // Remove the temporary object file and metadata if we aren't saving temps. sess.time("link_binary_remove_temps", || { // If the user requests that temporaries are saved, don't delete any. From a3bd12b88aaf32b1036cdcb2ef3efe509dbebc15 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 24 May 2025 22:12:15 +0200 Subject: [PATCH 05/24] Path::with_extension: improve examples --- library/std/src/path.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 7959c63385816..0583ee1eb3274 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -2743,12 +2743,27 @@ impl Path { /// /// let path = Path::new("foo.rs"); /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt")); + /// assert_eq!(path.with_extension(""), PathBuf::from("foo")); + /// ``` + /// + /// Handling multiple extensions: + /// + /// ``` + /// use std::path::{Path, PathBuf}; /// /// let path = Path::new("foo.tar.gz"); - /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar")); /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz")); /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt")); /// ``` + /// + /// Adding an extension where one did not exist: + /// + /// ``` + /// use std::path::{Path, PathBuf}; + /// + /// let path = Path::new("foo"); + /// assert_eq!(path.with_extension("rs"), PathBuf::from("foo.rs")); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn with_extension>(&self, extension: S) -> PathBuf { self._with_extension(extension.as_ref()) From 248f4b2ad2b18ab322748cc62b3524c109206b98 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sat, 24 May 2025 22:17:55 +0200 Subject: [PATCH 06/24] reduce clutter... too many imports --- library/std/src/path.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 0583ee1eb3274..87c5d6f0438de 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -2739,30 +2739,30 @@ impl Path { /// # Examples /// /// ``` - /// use std::path::{Path, PathBuf}; + /// use std::path::Path; /// /// let path = Path::new("foo.rs"); - /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt")); - /// assert_eq!(path.with_extension(""), PathBuf::from("foo")); + /// assert_eq!(path.with_extension("txt"), Path::new("foo.txt")); + /// assert_eq!(path.with_extension(""), Path::new("foo")); /// ``` /// /// Handling multiple extensions: /// /// ``` - /// use std::path::{Path, PathBuf}; + /// use std::path::Path; /// /// let path = Path::new("foo.tar.gz"); - /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz")); - /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt")); + /// assert_eq!(path.with_extension("xz"), Path::new("foo.tar.xz")); + /// assert_eq!(path.with_extension("").with_extension("txt"), Path::new("foo.txt")); /// ``` /// /// Adding an extension where one did not exist: /// /// ``` - /// use std::path::{Path, PathBuf}; + /// use std::path::Path; /// /// let path = Path::new("foo"); - /// assert_eq!(path.with_extension("rs"), PathBuf::from("foo.rs")); + /// assert_eq!(path.with_extension("rs"), Path::new("foo.rs")); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn with_extension>(&self, extension: S) -> PathBuf { From 396c5cafe70f735e3d0ea0c8982c6901bcf0023a Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 25 May 2025 09:24:28 +0200 Subject: [PATCH 07/24] clean up old rintf leftovers --- library/core/src/intrinsics/mod.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 23bafa778bc6b..e9fa3b1b3f649 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -2296,12 +2296,6 @@ pub fn round_ties_even_f16(x: f16) -> f16; #[rustc_nounwind] pub fn round_ties_even_f32(x: f32) -> f32; -/// Provided for compatibility with stdarch. DO NOT USE. -#[inline(always)] -pub unsafe fn rintf32(x: f32) -> f32 { - round_ties_even_f32(x) -} - /// Returns the nearest integer to an `f64`. Rounds half-way cases to the number with an even /// least significant digit. /// @@ -2311,12 +2305,6 @@ pub unsafe fn rintf32(x: f32) -> f32 { #[rustc_nounwind] pub fn round_ties_even_f64(x: f64) -> f64; -/// Provided for compatibility with stdarch. DO NOT USE. -#[inline(always)] -pub unsafe fn rintf64(x: f64) -> f64 { - round_ties_even_f64(x) -} - /// Returns the nearest integer to an `f128`. Rounds half-way cases to the number with an even /// least significant digit. /// From 7aef56d9b938a0df077c346007921497c092fdc9 Mon Sep 17 00:00:00 2001 From: Jacob Pratt Date: Mon, 26 May 2025 15:06:36 -0400 Subject: [PATCH 08/24] Call out possibility of invariant result --- library/core/src/marker/variance.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/library/core/src/marker/variance.rs b/library/core/src/marker/variance.rs index 235f8a3bb79f2..f9638fea225b7 100644 --- a/library/core/src/marker/variance.rs +++ b/library/core/src/marker/variance.rs @@ -131,6 +131,8 @@ phantom_lifetime! { /// /// [1]: https://doc.rust-lang.org/stable/reference/subtyping.html#variance /// + /// Note: If `'a` is otherwise contravariant or invariant, the resulting type is invariant. + /// /// ## Layout /// /// For all `'a`, the following are guaranteed: @@ -146,6 +148,8 @@ phantom_lifetime! { /// /// [1]: https://doc.rust-lang.org/stable/reference/subtyping.html#variance /// + /// Note: If `'a` is otherwise covariant or invariant, the resulting type is invariant. + /// /// ## Layout /// /// For all `'a`, the following are guaranteed: @@ -180,6 +184,8 @@ phantom_type! { /// /// [1]: https://doc.rust-lang.org/stable/reference/subtyping.html#variance /// + /// Note: If `T` is otherwise contravariant or invariant, the resulting type is invariant. + /// /// ## Layout /// /// For all `T`, the following are guaranteed: @@ -196,6 +202,8 @@ phantom_type! { /// /// [1]: https://doc.rust-lang.org/stable/reference/subtyping.html#variance /// + /// Note: If `T` is otherwise covariant or invariant, the resulting type is invariant. + /// /// ## Layout /// /// For all `T`, the following are guaranteed: From a83f8d02eaf36b36a7ed495e43b8bf891b6fc1af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Fri, 2 May 2025 20:22:13 +0200 Subject: [PATCH 09/24] Always evaluate free lifetime-generic constants Co-authored-by: Michael Goulet --- compiler/rustc_hir_analysis/src/lib.rs | 4 +++- compiler/rustc_monomorphize/src/collector.rs | 2 +- tests/ui/generic-const-items/def-site-eval.fail.stderr | 4 ++-- tests/ui/generic-const-items/def-site-eval.rs | 7 +++---- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 010c6c376fe3d..a64c24f5455bf 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -203,7 +203,9 @@ pub fn check_crate(tcx: TyCtxt<'_>) { tcx.ensure_ok().eval_static_initializer(item_def_id); check::maybe_check_static_with_link_section(tcx, item_def_id); } - DefKind::Const if tcx.generics_of(item_def_id).is_empty() => { + DefKind::Const if !tcx.generics_of(item_def_id).own_requires_monomorphization() => { + // FIXME(generic_const_items): Passing empty instead of identity args is fishy but + // seems to be fine for now. Revisit this! let instance = ty::Instance::new_raw(item_def_id.into(), ty::GenericArgs::empty()); let cid = GlobalId { instance, promoted: None }; let typing_env = ty::TypingEnv::fully_monomorphized(); diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index b3d7eaf332b25..1ee977a5457e2 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1483,7 +1483,7 @@ impl<'v> RootCollector<'_, 'v> { // But even just declaring them must collect the items they refer to // unless their generics require monomorphization. - if !self.tcx.generics_of(id.owner_id).requires_monomorphization(self.tcx) + if !self.tcx.generics_of(id.owner_id).own_requires_monomorphization() && let Ok(val) = self.tcx.const_eval_poly(id.owner_id.to_def_id()) { collect_const_value(self.tcx, val, self.output); diff --git a/tests/ui/generic-const-items/def-site-eval.fail.stderr b/tests/ui/generic-const-items/def-site-eval.fail.stderr index fa07f38552243..4e7d9d8154a0e 100644 --- a/tests/ui/generic-const-items/def-site-eval.fail.stderr +++ b/tests/ui/generic-const-items/def-site-eval.fail.stderr @@ -1,5 +1,5 @@ -error[E0080]: evaluation of `_::<'_>` failed - --> $DIR/def-site-eval.rs:14:20 +error[E0080]: evaluation of constant value failed + --> $DIR/def-site-eval.rs:13:20 | LL | const _<'_a>: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic diff --git a/tests/ui/generic-const-items/def-site-eval.rs b/tests/ui/generic-const-items/def-site-eval.rs index 3ed7f96aed02c..b95e40c05d4d8 100644 --- a/tests/ui/generic-const-items/def-site-eval.rs +++ b/tests/ui/generic-const-items/def-site-eval.rs @@ -1,16 +1,15 @@ //! Test that we only evaluate free const items (their def site to be clear) //! whose generics don't require monomorphization. #![feature(generic_const_items)] -#![allow(incomplete_features)] +#![expect(incomplete_features)] //@ revisions: fail pass -//@[fail] build-fail (we require monomorphization) -//@[pass] build-pass (we require monomorphization) +//@[pass] check-pass const _<_T>: () = panic!(); const _: () = panic!(); #[cfg(fail)] -const _<'_a>: () = panic!(); //[fail]~ ERROR evaluation of `_::<'_>` failed +const _<'_a>: () = panic!(); //[fail]~ ERROR evaluation of constant value failed fn main() {} From db21caf5ba1161d157e62956039f0ff2493454a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Fri, 2 May 2025 20:22:35 +0200 Subject: [PATCH 10/24] Drive-by: Delete dead TyCtxtEnsureOk::const_eval_poly --- .../rustc_middle/src/mir/interpret/queries.rs | 22 ------------------- 1 file changed, 22 deletions(-) diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index 4a5c42c721c12..97db45a70d7fe 100644 --- a/compiler/rustc_middle/src/mir/interpret/queries.rs +++ b/compiler/rustc_middle/src/mir/interpret/queries.rs @@ -9,7 +9,6 @@ use super::{ ReportedErrorInfo, }; use crate::mir; -use crate::query::TyCtxtEnsureOk; use crate::ty::{self, GenericArgs, TyCtxt, TypeVisitableExt}; impl<'tcx> TyCtxt<'tcx> { @@ -197,24 +196,3 @@ impl<'tcx> TyCtxt<'tcx> { } } } - -impl<'tcx> TyCtxtEnsureOk<'tcx> { - /// Evaluates a constant without providing any generic parameters. This is useful to evaluate consts - /// that can't take any generic arguments like const items or enum discriminants. If a - /// generic parameter is used within the constant `ErrorHandled::TooGeneric` will be returned. - #[instrument(skip(self), level = "debug")] - pub fn const_eval_poly(self, def_id: DefId) { - // In some situations def_id will have generic parameters within scope, but they aren't allowed - // to be used. So we can't use `Instance::mono`, instead we feed unresolved generic parameters - // into `const_eval` which will return `ErrorHandled::TooGeneric` if any of them are - // encountered. - let args = GenericArgs::identity_for_item(self.tcx, def_id); - let instance = ty::Instance::new_raw(def_id, self.tcx.erase_regions(args)); - let cid = GlobalId { instance, promoted: None }; - let typing_env = ty::TypingEnv::post_analysis(self.tcx, def_id); - // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should - // improve caching of queries. - let inputs = self.tcx.erase_regions(typing_env.as_query_input(cid)); - self.eval_to_const_value_raw(inputs) - } -} From 4c4a40f6dfa7630a8817748a687cfdd1335a7358 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 28 May 2025 08:20:30 +1000 Subject: [PATCH 11/24] Reorder `ast::ItemKind::{Struct,Enum,Union}` fields. So they match the order of the parts in the source code, e.g.: ``` struct Foo { t: T, u: U } <-><----> <------------> / | \ ident generics variant_data ``` --- compiler/rustc_ast/src/ast.rs | 20 +++++++++---------- compiler/rustc_ast/src/visit.rs | 6 +++--- compiler/rustc_ast_lowering/src/item.rs | 6 +++--- .../rustc_ast_passes/src/ast_validation.rs | 6 +++--- .../rustc_ast_pretty/src/pprust/state/item.rs | 8 ++++---- .../src/deriving/clone.rs | 4 ++-- .../src/deriving/cmp/partial_ord.rs | 2 +- .../src/deriving/coerce_pointee.rs | 2 +- .../src/deriving/generic/mod.rs | 6 +++--- compiler/rustc_expand/src/base.rs | 2 +- compiler/rustc_parse/src/parser/item.rs | 6 +++--- .../rustc_resolve/src/build_reduced_graph.rs | 4 ++-- compiler/rustc_resolve/src/def_collector.rs | 4 ++-- .../src/effective_visibilities.rs | 4 ++-- compiler/rustc_resolve/src/late.rs | 12 +++++------ .../src/field_scoped_visibility_modifiers.rs | 2 +- .../clippy_lints/src/partial_pub_fields.rs | 2 +- .../clippy/clippy_utils/src/ast_utils/mod.rs | 8 ++++---- src/tools/rustfmt/src/items.rs | 4 ++-- src/tools/rustfmt/src/visitor.rs | 2 +- 20 files changed, 54 insertions(+), 56 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index a16219361c051..2ececee87510d 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -3417,9 +3417,9 @@ impl Item { ItemKind::Fn(i) => Some(&i.generics), ItemKind::TyAlias(i) => Some(&i.generics), ItemKind::TraitAlias(_, generics, _) - | ItemKind::Enum(_, _, generics) - | ItemKind::Struct(_, _, generics) - | ItemKind::Union(_, _, generics) => Some(&generics), + | ItemKind::Enum(_, generics, _) + | ItemKind::Struct(_, generics, _) + | ItemKind::Union(_, generics, _) => Some(&generics), ItemKind::Trait(i) => Some(&i.generics), ItemKind::Impl(i) => Some(&i.generics), } @@ -3663,15 +3663,15 @@ pub enum ItemKind { /// An enum definition (`enum`). /// /// E.g., `enum Foo { C, D }`. - Enum(Ident, EnumDef, Generics), + Enum(Ident, Generics, EnumDef), /// A struct definition (`struct`). /// /// E.g., `struct Foo { x: A }`. - Struct(Ident, VariantData, Generics), + Struct(Ident, Generics, VariantData), /// A union definition (`union`). /// /// E.g., `union Foo { x: A, y: B }`. - Union(Ident, VariantData, Generics), + Union(Ident, Generics, VariantData), /// A trait declaration (`trait`). /// /// E.g., `trait Foo { .. }`, `trait Foo { .. }` or `auto trait Foo {}`. @@ -3688,10 +3688,8 @@ pub enum ItemKind { /// /// E.g., `foo!(..)`. MacCall(P), - /// A macro definition. MacroDef(Ident, MacroDef), - /// A single delegation item (`reuse`). /// /// E.g. `reuse ::name { target_expr_template }`. @@ -3767,9 +3765,9 @@ impl ItemKind { Self::Fn(box Fn { generics, .. }) | Self::TyAlias(box TyAlias { generics, .. }) | Self::Const(box ConstItem { generics, .. }) - | Self::Enum(_, _, generics) - | Self::Struct(_, _, generics) - | Self::Union(_, _, generics) + | Self::Enum(_, generics, _) + | Self::Struct(_, generics, _) + | Self::Union(_, generics, _) | Self::Trait(box Trait { generics, .. }) | Self::TraitAlias(_, generics, _) | Self::Impl(box Impl { generics, .. }) => Some(generics), diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index bf5c402e52e5a..1cc11b58dd97b 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -508,7 +508,7 @@ macro_rules! common_visitor_and_walkers { )? $(>::Result::output())? } - ItemKind::Enum(ident, enum_definition, generics) => { + ItemKind::Enum(ident, generics, enum_definition) => { try_visit!(vis.visit_ident(ident)); try_visit!(vis.visit_generics(generics)); $(${ignore($mut)} @@ -516,8 +516,8 @@ macro_rules! common_visitor_and_walkers { )? $(${ignore($lt)}vis.visit_enum_def(enum_definition))? } - ItemKind::Struct(ident, variant_data, generics) - | ItemKind::Union(ident, variant_data, generics) => { + ItemKind::Struct(ident, generics, variant_data) + | ItemKind::Union(ident, generics, variant_data) => { try_visit!(vis.visit_ident(ident)); try_visit!(vis.visit_generics(generics)); vis.visit_variant_data(variant_data) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index e98d6c50ee791..7f7d45790ee26 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -306,7 +306,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ); hir::ItemKind::TyAlias(ident, ty, generics) } - ItemKind::Enum(ident, enum_definition, generics) => { + ItemKind::Enum(ident, generics, enum_definition) => { let ident = self.lower_ident(*ident); let (generics, variants) = self.lower_generics( generics, @@ -320,7 +320,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ); hir::ItemKind::Enum(ident, hir::EnumDef { variants }, generics) } - ItemKind::Struct(ident, struct_def, generics) => { + ItemKind::Struct(ident, generics, struct_def) => { let ident = self.lower_ident(*ident); let (generics, struct_def) = self.lower_generics( generics, @@ -330,7 +330,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ); hir::ItemKind::Struct(ident, struct_def, generics) } - ItemKind::Union(ident, vdata, generics) => { + ItemKind::Union(ident, generics, vdata) => { let ident = self.lower_ident(*ident); let (generics, vdata) = self.lower_generics( generics, diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index cbf4f2f5eb2be..d6fe04d2994b5 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -1010,7 +1010,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { }); self.extern_mod_span = old_item; } - ItemKind::Enum(_, def, _) => { + ItemKind::Enum(_, _, def) => { for variant in &def.variants { self.visibility_not_permitted( &variant.vis, @@ -1061,7 +1061,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } visit::walk_item(self, item) } - ItemKind::Struct(ident, vdata, generics) => match vdata { + ItemKind::Struct(ident, generics, vdata) => match vdata { VariantData::Struct { fields, .. } => { self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident); self.visit_generics(generics); @@ -1070,7 +1070,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } _ => visit::walk_item(self, item), }, - ItemKind::Union(ident, vdata, generics) => { + ItemKind::Union(ident, generics, vdata) => { if vdata.fields().is_empty() { self.dcx().emit_err(errors::FieldlessUnion { span: item.span }); } diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 70cf2f2a45982..3638eb31c6186 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -298,14 +298,14 @@ impl<'a> State<'a> { *defaultness, ); } - ast::ItemKind::Enum(ident, enum_definition, params) => { - self.print_enum_def(enum_definition, params, *ident, item.span, &item.vis); + ast::ItemKind::Enum(ident, generics, enum_definition) => { + self.print_enum_def(enum_definition, generics, *ident, item.span, &item.vis); } - ast::ItemKind::Struct(ident, struct_def, generics) => { + ast::ItemKind::Struct(ident, generics, struct_def) => { let (cb, ib) = self.head(visibility_qualified(&item.vis, "struct")); self.print_struct(struct_def, generics, *ident, item.span, true, cb, ib); } - ast::ItemKind::Union(ident, struct_def, generics) => { + ast::ItemKind::Union(ident, generics, struct_def) => { let (cb, ib) = self.head(visibility_qualified(&item.vis, "union")); self.print_struct(struct_def, generics, *ident, item.span, true, cb, ib); } diff --git a/compiler/rustc_builtin_macros/src/deriving/clone.rs b/compiler/rustc_builtin_macros/src/deriving/clone.rs index 44cf215c66227..69f8c273797e4 100644 --- a/compiler/rustc_builtin_macros/src/deriving/clone.rs +++ b/compiler/rustc_builtin_macros/src/deriving/clone.rs @@ -34,8 +34,8 @@ pub(crate) fn expand_deriving_clone( let is_simple; match item { Annotatable::Item(annitem) => match &annitem.kind { - ItemKind::Struct(_, _, Generics { params, .. }) - | ItemKind::Enum(_, _, Generics { params, .. }) => { + ItemKind::Struct(_, Generics { params, .. }, _) + | ItemKind::Enum(_, Generics { params, .. }, _) => { let container_id = cx.current_expansion.id.expn_data().parent.expect_local(); let has_derive_copy = cx.resolver.has_derive_copy(container_id); if has_derive_copy diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs index aa01da3151eb4..0a076dd670b34 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs @@ -21,7 +21,7 @@ pub(crate) fn expand_deriving_partial_ord( // Order in which to perform matching let discr_then_data = if let Annotatable::Item(item) = item - && let ItemKind::Enum(_, def, _) = &item.kind + && let ItemKind::Enum(_, _, def) = &item.kind { let dataful: Vec = def.variants.iter().map(|v| !v.data.fields().is_empty()).collect(); match dataful.iter().filter(|&&b| b).count() { diff --git a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs index 446d8afeedd7f..0794192621a93 100644 --- a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs +++ b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs @@ -30,7 +30,7 @@ pub(crate) fn expand_deriving_coerce_pointee( item.visit_with(&mut DetectNonGenericPointeeAttr { cx }); let (name_ident, generics) = if let Annotatable::Item(aitem) = item - && let ItemKind::Struct(ident, struct_data, g) = &aitem.kind + && let ItemKind::Struct(ident, g, struct_data) = &aitem.kind { if !matches!( struct_data, diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 9aa53f9e4f73b..f1bef526c1080 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -488,7 +488,7 @@ impl<'a> TraitDef<'a> { ); let newitem = match &item.kind { - ast::ItemKind::Struct(ident, struct_def, generics) => self.expand_struct_def( + ast::ItemKind::Struct(ident, generics, struct_def) => self.expand_struct_def( cx, struct_def, *ident, @@ -496,7 +496,7 @@ impl<'a> TraitDef<'a> { from_scratch, is_packed, ), - ast::ItemKind::Enum(ident, enum_def, generics) => { + ast::ItemKind::Enum(ident, generics, enum_def) => { // We ignore `is_packed` here, because `repr(packed)` // enums cause an error later on. // @@ -504,7 +504,7 @@ impl<'a> TraitDef<'a> { // downstream in blatantly illegal code, so it is fine. self.expand_enum_def(cx, enum_def, *ident, generics, from_scratch) } - ast::ItemKind::Union(ident, struct_def, generics) => { + ast::ItemKind::Union(ident, generics, struct_def) => { if self.supports_unions { self.expand_struct_def( cx, diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 55751aa49089b..2accfba383e66 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1424,7 +1424,7 @@ pub fn parse_macro_name_and_helper_attrs( /// See #73345 and #83125 for more details. /// FIXME(#73933): Remove this eventually. fn pretty_printing_compatibility_hack(item: &Item, psess: &ParseSess) { - if let ast::ItemKind::Enum(ident, enum_def, _) = &item.kind + if let ast::ItemKind::Enum(ident, _, enum_def) = &item.kind && ident.name == sym::ProceduralMasqueradeDummyType && let [variant] = &*enum_def.variants && variant.ident.name == sym::Input diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index babc55ccc0f9e..c7b0eb11e5a03 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -1577,7 +1577,7 @@ impl<'a> Parser<'a> { }; let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() }; - Ok(ItemKind::Enum(ident, enum_definition, generics)) + Ok(ItemKind::Enum(ident, generics, enum_definition)) } fn parse_enum_variant(&mut self, span: Span) -> PResult<'a, Option> { @@ -1732,7 +1732,7 @@ impl<'a> Parser<'a> { return Err(self.dcx().create_err(err)); }; - Ok(ItemKind::Struct(ident, vdata, generics)) + Ok(ItemKind::Struct(ident, generics, vdata)) } /// Parses `union Foo { ... }`. @@ -1764,7 +1764,7 @@ impl<'a> Parser<'a> { return Err(err); }; - Ok(ItemKind::Union(ident, vdata, generics)) + Ok(ItemKind::Union(ident, generics, vdata)) } /// This function parses the fields of record structs: diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 3460c53782f34..c30ed781f35f3 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -823,7 +823,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { } // These items live in both the type and value namespaces. - ItemKind::Struct(ident, ref vdata, _) => { + ItemKind::Struct(ident, _, ref vdata) => { self.build_reduced_graph_for_struct_variant( vdata.fields(), ident, @@ -874,7 +874,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { } } - ItemKind::Union(ident, ref vdata, _) => { + ItemKind::Union(ident, _, ref vdata) => { self.build_reduced_graph_for_struct_variant( vdata.fields(), ident, diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index 13dfb59f27fc0..25485be562269 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -162,8 +162,8 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { self.with_parent(def_id, |this| { this.with_impl_trait(ImplTraitContext::Existential, |this| { match i.kind { - ItemKind::Struct(_, ref struct_def, _) - | ItemKind::Union(_, ref struct_def, _) => { + ItemKind::Struct(_, _, ref struct_def) + | ItemKind::Union(_, _, ref struct_def) => { // If this is a unit or tuple-like struct, register the constructor. if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(struct_def) { this.create_def( diff --git a/compiler/rustc_resolve/src/effective_visibilities.rs b/compiler/rustc_resolve/src/effective_visibilities.rs index a5ca4565d7b42..5de80de3f8d37 100644 --- a/compiler/rustc_resolve/src/effective_visibilities.rs +++ b/compiler/rustc_resolve/src/effective_visibilities.rs @@ -252,7 +252,7 @@ impl<'a, 'ra, 'tcx> Visitor<'a> for EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> self.current_private_vis = prev_private_vis; } - ast::ItemKind::Enum(_, EnumDef { ref variants }, _) => { + ast::ItemKind::Enum(_, _, EnumDef { ref variants }) => { self.set_bindings_effective_visibilities(def_id); for variant in variants { let variant_def_id = self.r.local_def_id(variant.id); @@ -262,7 +262,7 @@ impl<'a, 'ra, 'tcx> Visitor<'a> for EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> } } - ast::ItemKind::Struct(_, ref def, _) | ast::ItemKind::Union(_, ref def, _) => { + ast::ItemKind::Struct(_, _, ref def) | ast::ItemKind::Union(_, _, ref def) => { for field in def.fields() { self.update_field(self.r.local_def_id(field.id), def_id); } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index fd977a8eb6c0b..4cfa079e49b44 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -2694,9 +2694,9 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { self.resolve_define_opaques(define_opaque); } - ItemKind::Enum(_, _, ref generics) - | ItemKind::Struct(_, _, ref generics) - | ItemKind::Union(_, _, ref generics) => { + ItemKind::Enum(_, ref generics, _) + | ItemKind::Struct(_, ref generics, _) + | ItemKind::Union(_, ref generics, _) => { self.resolve_adt(item, generics); } @@ -5243,9 +5243,9 @@ impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> { ItemKind::TyAlias(box TyAlias { generics, .. }) | ItemKind::Const(box ConstItem { generics, .. }) | ItemKind::Fn(box Fn { generics, .. }) - | ItemKind::Enum(_, _, generics) - | ItemKind::Struct(_, _, generics) - | ItemKind::Union(_, _, generics) + | ItemKind::Enum(_, generics, _) + | ItemKind::Struct(_, generics, _) + | ItemKind::Union(_, generics, _) | ItemKind::Impl(box Impl { generics, .. }) | ItemKind::Trait(box Trait { generics, .. }) | ItemKind::TraitAlias(_, generics, _) => { diff --git a/src/tools/clippy/clippy_lints/src/field_scoped_visibility_modifiers.rs b/src/tools/clippy/clippy_lints/src/field_scoped_visibility_modifiers.rs index aae8291905d37..dfb0b4f103c5f 100644 --- a/src/tools/clippy/clippy_lints/src/field_scoped_visibility_modifiers.rs +++ b/src/tools/clippy/clippy_lints/src/field_scoped_visibility_modifiers.rs @@ -51,7 +51,7 @@ declare_lint_pass!(FieldScopedVisibilityModifiers => [FIELD_SCOPED_VISIBILITY_MO impl EarlyLintPass for FieldScopedVisibilityModifiers { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) { - let ItemKind::Struct(_, ref st, _) = item.kind else { + let ItemKind::Struct(_, _, ref st) = item.kind else { return; }; for field in st.fields() { diff --git a/src/tools/clippy/clippy_lints/src/partial_pub_fields.rs b/src/tools/clippy/clippy_lints/src/partial_pub_fields.rs index cda752d003fa0..65e93af9420dd 100644 --- a/src/tools/clippy/clippy_lints/src/partial_pub_fields.rs +++ b/src/tools/clippy/clippy_lints/src/partial_pub_fields.rs @@ -41,7 +41,7 @@ declare_lint_pass!(PartialPubFields => [PARTIAL_PUB_FIELDS]); impl EarlyLintPass for PartialPubFields { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) { - let ItemKind::Struct(_, ref st, _) = item.kind else { + let ItemKind::Struct(_, _, ref st) = item.kind else { return; }; diff --git a/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs b/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs index 8996b694ed8f7..a0503a699e691 100644 --- a/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs @@ -436,11 +436,11 @@ pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool { && over(lb, rb, eq_generic_bound) && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r)) }, - (Enum(li, le, lg), Enum(ri, re, rg)) => { - eq_id(*li, *ri) && over(&le.variants, &re.variants, eq_variant) && eq_generics(lg, rg) + (Enum(li, lg, le), Enum(ri, rg, re)) => { + eq_id(*li, *ri) && eq_generics(lg, rg) && over(&le.variants, &re.variants, eq_variant) }, - (Struct(li, lv, lg), Struct(ri, rv, rg)) | (Union(li, lv, lg), Union(ri, rv, rg)) => { - eq_id(*li, *ri) && eq_variant_data(lv, rv) && eq_generics(lg, rg) + (Struct(li, lg, lv), Struct(ri, rg, rv)) | (Union(li, lg, lv), Union(ri, rg, rv)) => { + eq_id(*li, *ri) && eq_generics(lg, rg) && eq_variant_data(lv, rv) }, ( Trait(box ast::Trait { diff --git a/src/tools/rustfmt/src/items.rs b/src/tools/rustfmt/src/items.rs index e79b7803c6072..1a3897b51cb8f 100644 --- a/src/tools/rustfmt/src/items.rs +++ b/src/tools/rustfmt/src/items.rs @@ -1110,10 +1110,10 @@ impl<'a> StructParts<'a> { pub(crate) fn from_item(item: &'a ast::Item) -> Self { let (prefix, def, ident, generics) = match item.kind { - ast::ItemKind::Struct(ident, ref def, ref generics) => { + ast::ItemKind::Struct(ident, ref generics, ref def) => { ("struct ", def, ident, generics) } - ast::ItemKind::Union(ident, ref def, ref generics) => ("union ", def, ident, generics), + ast::ItemKind::Union(ident, ref generics, ref def) => ("union ", def, ident, generics), _ => unreachable!(), }; StructParts { diff --git a/src/tools/rustfmt/src/visitor.rs b/src/tools/rustfmt/src/visitor.rs index 16d1f5105d5f9..f6a9a3f2cd175 100644 --- a/src/tools/rustfmt/src/visitor.rs +++ b/src/tools/rustfmt/src/visitor.rs @@ -521,7 +521,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => { self.visit_struct(&StructParts::from_item(item)); } - ast::ItemKind::Enum(ident, ref def, ref generics) => { + ast::ItemKind::Enum(ident, ref generics, ref def) => { self.format_missing_with_indent(source!(self, item.span).lo()); self.visit_enum(ident, &item.vis, def, generics, item.span); self.last_pos = source!(self, item.span).hi(); From bf52d1a8037c15ea67c21d857cb9ae6e2829931b Mon Sep 17 00:00:00 2001 From: MarcoIeni <11428655+MarcoIeni@users.noreply.github.com> Date: Wed, 28 May 2025 10:23:38 +0200 Subject: [PATCH 12/24] ci: verify that codebuild jobs use ghcr.io --- src/ci/citool/src/jobs/tests.rs | 66 +++++++++++++++++++++++++++++++++ src/ci/citool/src/main.rs | 2 +- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/src/ci/citool/src/jobs/tests.rs b/src/ci/citool/src/jobs/tests.rs index a489656fa5dc7..ed5444d4333d3 100644 --- a/src/ci/citool/src/jobs/tests.rs +++ b/src/ci/citool/src/jobs/tests.rs @@ -1,4 +1,8 @@ +use std::path::Path; + +use super::Job; use crate::jobs::{JobDatabase, load_job_db}; +use crate::{DOCKER_DIRECTORY, JOBS_YML_PATH, utils}; #[test] fn lookup_job_pattern() { @@ -62,3 +66,65 @@ fn check_pattern(db: &JobDatabase, pattern: &str, expected: &[&str]) { assert_eq!(jobs, expected); } + +/// Validate that CodeBuild jobs use Docker images from ghcr.io registry. +/// This is needed because otherwise from CodeBuild we get rate limited by Docker Hub. +fn validate_codebuild_image(job: &Job) -> anyhow::Result<()> { + let is_job_on_codebuild = job.codebuild.unwrap_or(false); + if !is_job_on_codebuild { + // Jobs in GitHub Actions don't get rate limited by Docker Hub. + return Ok(()); + } + + let image_name = job.image(); + // we hardcode host-x86_64 here, because in codebuild we only run jobs for this architecture. + let dockerfile_path = + Path::new(DOCKER_DIRECTORY).join("host-x86_64").join(&image_name).join("Dockerfile"); + + if !dockerfile_path.exists() { + return Err(anyhow::anyhow!( + "Dockerfile not found for CodeBuild job '{}' at path: {}", + job.name, + dockerfile_path.display() + )); + } + + let dockerfile_content = utils::read_to_string(&dockerfile_path)?; + + // Check if all FROM statement uses ghcr.io registry + let has_ghcr_from = dockerfile_content + .lines() + .filter(|line| line.trim_start().to_lowercase().starts_with("from ")) + .all(|line| line.contains("ghcr.io")); + + if !has_ghcr_from { + return Err(anyhow::anyhow!( + "CodeBuild job '{}' must use ghcr.io registry in its Dockerfile FROM statement. \ + Dockerfile path: {dockerfile_path:?}", + job.name, + )); + } + + Ok(()) +} + +#[test] +fn validate_jobs() { + let db = { + let default_jobs_file = Path::new(JOBS_YML_PATH); + let db_str = utils::read_to_string(default_jobs_file).unwrap(); + load_job_db(&db_str).expect("Failed to load job database") + }; + + let all_jobs = + db.pr_jobs.iter().chain(db.try_jobs.iter()).chain(db.auto_jobs.iter()).collect::>(); + + let errors: Vec = + all_jobs.into_iter().filter_map(|job| validate_codebuild_image(job).err()).collect(); + + if !errors.is_empty() { + let error_messages = + errors.into_iter().map(|e| format!("- {e}")).collect::>().join("\n"); + panic!("Job validation failed:\n{error_messages}"); + } +} diff --git a/src/ci/citool/src/main.rs b/src/ci/citool/src/main.rs index 87ce09cfb233d..bb73a5ef909f2 100644 --- a/src/ci/citool/src/main.rs +++ b/src/ci/citool/src/main.rs @@ -27,7 +27,7 @@ use crate::test_dashboard::generate_test_dashboard; use crate::utils::{load_env_var, output_details}; const CI_DIRECTORY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/.."); -const DOCKER_DIRECTORY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../docker"); +pub const DOCKER_DIRECTORY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../docker"); const JOBS_YML_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../github-actions/jobs.yml"); struct GitHubContext { From 550aed825b3a630b5b2bd235e193bfce065268c2 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 26 May 2025 10:38:02 +0000 Subject: [PATCH 13/24] Use `builin_index` instead of hand-rolling it --- compiler/rustc_hir_analysis/src/check/wfcheck.rs | 3 +-- compiler/rustc_hir_typeck/src/expr.rs | 10 ++-------- compiler/rustc_pattern_analysis/src/rustc.rs | 6 +++--- .../clippy/clippy_lints/src/index_refutable_slice.rs | 5 ++--- .../clippy/clippy_lints/src/tuple_array_conversions.rs | 4 ++-- src/tools/clippy/clippy_utils/src/consts.rs | 4 +--- 6 files changed, 11 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 06c5e518fc646..0f17cbc0ce801 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1048,8 +1048,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(), match ty.kind() { ty::Adt(adt_def, ..) => adt_def.did().is_local(), // Arrays and slices use the inner type's `ConstParamTy`. - ty::Array(ty, ..) => ty_is_local(*ty), - ty::Slice(ty) => ty_is_local(*ty), + ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty), // `&` references use the inner type's `ConstParamTy`. // `&mut` are not supported. ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty), diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 1d86f7d223ce6..082ddac7e5ae2 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1793,10 +1793,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let element_ty = if !args.is_empty() { let coerce_to = expected .to_option(self) - .and_then(|uty| match *self.try_structurally_resolve_type(expr.span, uty).kind() { - ty::Array(ty, _) | ty::Slice(ty) => Some(ty), - _ => None, - }) + .and_then(|uty| self.try_structurally_resolve_type(expr.span, uty).builtin_index()) .unwrap_or_else(|| self.next_ty_var(expr.span)); let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args); assert_eq!(self.diverges.get(), Diverges::Maybe); @@ -1874,10 +1871,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let uty = match expected { - ExpectHasType(uty) => match *uty.kind() { - ty::Array(ty, _) | ty::Slice(ty) => Some(ty), - _ => None, - }, + ExpectHasType(uty) => uty.builtin_index(), _ => None, }; diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index d9f1888bfd9ad..46ced7500ea20 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -249,12 +249,12 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { ty::Ref(_, rty, _) => reveal_and_alloc(cx, once(*rty)), _ => bug!("Unexpected type for `Ref` constructor: {ty:?}"), }, - Slice(slice) => match *ty.kind() { - ty::Slice(ty) | ty::Array(ty, _) => { + Slice(slice) => match ty.builtin_index() { + Some(ty) => { let arity = slice.arity(); reveal_and_alloc(cx, (0..arity).map(|_| ty)) } - _ => bug!("bad slice pattern {:?} {:?}", ctor, ty), + None => bug!("bad slice pattern {:?} {:?}", ctor, ty), }, DerefPattern(pointee_ty) => reveal_and_alloc(cx, once(pointee_ty.inner())), Bool(..) | IntRange(..) | F16Range(..) | F32Range(..) | F64Range(..) diff --git a/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs b/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs index 0b1cae30ca501..3d131a7825aff 100644 --- a/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs +++ b/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs @@ -12,7 +12,6 @@ use rustc_hir::HirId; use rustc_hir::intravisit::{self, Visitor}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::nested_filter; -use rustc_middle::ty; use rustc_session::impl_lint_pass; use rustc_span::Span; use rustc_span::symbol::Ident; @@ -109,11 +108,11 @@ fn find_slice_values(cx: &LateContext<'_>, pat: &hir::Pat<'_>) -> FxIndexMap for TupleArrayConversions { } fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, elements: &'tcx [Expr<'tcx>]) { - let (ty::Array(ty, _) | ty::Slice(ty)) = cx.typeck_results().expr_ty(expr).kind() else { + let Some(ty) = cx.typeck_results().expr_ty(expr).builtin_index() else { unreachable!("`expr` must be an array or slice due to `ExprKind::Array`"); }; @@ -85,7 +85,7 @@ fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, elements: & ExprKind::Path(_) => Some(elements.iter().collect()), _ => None, }) - && all_bindings_are_for_conv(cx, &[*ty], expr, elements, &locals, ToType::Array) + && all_bindings_are_for_conv(cx, &[ty], expr, elements, &locals, ToType::Array) && !is_from_proc_macro(cx, expr) { span_lint_and_help( diff --git a/src/tools/clippy/clippy_utils/src/consts.rs b/src/tools/clippy/clippy_utils/src/consts.rs index 6f5b0ec54cd85..1ec5d11384f57 100644 --- a/src/tools/clippy/clippy_utils/src/consts.rs +++ b/src/tools/clippy/clippy_utils/src/consts.rs @@ -235,9 +235,7 @@ impl Constant<'_> { _ => None, }, (Self::Vec(l), Self::Vec(r)) => { - let (ty::Array(cmp_type, _) | ty::Slice(cmp_type)) = *cmp_type.kind() else { - return None; - }; + let cmp_type = cmp_type.builtin_index()?; iter::zip(l, r) .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri)) .find(|r| r.is_none_or(|o| o != Ordering::Equal)) From 0dd5722d6790be37b310c2e578be4f162d2be6ef Mon Sep 17 00:00:00 2001 From: Paul Mabileau Date: Fri, 16 May 2025 22:49:00 +0200 Subject: [PATCH 14/24] Test(fs): Fix test_eq_windows_file_type for Windows 7 Would otherwise fail on: ``` thread 'fs::tests::test_eq_windows_file_type' panicked at library/std/src/test_helpers.rs:53:20: called `Result::unwrap()` on an `Err` value: Os { code: 5, kind: PermissionDenied, message: "Access is denied." } ``` This came from the read-only attribute set on the test file. In order to fix this, instead of simply disabling the test, the attribute is reset before the test's end so it may still run successfully. Signed-off-by: Paul Mabileau --- library/std/src/fs/tests.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs index 8da6d75b73e17..c81e3af2f0d4c 100644 --- a/library/std/src/fs/tests.rs +++ b/library/std/src/fs/tests.rs @@ -1782,8 +1782,30 @@ fn test_eq_windows_file_type() { // Change the readonly attribute of one file. let mut perms = file1.metadata().unwrap().permissions(); perms.set_readonly(true); - file1.set_permissions(perms).unwrap(); + file1.set_permissions(perms.clone()).unwrap(); + #[cfg(target_vendor = "win7")] + let _g = ReadonlyGuard { file: &file1, perms }; assert_eq!(file1.metadata().unwrap().file_type(), file2.metadata().unwrap().file_type()); + + // Reset the attribute before the `TmpDir`'s drop that removes the + // associated directory, which fails with a `PermissionDenied` error when + // running under Windows 7. + #[cfg(target_vendor = "win7")] + struct ReadonlyGuard<'f> { + file: &'f File, + perms: fs::Permissions, + } + #[cfg(target_vendor = "win7")] + impl<'f> Drop for ReadonlyGuard<'f> { + fn drop(&mut self) { + self.perms.set_readonly(false); + let res = self.file.set_permissions(self.perms.clone()); + + if !thread::panicking() { + res.unwrap(); + } + } + } } /// Regression test for https://github.com/rust-lang/rust/issues/50619. From 9389daab8d37298587305127f587e4fdd0f20598 Mon Sep 17 00:00:00 2001 From: David Klank <155117116+davidjsonn@users.noreply.github.com> Date: Wed, 28 May 2025 13:50:38 +0300 Subject: [PATCH 15/24] replace TraitRef link memory.md --- src/doc/rustc-dev-guide/src/memory.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/src/memory.md b/src/doc/rustc-dev-guide/src/memory.md index eeb4a813980a6..f766a51898e41 100644 --- a/src/doc/rustc-dev-guide/src/memory.md +++ b/src/doc/rustc-dev-guide/src/memory.md @@ -63,7 +63,7 @@ represented as a slice `&'tcx [tcx.types.i32, tcx.types.u32]`). [`mk_args`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.mk_args [adtdefid]: ./ty_module/generic_arguments.md#adtdef-and-defid [`Predicate`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.Predicate.html -[`TraitRef`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TraitRef.html +[`TraitRef`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/type.TraitRef.html [`ty::TyKind`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/sty/type.TyKind.html [traits]: ./traits/resolution.md From bcebf58accb50f2252a1bf728a8da2316a1c1e48 Mon Sep 17 00:00:00 2001 From: Nia Espera Date: Wed, 28 May 2025 13:04:37 +0200 Subject: [PATCH 16/24] interpret/allocation: make alloc fn be FnOnce --- compiler/rustc_middle/src/mir/interpret/allocation.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index f17747558fc55..dd55d039794f7 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -512,7 +512,7 @@ impl Allocation { pub fn adjust_from_tcx<'tcx, Prov: Provenance, Bytes: AllocBytes>( &self, cx: &impl HasDataLayout, - mut alloc_bytes: impl FnMut(&[u8], Align) -> InterpResult<'tcx, Bytes>, + alloc_bytes: impl FnOnce(&[u8], Align) -> InterpResult<'tcx, Bytes>, mut adjust_ptr: impl FnMut(Pointer) -> InterpResult<'tcx, Pointer>, ) -> InterpResult<'tcx, Allocation> { // Copy the data. From 3a736e2726dcd4cb534eaf64b25196fa45a26a03 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 28 May 2025 12:17:18 +0000 Subject: [PATCH 17/24] Handle e2021 precise capturing of unsafe binder --- compiler/rustc_middle/src/ty/closure.rs | 4 ++++ compiler/rustc_mir_build/src/builder/expr/as_place.rs | 4 ++-- tests/ui/unsafe-binders/cat-projection.rs | 3 +++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index ff9096695d4db..df67bb505a689 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -117,6 +117,10 @@ impl<'tcx> CapturedPlace<'tcx> { } }, + HirProjectionKind::UnwrapUnsafeBinder => { + write!(&mut symbol, "__unwrap").unwrap(); + } + // Ignore derefs for now, as they are likely caused by // autoderefs that don't appear in the original code. HirProjectionKind::Deref => {} 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 830a129c58542..f8c64d7d13ed5 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_place.rs @@ -101,12 +101,12 @@ fn convert_to_hir_projections_and_truncate_for_capture( variant = Some(*idx); continue; } + ProjectionElem::UnwrapUnsafeBinder(_) => HirProjectionKind::UnwrapUnsafeBinder, // These do not affect anything, they just make sure we know the right type. ProjectionElem::OpaqueCast(_) | ProjectionElem::Subtype(..) => continue, ProjectionElem::Index(..) | ProjectionElem::ConstantIndex { .. } - | ProjectionElem::Subslice { .. } - | ProjectionElem::UnwrapUnsafeBinder(_) => { + | ProjectionElem::Subslice { .. } => { // We don't capture array-access projections. // We can stop here as arrays are captured completely. break; diff --git a/tests/ui/unsafe-binders/cat-projection.rs b/tests/ui/unsafe-binders/cat-projection.rs index dd7a78d59b364..0ce8579a68827 100644 --- a/tests/ui/unsafe-binders/cat-projection.rs +++ b/tests/ui/unsafe-binders/cat-projection.rs @@ -1,3 +1,6 @@ +//@ revisions: e2015 e2021 +//@[e2015] edition: 2015 +//@[e2021] edition: 2021 //@ check-pass #![feature(unsafe_binders)] From d88641f8bc4c9ad1e0f528f0834c14da302be447 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 28 May 2025 15:36:32 +0300 Subject: [PATCH 18/24] rustbook: Bump versions of `onig` and `onig_sys` This fixes the build on GCC 15 --- src/tools/rustbook/Cargo.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tools/rustbook/Cargo.lock b/src/tools/rustbook/Cargo.lock index 07c5106331bf5..8893846b5fa54 100644 --- a/src/tools/rustbook/Cargo.lock +++ b/src/tools/rustbook/Cargo.lock @@ -1026,11 +1026,11 @@ checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "onig" -version = "6.4.0" +version = "6.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c4b31c8722ad9171c6d77d3557db078cab2bd50afcc9d09c8b315c59df8ca4f" +checksum = "336b9c63443aceef14bea841b899035ae3abe89b7c486aaf4c5bd8aafedac3f0" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.9.0", "libc", "once_cell", "onig_sys", @@ -1038,9 +1038,9 @@ dependencies = [ [[package]] name = "onig_sys" -version = "69.8.1" +version = "69.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b829e3d7e9cc74c7e315ee8edb185bf4190da5acde74afd7fc59c35b1f086e7" +checksum = "c7f86c6eef3d6df15f23bcfb6af487cbd2fed4e5581d58d5bf1f5f8b7f6727dc" dependencies = [ "cc", "pkg-config", From 2e99a880e22f5a1f3800e1a26828b188204d037e Mon Sep 17 00:00:00 2001 From: Patrick-6 Date: Wed, 28 May 2025 15:12:56 +0200 Subject: [PATCH 19/24] Add diagnostic items to sys::Mutex --- compiler/rustc_span/src/symbol.rs | 3 +++ library/std/src/sys/sync/mutex/futex.rs | 3 +++ library/std/src/sys/sync/mutex/pthread.rs | 3 +++ 3 files changed, 9 insertions(+) diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 0447713fb05d0..58091bc32d22a 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2071,6 +2071,9 @@ symbols! { sym, sync, synthetic, + sys_mutex_lock, + sys_mutex_try_lock, + sys_mutex_unlock, t32, target, target_abi, diff --git a/library/std/src/sys/sync/mutex/futex.rs b/library/std/src/sys/sync/mutex/futex.rs index ce9b2daa5f808..01e91a6294a45 100644 --- a/library/std/src/sys/sync/mutex/futex.rs +++ b/library/std/src/sys/sync/mutex/futex.rs @@ -19,11 +19,13 @@ impl Mutex { } #[inline] + #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_try_lock")] pub fn try_lock(&self) -> bool { self.futex.compare_exchange(UNLOCKED, LOCKED, Acquire, Relaxed).is_ok() } #[inline] + #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_lock")] pub fn lock(&self) { if self.futex.compare_exchange(UNLOCKED, LOCKED, Acquire, Relaxed).is_err() { self.lock_contended(); @@ -80,6 +82,7 @@ impl Mutex { } #[inline] + #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_unlock")] pub unsafe fn unlock(&self) { if self.futex.swap(UNLOCKED, Release) == CONTENDED { // We only wake up one thread. When that thread locks the mutex, it diff --git a/library/std/src/sys/sync/mutex/pthread.rs b/library/std/src/sys/sync/mutex/pthread.rs index 75b4b9c6dad9b..52588a7899a73 100644 --- a/library/std/src/sys/sync/mutex/pthread.rs +++ b/library/std/src/sys/sync/mutex/pthread.rs @@ -28,6 +28,7 @@ impl Mutex { } #[inline] + #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_lock")] pub fn lock(&self) { // SAFETY: we call `init` above, therefore reentrant locking is safe. // In `drop` we ensure that the mutex is not destroyed while locked. @@ -35,6 +36,7 @@ impl Mutex { } #[inline] + #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_unlock")] pub unsafe fn unlock(&self) { // SAFETY: the mutex can only be locked if it is already initialized // and we observed this initialization since we observed the locking. @@ -42,6 +44,7 @@ impl Mutex { } #[inline] + #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_try_lock")] pub fn try_lock(&self) -> bool { // SAFETY: we call `init` above, therefore reentrant locking is safe. // In `drop` we ensure that the mutex is not destroyed while locked. From 149b5b2567535af761d16ed388b653740db7a457 Mon Sep 17 00:00:00 2001 From: Patrick-6 Date: Wed, 28 May 2025 15:13:38 +0200 Subject: [PATCH 20/24] Make pthread Mutex internals less public --- library/std/src/sys/sync/mutex/pthread.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/sync/mutex/pthread.rs b/library/std/src/sys/sync/mutex/pthread.rs index 52588a7899a73..1d442248374d5 100644 --- a/library/std/src/sys/sync/mutex/pthread.rs +++ b/library/std/src/sys/sync/mutex/pthread.rs @@ -6,7 +6,7 @@ use crate::sys::pal::sync as pal; use crate::sys::sync::OnceBox; pub struct Mutex { - pub pal: OnceBox, + pub(in crate::sys::sync) pal: OnceBox, } impl Mutex { From 9f12748086823f58bc03ab5f4390e98a69991127 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sun, 2 Feb 2025 11:26:20 +0100 Subject: [PATCH 21/24] GCI: Check where-clauses for well-formedness at the def site --- .../rustc_hir_analysis/src/check/wfcheck.rs | 41 +++++++++++++++---- .../def-site-predicates-wf.rs | 9 ++++ .../def-site-predicates-wf.stderr | 13 ++++++ 3 files changed, 55 insertions(+), 8 deletions(-) create mode 100644 tests/ui/generic-const-items/def-site-predicates-wf.rs create mode 100644 tests/ui/generic-const-items/def-site-predicates-wf.stderr diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 06c5e518fc646..5070ab138c520 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -298,11 +298,9 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) -> Result<() check_item_fn(tcx, def_id, ident, item.span, sig.decl) } hir::ItemKind::Static(_, ty, ..) => { - check_item_type(tcx, def_id, ty.span, UnsizedHandling::Forbid) - } - hir::ItemKind::Const(_, ty, ..) => { - check_item_type(tcx, def_id, ty.span, UnsizedHandling::Forbid) + check_static_item(tcx, def_id, ty.span, UnsizedHandling::Forbid) } + hir::ItemKind::Const(_, ty, ..) => check_const_item(tcx, def_id, ty.span, item.span), hir::ItemKind::Struct(_, _, hir_generics) => { let res = check_type_defn(tcx, item, false); check_variances_for_type_defn(tcx, item, hir_generics); @@ -366,7 +364,7 @@ fn check_foreign_item<'tcx>( check_item_fn(tcx, def_id, item.ident, item.span, sig.decl) } hir::ForeignItemKind::Static(ty, ..) => { - check_item_type(tcx, def_id, ty.span, UnsizedHandling::AllowIfForeignTail) + check_static_item(tcx, def_id, ty.span, UnsizedHandling::AllowIfForeignTail) } hir::ForeignItemKind::Type => Ok(()), } @@ -1331,14 +1329,13 @@ enum UnsizedHandling { AllowIfForeignTail, } -fn check_item_type( +#[instrument(level = "debug", skip(tcx, ty_span, unsized_handling))] +fn check_static_item( tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, unsized_handling: UnsizedHandling, ) -> Result<(), ErrorGuaranteed> { - debug!("check_item_type: {:?}", item_id); - enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| { let ty = tcx.type_of(item_id).instantiate_identity(); let item_ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty); @@ -1388,6 +1385,34 @@ fn check_item_type( }) } +fn check_const_item( + tcx: TyCtxt<'_>, + def_id: LocalDefId, + ty_span: Span, + item_span: Span, +) -> Result<(), ErrorGuaranteed> { + enter_wf_checking_ctxt(tcx, ty_span, def_id, |wfcx| { + let ty = tcx.type_of(def_id).instantiate_identity(); + let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty); + + wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into()); + wfcx.register_bound( + traits::ObligationCause::new( + ty_span, + wfcx.body_def_id, + ObligationCauseCode::SizedConstOrStatic, + ), + wfcx.param_env, + ty, + tcx.require_lang_item(LangItem::Sized, None), + ); + + check_where_clauses(wfcx, item_span, def_id); + + Ok(()) + }) +} + #[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))] fn check_impl<'tcx>( tcx: TyCtxt<'tcx>, diff --git a/tests/ui/generic-const-items/def-site-predicates-wf.rs b/tests/ui/generic-const-items/def-site-predicates-wf.rs new file mode 100644 index 0000000000000..39cdcc304f3e9 --- /dev/null +++ b/tests/ui/generic-const-items/def-site-predicates-wf.rs @@ -0,0 +1,9 @@ +//! Ensure that we check the predicates for well-formedness at the definition site. +#![feature(generic_const_items)] +#![expect(incomplete_features)] + +const _: () = () +where + Vec: Sized; //~ ERROR the size for values of type `str` cannot be known at compilation time + +fn main() {} diff --git a/tests/ui/generic-const-items/def-site-predicates-wf.stderr b/tests/ui/generic-const-items/def-site-predicates-wf.stderr new file mode 100644 index 0000000000000..62db089fd5573 --- /dev/null +++ b/tests/ui/generic-const-items/def-site-predicates-wf.stderr @@ -0,0 +1,13 @@ +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/def-site-predicates-wf.rs:7:15 + | +LL | Vec: Sized; + | ^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` +note: required by an implicit `Sized` bound in `Vec` + --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. From 2593df8837f330301b5679e33efd54f36ba43c43 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 28 May 2025 15:06:08 +0200 Subject: [PATCH 22/24] core: unstably expose atomic_compare_exchange so stdarch can use it --- library/core/src/sync/atomic.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index bd5a58d74ba0d..6bc6bee682df6 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -3885,10 +3885,13 @@ unsafe fn atomic_sub(dst: *mut T, val: T, order: Ordering) -> T { } } +/// Publicly exposed for stdarch; nobody else should use this. #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -unsafe fn atomic_compare_exchange( +#[unstable(feature = "core_intrinsics", issue = "none")] +#[doc(hidden)] +pub unsafe fn atomic_compare_exchange( dst: *mut T, old: T, new: T, From 8237107d88866d4f4525f77384c653d4c80ad4df Mon Sep 17 00:00:00 2001 From: Patrick-6 Date: Wed, 28 May 2025 17:05:45 +0200 Subject: [PATCH 23/24] Add comments to diagnostic items --- library/std/src/sys/sync/mutex/futex.rs | 3 +++ library/std/src/sys/sync/mutex/pthread.rs | 3 +++ 2 files changed, 6 insertions(+) diff --git a/library/std/src/sys/sync/mutex/futex.rs b/library/std/src/sys/sync/mutex/futex.rs index 01e91a6294a45..70e2ea9f60586 100644 --- a/library/std/src/sys/sync/mutex/futex.rs +++ b/library/std/src/sys/sync/mutex/futex.rs @@ -19,12 +19,14 @@ impl Mutex { } #[inline] + // Make this a diagnostic item for Miri's concurrency model checker. #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_try_lock")] pub fn try_lock(&self) -> bool { self.futex.compare_exchange(UNLOCKED, LOCKED, Acquire, Relaxed).is_ok() } #[inline] + // Make this a diagnostic item for Miri's concurrency model checker. #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_lock")] pub fn lock(&self) { if self.futex.compare_exchange(UNLOCKED, LOCKED, Acquire, Relaxed).is_err() { @@ -82,6 +84,7 @@ impl Mutex { } #[inline] + // Make this a diagnostic item for Miri's concurrency model checker. #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_unlock")] pub unsafe fn unlock(&self) { if self.futex.swap(UNLOCKED, Release) == CONTENDED { diff --git a/library/std/src/sys/sync/mutex/pthread.rs b/library/std/src/sys/sync/mutex/pthread.rs index 1d442248374d5..a7a3b47d0ec62 100644 --- a/library/std/src/sys/sync/mutex/pthread.rs +++ b/library/std/src/sys/sync/mutex/pthread.rs @@ -28,6 +28,7 @@ impl Mutex { } #[inline] + // Make this a diagnostic item for Miri's concurrency model checker. #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_lock")] pub fn lock(&self) { // SAFETY: we call `init` above, therefore reentrant locking is safe. @@ -36,6 +37,7 @@ impl Mutex { } #[inline] + // Make this a diagnostic item for Miri's concurrency model checker. #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_unlock")] pub unsafe fn unlock(&self) { // SAFETY: the mutex can only be locked if it is already initialized @@ -44,6 +46,7 @@ impl Mutex { } #[inline] + // Make this a diagnostic item for Miri's concurrency model checker. #[cfg_attr(not(test), rustc_diagnostic_item = "sys_mutex_try_lock")] pub fn try_lock(&self) -> bool { // SAFETY: we call `init` above, therefore reentrant locking is safe. From 9f2ee0f4fb1420f9b49faadaed6cd021135ff354 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Wed, 28 May 2025 11:30:18 -0700 Subject: [PATCH 24/24] Add eholk to compiler reviewer rotation Now that we have work queue limits on triagebot, I'm happy to share some of the review load. --- triagebot.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/triagebot.toml b/triagebot.toml index 12cbc926a4a88..b74159e5e5f11 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1196,6 +1196,7 @@ compiler = [ "@BoxyUwU", "@compiler-errors", "@davidtwco", + "@eholk", "@fee1-dead", "@fmease", "@jieyouxu",