From 7643ea5b9c241019ecabb29b3d1eb30450dc2412 Mon Sep 17 00:00:00 2001 From: binarycat Date: Wed, 24 Jul 2024 15:14:41 -0400 Subject: [PATCH 01/25] create a new section on pointer to reference conversion also start deduplicating the docs that are getting moved to this section. --- library/core/src/ptr/mod.rs | 24 ++++++++++++++++++++ library/core/src/ptr/mut_ptr.rs | 40 ++++----------------------------- 2 files changed, 28 insertions(+), 36 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index f2247e83ec5c5..683f1d57f2259 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -56,6 +56,30 @@ //! has size 0, i.e., even if memory is not actually touched. Consider using //! [`NonNull::dangling`] in such cases. //! +//! ## Pointer to reference conversion +//! When converting a pointer to a reference using `&*`, there are several +//! rules that must be followed: +//! * The pointer must be properly aligned. +//! +//! * It must be "dereferenceable" in the sense defined above +//! +//! * The pointer must point to an initialized instance of `T`. +//! +//! * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is +//! arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. +//! In particular, while this reference exists, the memory the pointer points to must +//! not get accessed (read or written) through any other pointer. +//! +//! If a pointer follows all of these rules, it is said to be +//! *convertable to a reference*. +//! +//! These apply even if the result is unused! +//! (The part about being initialized is not yet fully decided, but until +//! it is, the only safe approach is to ensure that they are indeed initialized.) +//! +//! An example of the implications of the above rules is that an expression such +//! as `unsafe { &*(0 as *const u8) }` is Immediate Undefined Behavior. +//! //! ## Allocated object //! //! An *allocated object* is a subset of program memory which is addressable diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 904d6c62dcf1e..c88b356ec743c 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -247,24 +247,7 @@ impl *mut T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * The pointer must point to an initialized instance of `T`. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// (The part about being initialized is not yet fully decided, but until - /// it is, the only safe approach is to ensure that they are indeed initialized.) - /// - /// [the module documentation]: crate::ptr#safety + /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// @@ -609,25 +592,10 @@ impl *mut T { /// /// # Safety /// - /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * The pointer must point to an initialized instance of `T`. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get accessed (read or written) through any other pointer. + /// When calling this method, you have to ensure that *either* + /// the pointer is null *or* + /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion) /// - /// This applies even if the result of this method is unused! - /// (The part about being initialized is not yet fully decided, but until - /// it is, the only safe approach is to ensure that they are indeed initialized.) - /// - /// [the module documentation]: crate::ptr#safety /// /// # Examples /// From 1073f97ed8ed11bad047fc0b647ed99b98afb7ca Mon Sep 17 00:00:00 2001 From: binarycat Date: Wed, 24 Jul 2024 16:36:33 -0400 Subject: [PATCH 02/25] remove duplicate explanations of the ptr to ref conversion rules --- library/core/src/ptr/const_ptr.rs | 54 ++--------------------- library/core/src/ptr/mod.rs | 34 ++++++++++---- library/core/src/ptr/mut_ptr.rs | 73 ++++--------------------------- library/core/src/ptr/non_null.rs | 72 +++++------------------------- 4 files changed, 50 insertions(+), 183 deletions(-) diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 3e7933e9eec86..8b9f7b57d0053 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -239,24 +239,7 @@ impl *const T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * The pointer must point to an initialized instance of `T`. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// (The part about being initialized is not yet fully decided, but until - /// it is, the only safe approach is to ensure that they are indeed initialized.) - /// - /// [the module documentation]: crate::ptr#safety + /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// @@ -302,24 +285,8 @@ impl *const T { /// /// # Safety /// - /// When calling this method, you have to ensure that all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * The pointer must point to an initialized instance of `T`. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// (The part about being initialized is not yet fully decided, but until - /// it is, the only safe approach is to ensure that they are indeed initialized.) - /// - /// [the module documentation]: crate::ptr#safety + /// When calling this method, you have to ensure that + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// @@ -350,20 +317,7 @@ impl *const T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// - /// [the module documentation]: crate::ptr#safety + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 683f1d57f2259..591705a69fdee 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -57,21 +57,39 @@ //! [`NonNull::dangling`] in such cases. //! //! ## Pointer to reference conversion -//! When converting a pointer to a reference using `&*`, there are several -//! rules that must be followed: +//! When converting a pointer to a reference `&T` using `&*`, +//! there are several rules that must be followed: +//! //! * The pointer must be properly aligned. //! -//! * It must be "dereferenceable" in the sense defined above +// some microprocessors may use address 0 for an interrupt vector. +// users of these microprocessors must always read/write address 0 through +// a raw pointer, not a reference. +//! * It must be non-null. +//! +//! * It must be "dereferenceable" in the sense defined above. //! -//! * The pointer must point to an initialized instance of `T`. +//! * The pointer must point to a valid instance of `T`. +//! This means that the created reference can only refer to +//! uninitialized memory through careful use of `MaybeUninit`. //! -//! * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is -//! arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. -//! In particular, while this reference exists, the memory the pointer points to must -//! not get accessed (read or written) through any other pointer. +//! * You must enforce Rust's aliasing rules, since the lifetime of the +//! created reference is arbitrarily chosen, +//! and does not necessarily reflect the actual lifetime of the data. +//! In particular, while this reference exists, +//! the memory the pointer points to must +//! not get accessed (read or written) through any raw pointer, +//! except for data inside an `UnsafeCell` +// ^ previous documentation was somewhat unclear on if modifications through +// an UnsafeCell are safe even if they would seemingly violate the exclusivity +// of a mut ref. //! //! If a pointer follows all of these rules, it is said to be //! *convertable to a reference*. +// ^ we use this term instead of saying that the produced reference must +// be valid, as the validity of a reference is easily confused for the +// validity of the thing it refers to, and while the two concepts are +// closly related, they are not identical. //! //! These apply even if the result is unused! //! (The part about being initialized is not yet fully decided, but until diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index c88b356ec743c..fb393ffadd5cd 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -296,24 +296,7 @@ impl *mut T { /// /// # Safety /// - /// When calling this method, you have to ensure that all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * The pointer must point to an initialized instance of `T`. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// (The part about being initialized is not yet fully decided, but until - /// it is, the only safe approach is to ensure that they are indeed initialized.) - /// - /// [the module documentation]: crate::ptr#safety + /// When calling this method, you have to ensure that the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// @@ -347,20 +330,9 @@ impl *mut T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// - /// [the module documentation]: crate::ptr#safety + /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion). + /// Note that because the created reference is to `MaybeUninit`, the + /// source pointer can point to uninitialized memory. /// /// # Examples /// @@ -594,7 +566,7 @@ impl *mut T { /// /// When calling this method, you have to ensure that *either* /// the pointer is null *or* - /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// /// # Examples @@ -643,24 +615,8 @@ impl *mut T { /// /// # Safety /// - /// When calling this method, you have to ensure that all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * The pointer must point to an initialized instance of `T`. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// (The part about being initialized is not yet fully decided, but until - /// it is, the only safe approach is to ensure that they are indeed initialized.) - /// - /// [the module documentation]: crate::ptr#safety + /// When calling this method, you have to ensure that + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// @@ -695,20 +651,7 @@ impl *mut T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get accessed (read or written) through any other pointer. - /// - /// This applies even if the result of this method is unused! - /// - /// [the module documentation]: crate::ptr#safety + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) #[inline] #[unstable(feature = "ptr_as_uninit", issue = "75402")] #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index 796c85d0cacc7..1e1cf780c28f0 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -128,20 +128,10 @@ impl NonNull { /// /// # Safety /// - /// When calling this method, you have to ensure that all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// - /// [the module documentation]: crate::ptr#safety + /// When calling this method, you have to ensure that + /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion). + /// Note that because the created reference is to `MaybeUninit`, the + /// source pointer can point to uninitialized memory. #[inline] #[must_use] #[unstable(feature = "ptr_as_uninit", issue = "75402")] @@ -162,20 +152,10 @@ impl NonNull { /// /// # Safety /// - /// When calling this method, you have to ensure that all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get accessed (read or written) through any other pointer. - /// - /// This applies even if the result of this method is unused! - /// - /// [the module documentation]: crate::ptr#safety + /// When calling this method, you have to ensure that + /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion). + /// Note that because the created reference is to `MaybeUninit`, the + /// source pointer can point to uninitialized memory. #[inline] #[must_use] #[unstable(feature = "ptr_as_uninit", issue = "75402")] @@ -361,22 +341,8 @@ impl NonNull { /// /// # Safety /// - /// When calling this method, you have to ensure that all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * The pointer must point to an initialized instance of `T`. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get mutated (except inside `UnsafeCell`). - /// - /// This applies even if the result of this method is unused! - /// (The part about being initialized is not yet fully decided, but until - /// it is, the only safe approach is to ensure that they are indeed initialized.) + /// When calling this method, you have to ensure that + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// @@ -412,22 +378,8 @@ impl NonNull { /// /// # Safety /// - /// When calling this method, you have to ensure that all of the following is true: - /// - /// * The pointer must be properly aligned. - /// - /// * It must be "dereferenceable" in the sense defined in [the module documentation]. - /// - /// * The pointer must point to an initialized instance of `T`. - /// - /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is - /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. - /// In particular, while this reference exists, the memory the pointer points to must - /// not get accessed (read or written) through any other pointer. - /// - /// This applies even if the result of this method is unused! - /// (The part about being initialized is not yet fully decided, but until - /// it is, the only safe approach is to ensure that they are indeed initialized.) + /// When calling this method, you have to ensure that + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) /// # Examples /// /// ``` From 3877a7bcf3176740b49c94a137b233e88ce0a401 Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 25 Jul 2024 11:53:07 -0400 Subject: [PATCH 03/25] clarify interactions with MaybeUninit and UnsafeCell --- library/core/src/ptr/mod.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 591705a69fdee..b2fb365d22745 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -69,9 +69,12 @@ //! //! * It must be "dereferenceable" in the sense defined above. //! -//! * The pointer must point to a valid instance of `T`. +//! * The pointer must point to a valid value of type `T`. //! This means that the created reference can only refer to -//! uninitialized memory through careful use of `MaybeUninit`. +//! uninitialized memory through careful use of `MaybeUninit`, +//! or if the uninitialized memory is entirly contained within +//! padding bytes, since +//! [padding has the same validity invariant as `MaybeUninit`][ucg-pad]. //! //! * You must enforce Rust's aliasing rules, since the lifetime of the //! created reference is arbitrarily chosen, @@ -79,10 +82,9 @@ //! In particular, while this reference exists, //! the memory the pointer points to must //! not get accessed (read or written) through any raw pointer, -//! except for data inside an `UnsafeCell` -// ^ previous documentation was somewhat unclear on if modifications through -// an UnsafeCell are safe even if they would seemingly violate the exclusivity -// of a mut ref. +//! except for data inside an `UnsafeCell`. +//! Note that aliased writes are always UB for mutable references, +//! even if they only modify `UnsafeCell` data. //! //! If a pointer follows all of these rules, it is said to be //! *convertable to a reference*. @@ -98,6 +100,8 @@ //! An example of the implications of the above rules is that an expression such //! as `unsafe { &*(0 as *const u8) }` is Immediate Undefined Behavior. //! +//! [ucgpad]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#padding +//! //! ## Allocated object //! //! An *allocated object* is a subset of program memory which is addressable From 194489473d6edf6d421d657b5716996f02230928 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 11 Jun 2024 10:27:44 +1000 Subject: [PATCH 04/25] Add `warn(unreachable_pub)` to several crates. It requires no additonal changes to these crates, but will prevent unnecessary `pub`s in the future. --- compiler/rustc_abi/src/lib.rs | 1 + compiler/rustc_ast/src/lib.rs | 1 + compiler/rustc_ast_ir/src/lib.rs | 1 + 3 files changed, 3 insertions(+) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 3dc548c4554a3..ea634d7485ef7 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -3,6 +3,7 @@ #![cfg_attr(feature = "nightly", doc(rust_logo))] #![cfg_attr(feature = "nightly", feature(rustdoc_internals))] #![cfg_attr(feature = "nightly", feature(step_trait))] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::fmt; diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index 27e9f3d137ffd..7730d0b4b78df 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -19,6 +19,7 @@ #![feature(never_type)] #![feature(rustdoc_internals)] #![feature(stmt_expr_attributes)] +#![warn(unreachable_pub)] // tidy-alphabetical-end pub mod util { diff --git a/compiler/rustc_ast_ir/src/lib.rs b/compiler/rustc_ast_ir/src/lib.rs index 1d0c76f6ceae8..eeed5d3615139 100644 --- a/compiler/rustc_ast_ir/src/lib.rs +++ b/compiler/rustc_ast_ir/src/lib.rs @@ -2,6 +2,7 @@ #![cfg_attr(feature = "nightly", allow(internal_features))] #![cfg_attr(feature = "nightly", feature(never_type))] #![cfg_attr(feature = "nightly", feature(rustc_attrs))] +#![warn(unreachable_pub)] // tidy-alphabetical-end #[cfg(feature = "nightly")] From f839309c74d08a2cc8fb0a6db5089bb6f70f669b Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 11 Jun 2024 10:40:10 +1000 Subject: [PATCH 05/25] Add `warn(unreachable_pub)` to `rustc_arena`. --- compiler/rustc_arena/src/lib.rs | 1 + compiler/rustc_arena/src/tests.rs | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_arena/src/lib.rs b/compiler/rustc_arena/src/lib.rs index f5f01348e4612..8493354014734 100644 --- a/compiler/rustc_arena/src/lib.rs +++ b/compiler/rustc_arena/src/lib.rs @@ -25,6 +25,7 @@ #![feature(rustc_attrs)] #![feature(rustdoc_internals)] #![feature(strict_provenance)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::alloc::Layout; diff --git a/compiler/rustc_arena/src/tests.rs b/compiler/rustc_arena/src/tests.rs index 9eaa292e9893c..bfde8abd5893a 100644 --- a/compiler/rustc_arena/src/tests.rs +++ b/compiler/rustc_arena/src/tests.rs @@ -32,7 +32,7 @@ impl TypedArena { } #[test] -pub fn test_unused() { +fn test_unused() { let arena: TypedArena = TypedArena::default(); assert!(arena.chunks.borrow().is_empty()); } @@ -75,7 +75,7 @@ fn test_arena_alloc_nested() { } #[test] -pub fn test_copy() { +fn test_copy() { let arena = TypedArena::default(); #[cfg(not(miri))] const N: usize = 100000; @@ -87,13 +87,13 @@ pub fn test_copy() { } #[bench] -pub fn bench_copy(b: &mut Bencher) { +fn bench_copy(b: &mut Bencher) { let arena = TypedArena::default(); b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 })) } #[bench] -pub fn bench_copy_nonarena(b: &mut Bencher) { +fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { let _: Box<_> = Box::new(Point { x: 1, y: 2, z: 3 }); }) @@ -106,7 +106,7 @@ struct Noncopy { } #[test] -pub fn test_noncopy() { +fn test_noncopy() { let arena = TypedArena::default(); #[cfg(not(miri))] const N: usize = 100000; @@ -118,7 +118,7 @@ pub fn test_noncopy() { } #[test] -pub fn test_typed_arena_zero_sized() { +fn test_typed_arena_zero_sized() { let arena = TypedArena::default(); #[cfg(not(miri))] const N: usize = 100000; @@ -130,7 +130,7 @@ pub fn test_typed_arena_zero_sized() { } #[test] -pub fn test_typed_arena_clear() { +fn test_typed_arena_clear() { let mut arena = TypedArena::default(); for _ in 0..10 { arena.clear(); @@ -145,7 +145,7 @@ pub fn test_typed_arena_clear() { } #[bench] -pub fn bench_typed_arena_clear(b: &mut Bencher) { +fn bench_typed_arena_clear(b: &mut Bencher) { let mut arena = TypedArena::default(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3 }); @@ -154,7 +154,7 @@ pub fn bench_typed_arena_clear(b: &mut Bencher) { } #[bench] -pub fn bench_typed_arena_clear_100(b: &mut Bencher) { +fn bench_typed_arena_clear_100(b: &mut Bencher) { let mut arena = TypedArena::default(); b.iter(|| { for _ in 0..100 { @@ -230,7 +230,7 @@ fn test_typed_arena_drop_small_count() { } #[bench] -pub fn bench_noncopy(b: &mut Bencher) { +fn bench_noncopy(b: &mut Bencher) { let arena = TypedArena::default(); b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec![1, 2, 3, 4, 5] }) @@ -238,7 +238,7 @@ pub fn bench_noncopy(b: &mut Bencher) { } #[bench] -pub fn bench_noncopy_nonarena(b: &mut Bencher) { +fn bench_noncopy_nonarena(b: &mut Bencher) { b.iter(|| { let _: Box<_> = Box::new(Noncopy { string: "hello world".to_string(), array: vec![1, 2, 3, 4, 5] }); From ea014b4d75d63c2c9d19a67abae5309790186525 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 11 Jun 2024 10:46:06 +1000 Subject: [PATCH 06/25] Add `warn(unreachable_pub)` to `rustc_ast_lowering`. --- compiler/rustc_ast_lowering/src/errors.rs | 80 +++++++++++------------ compiler/rustc_ast_lowering/src/item.rs | 2 +- compiler/rustc_ast_lowering/src/lib.rs | 1 + 3 files changed, 42 insertions(+), 41 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index 7a6c9d8d0d375..18019b3da9206 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -6,7 +6,7 @@ use rustc_span::{Span, Symbol}; #[derive(Diagnostic)] #[diag(ast_lowering_generic_type_with_parentheses, code = E0214)] -pub struct GenericTypeWithParentheses { +pub(crate) struct GenericTypeWithParentheses { #[primary_span] #[label] pub span: Span, @@ -16,7 +16,7 @@ pub struct GenericTypeWithParentheses { #[derive(Subdiagnostic)] #[multipart_suggestion(ast_lowering_use_angle_brackets, applicability = "maybe-incorrect")] -pub struct UseAngleBrackets { +pub(crate) struct UseAngleBrackets { #[suggestion_part(code = "<")] pub open_param: Span, #[suggestion_part(code = ">")] @@ -26,7 +26,7 @@ pub struct UseAngleBrackets { #[derive(Diagnostic)] #[diag(ast_lowering_invalid_abi, code = E0703)] #[note] -pub struct InvalidAbi { +pub(crate) struct InvalidAbi { #[primary_span] #[label] pub span: Span, @@ -38,7 +38,7 @@ pub struct InvalidAbi { pub suggestion: Option, } -pub struct InvalidAbiReason(pub &'static str); +pub(crate) struct InvalidAbiReason(pub &'static str); impl Subdiagnostic for InvalidAbiReason { fn add_to_diag_with>( @@ -57,7 +57,7 @@ impl Subdiagnostic for InvalidAbiReason { code = "{suggestion}", applicability = "maybe-incorrect" )] -pub struct InvalidAbiSuggestion { +pub(crate) struct InvalidAbiSuggestion { #[primary_span] pub span: Span, pub suggestion: String, @@ -65,7 +65,7 @@ pub struct InvalidAbiSuggestion { #[derive(Diagnostic)] #[diag(ast_lowering_assoc_ty_parentheses)] -pub struct AssocTyParentheses { +pub(crate) struct AssocTyParentheses { #[primary_span] pub span: Span, #[subdiagnostic] @@ -73,7 +73,7 @@ pub struct AssocTyParentheses { } #[derive(Subdiagnostic)] -pub enum AssocTyParenthesesSub { +pub(crate) enum AssocTyParenthesesSub { #[multipart_suggestion(ast_lowering_remove_parentheses)] Empty { #[suggestion_part(code = "")] @@ -91,7 +91,7 @@ pub enum AssocTyParenthesesSub { #[derive(Diagnostic)] #[diag(ast_lowering_misplaced_impl_trait, code = E0562)] #[note] -pub struct MisplacedImplTrait<'a> { +pub(crate) struct MisplacedImplTrait<'a> { #[primary_span] pub span: Span, pub position: DiagArgFromDisplay<'a>, @@ -99,7 +99,7 @@ pub struct MisplacedImplTrait<'a> { #[derive(Diagnostic)] #[diag(ast_lowering_assoc_ty_binding_in_dyn)] -pub struct MisplacedAssocTyBinding { +pub(crate) struct MisplacedAssocTyBinding { #[primary_span] pub span: Span, #[suggestion(code = " = impl", applicability = "maybe-incorrect", style = "verbose")] @@ -108,7 +108,7 @@ pub struct MisplacedAssocTyBinding { #[derive(Diagnostic)] #[diag(ast_lowering_underscore_expr_lhs_assign)] -pub struct UnderscoreExprLhsAssign { +pub(crate) struct UnderscoreExprLhsAssign { #[primary_span] #[label] pub span: Span, @@ -116,7 +116,7 @@ pub struct UnderscoreExprLhsAssign { #[derive(Diagnostic)] #[diag(ast_lowering_base_expression_double_dot, code = E0797)] -pub struct BaseExpressionDoubleDot { +pub(crate) struct BaseExpressionDoubleDot { #[primary_span] #[suggestion(code = "/* expr */", applicability = "has-placeholders", style = "verbose")] pub span: Span, @@ -124,7 +124,7 @@ pub struct BaseExpressionDoubleDot { #[derive(Diagnostic)] #[diag(ast_lowering_await_only_in_async_fn_and_blocks, code = E0728)] -pub struct AwaitOnlyInAsyncFnAndBlocks { +pub(crate) struct AwaitOnlyInAsyncFnAndBlocks { #[primary_span] #[label] pub await_kw_span: Span, @@ -134,21 +134,21 @@ pub struct AwaitOnlyInAsyncFnAndBlocks { #[derive(Diagnostic)] #[diag(ast_lowering_coroutine_too_many_parameters, code = E0628)] -pub struct CoroutineTooManyParameters { +pub(crate) struct CoroutineTooManyParameters { #[primary_span] pub fn_decl_span: Span, } #[derive(Diagnostic)] #[diag(ast_lowering_closure_cannot_be_static, code = E0697)] -pub struct ClosureCannotBeStatic { +pub(crate) struct ClosureCannotBeStatic { #[primary_span] pub fn_decl_span: Span, } #[derive(Diagnostic)] #[diag(ast_lowering_functional_record_update_destructuring_assignment)] -pub struct FunctionalRecordUpdateDestructuringAssignment { +pub(crate) struct FunctionalRecordUpdateDestructuringAssignment { #[primary_span] #[suggestion(code = "", applicability = "machine-applicable")] pub span: Span, @@ -156,28 +156,28 @@ pub struct FunctionalRecordUpdateDestructuringAssignment { #[derive(Diagnostic)] #[diag(ast_lowering_async_coroutines_not_supported, code = E0727)] -pub struct AsyncCoroutinesNotSupported { +pub(crate) struct AsyncCoroutinesNotSupported { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_lowering_inline_asm_unsupported_target, code = E0472)] -pub struct InlineAsmUnsupportedTarget { +pub(crate) struct InlineAsmUnsupportedTarget { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_lowering_att_syntax_only_x86)] -pub struct AttSyntaxOnlyX86 { +pub(crate) struct AttSyntaxOnlyX86 { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_lowering_abi_specified_multiple_times)] -pub struct AbiSpecifiedMultipleTimes { +pub(crate) struct AbiSpecifiedMultipleTimes { #[primary_span] pub abi_span: Span, pub prev_name: Symbol, @@ -189,7 +189,7 @@ pub struct AbiSpecifiedMultipleTimes { #[derive(Diagnostic)] #[diag(ast_lowering_clobber_abi_not_supported)] -pub struct ClobberAbiNotSupported { +pub(crate) struct ClobberAbiNotSupported { #[primary_span] pub abi_span: Span, } @@ -197,7 +197,7 @@ pub struct ClobberAbiNotSupported { #[derive(Diagnostic)] #[note] #[diag(ast_lowering_invalid_abi_clobber_abi)] -pub struct InvalidAbiClobberAbi { +pub(crate) struct InvalidAbiClobberAbi { #[primary_span] pub abi_span: Span, pub supported_abis: String, @@ -205,7 +205,7 @@ pub struct InvalidAbiClobberAbi { #[derive(Diagnostic)] #[diag(ast_lowering_invalid_register)] -pub struct InvalidRegister<'a> { +pub(crate) struct InvalidRegister<'a> { #[primary_span] pub op_span: Span, pub reg: Symbol, @@ -214,7 +214,7 @@ pub struct InvalidRegister<'a> { #[derive(Diagnostic)] #[diag(ast_lowering_invalid_register_class)] -pub struct InvalidRegisterClass<'a> { +pub(crate) struct InvalidRegisterClass<'a> { #[primary_span] pub op_span: Span, pub reg_class: Symbol, @@ -223,7 +223,7 @@ pub struct InvalidRegisterClass<'a> { #[derive(Diagnostic)] #[diag(ast_lowering_invalid_asm_template_modifier_reg_class)] -pub struct InvalidAsmTemplateModifierRegClass { +pub(crate) struct InvalidAsmTemplateModifierRegClass { #[primary_span] #[label(ast_lowering_template_modifier)] pub placeholder_span: Span, @@ -234,7 +234,7 @@ pub struct InvalidAsmTemplateModifierRegClass { } #[derive(Subdiagnostic)] -pub enum InvalidAsmTemplateModifierRegClassSub { +pub(crate) enum InvalidAsmTemplateModifierRegClassSub { #[note(ast_lowering_support_modifiers)] SupportModifier { class_name: Symbol, modifiers: String }, #[note(ast_lowering_does_not_support_modifiers)] @@ -243,7 +243,7 @@ pub enum InvalidAsmTemplateModifierRegClassSub { #[derive(Diagnostic)] #[diag(ast_lowering_invalid_asm_template_modifier_const)] -pub struct InvalidAsmTemplateModifierConst { +pub(crate) struct InvalidAsmTemplateModifierConst { #[primary_span] #[label(ast_lowering_template_modifier)] pub placeholder_span: Span, @@ -253,7 +253,7 @@ pub struct InvalidAsmTemplateModifierConst { #[derive(Diagnostic)] #[diag(ast_lowering_invalid_asm_template_modifier_sym)] -pub struct InvalidAsmTemplateModifierSym { +pub(crate) struct InvalidAsmTemplateModifierSym { #[primary_span] #[label(ast_lowering_template_modifier)] pub placeholder_span: Span, @@ -263,7 +263,7 @@ pub struct InvalidAsmTemplateModifierSym { #[derive(Diagnostic)] #[diag(ast_lowering_invalid_asm_template_modifier_label)] -pub struct InvalidAsmTemplateModifierLabel { +pub(crate) struct InvalidAsmTemplateModifierLabel { #[primary_span] #[label(ast_lowering_template_modifier)] pub placeholder_span: Span, @@ -273,7 +273,7 @@ pub struct InvalidAsmTemplateModifierLabel { #[derive(Diagnostic)] #[diag(ast_lowering_register_class_only_clobber)] -pub struct RegisterClassOnlyClobber { +pub(crate) struct RegisterClassOnlyClobber { #[primary_span] pub op_span: Span, pub reg_class_name: Symbol, @@ -281,7 +281,7 @@ pub struct RegisterClassOnlyClobber { #[derive(Diagnostic)] #[diag(ast_lowering_register_conflict)] -pub struct RegisterConflict<'a> { +pub(crate) struct RegisterConflict<'a> { #[primary_span] #[label(ast_lowering_register1)] pub op_span1: Span, @@ -296,7 +296,7 @@ pub struct RegisterConflict<'a> { #[derive(Diagnostic)] #[help] #[diag(ast_lowering_sub_tuple_binding)] -pub struct SubTupleBinding<'a> { +pub(crate) struct SubTupleBinding<'a> { #[primary_span] #[label] #[suggestion( @@ -313,7 +313,7 @@ pub struct SubTupleBinding<'a> { #[derive(Diagnostic)] #[diag(ast_lowering_extra_double_dot)] -pub struct ExtraDoubleDot<'a> { +pub(crate) struct ExtraDoubleDot<'a> { #[primary_span] #[label] pub span: Span, @@ -325,21 +325,21 @@ pub struct ExtraDoubleDot<'a> { #[derive(Diagnostic)] #[note] #[diag(ast_lowering_misplaced_double_dot)] -pub struct MisplacedDoubleDot { +pub(crate) struct MisplacedDoubleDot { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_lowering_misplaced_relax_trait_bound)] -pub struct MisplacedRelaxTraitBound { +pub(crate) struct MisplacedRelaxTraitBound { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_lowering_match_arm_with_no_body)] -pub struct MatchArmWithNoBody { +pub(crate) struct MatchArmWithNoBody { #[primary_span] pub span: Span, #[suggestion(code = " => todo!(),", applicability = "has-placeholders")] @@ -348,7 +348,7 @@ pub struct MatchArmWithNoBody { #[derive(Diagnostic)] #[diag(ast_lowering_never_pattern_with_body)] -pub struct NeverPatternWithBody { +pub(crate) struct NeverPatternWithBody { #[primary_span] #[label] #[suggestion(code = "", applicability = "maybe-incorrect")] @@ -357,7 +357,7 @@ pub struct NeverPatternWithBody { #[derive(Diagnostic)] #[diag(ast_lowering_never_pattern_with_guard)] -pub struct NeverPatternWithGuard { +pub(crate) struct NeverPatternWithGuard { #[primary_span] #[suggestion(code = "", applicability = "maybe-incorrect")] pub span: Span, @@ -365,7 +365,7 @@ pub struct NeverPatternWithGuard { #[derive(Diagnostic)] #[diag(ast_lowering_arbitrary_expression_in_pattern)] -pub struct ArbitraryExpressionInPattern { +pub(crate) struct ArbitraryExpressionInPattern { #[primary_span] pub span: Span, #[note(ast_lowering_pattern_from_macro_note)] @@ -374,13 +374,13 @@ pub struct ArbitraryExpressionInPattern { #[derive(Diagnostic)] #[diag(ast_lowering_inclusive_range_with_no_end)] -pub struct InclusiveRangeWithNoEnd { +pub(crate) struct InclusiveRangeWithNoEnd { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -pub enum BadReturnTypeNotation { +pub(crate) enum BadReturnTypeNotation { #[diag(ast_lowering_bad_return_type_notation_inputs)] Inputs { #[primary_span] diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 7af3945d3f99d..46ea7e6acb724 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1182,7 +1182,7 @@ impl<'hir> LoweringContext<'_, 'hir> { /// into the body. This is to make sure that the future actually owns the /// arguments that are passed to the function, and to ensure things like /// drop order are stable. - pub fn lower_coroutine_body_with_moved_arguments( + pub(crate) fn lower_coroutine_body_with_moved_arguments( &mut self, decl: &FnDecl, lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::Expr<'hir>, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 81d17a9dec205..43b56d7a91b12 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -37,6 +37,7 @@ #![feature(box_patterns)] #![feature(let_chains)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::collections::hash_map::Entry; From a6b2880d5a3f8faec20b96014792b21ae2c5bfbb Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 6 Jul 2024 21:19:05 +1000 Subject: [PATCH 07/25] Add `warn(unreachable_pub)` to `rustc_ast_passes`. --- compiler/rustc_ast_passes/src/errors.rs | 164 ++++++++++++------------ compiler/rustc_ast_passes/src/lib.rs | 1 + 2 files changed, 83 insertions(+), 82 deletions(-) diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 9e40368083729..d2c127a7bbb0d 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -11,7 +11,7 @@ use crate::fluent_generated as fluent; #[derive(Diagnostic)] #[diag(ast_passes_visibility_not_permitted, code = E0449)] -pub struct VisibilityNotPermitted { +pub(crate) struct VisibilityNotPermitted { #[primary_span] pub span: Span, #[subdiagnostic] @@ -25,7 +25,7 @@ pub struct VisibilityNotPermitted { } #[derive(Subdiagnostic)] -pub enum VisibilityNotPermittedNote { +pub(crate) enum VisibilityNotPermittedNote { #[note(ast_passes_enum_variant)] EnumVariant, #[note(ast_passes_trait_impl)] @@ -38,7 +38,7 @@ pub enum VisibilityNotPermittedNote { #[derive(Diagnostic)] #[diag(ast_passes_trait_fn_const, code = E0379)] -pub struct TraitFnConst { +pub(crate) struct TraitFnConst { #[primary_span] #[label] pub span: Span, @@ -64,21 +64,21 @@ pub struct TraitFnConst { #[derive(Diagnostic)] #[diag(ast_passes_forbidden_bound)] -pub struct ForbiddenBound { +pub(crate) struct ForbiddenBound { #[primary_span] pub spans: Vec, } #[derive(Diagnostic)] #[diag(ast_passes_forbidden_const_param)] -pub struct ForbiddenConstParam { +pub(crate) struct ForbiddenConstParam { #[primary_span] pub const_param_spans: Vec, } #[derive(Diagnostic)] #[diag(ast_passes_fn_param_too_many)] -pub struct FnParamTooMany { +pub(crate) struct FnParamTooMany { #[primary_span] pub span: Span, pub max_num_args: usize, @@ -86,14 +86,14 @@ pub struct FnParamTooMany { #[derive(Diagnostic)] #[diag(ast_passes_fn_param_c_var_args_not_last)] -pub struct FnParamCVarArgsNotLast { +pub(crate) struct FnParamCVarArgsNotLast { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_fn_param_doc_comment)] -pub struct FnParamDocComment { +pub(crate) struct FnParamDocComment { #[primary_span] #[label] pub span: Span, @@ -101,7 +101,7 @@ pub struct FnParamDocComment { #[derive(Diagnostic)] #[diag(ast_passes_fn_param_forbidden_attr)] -pub struct FnParamForbiddenAttr { +pub(crate) struct FnParamForbiddenAttr { #[primary_span] pub span: Span, } @@ -109,7 +109,7 @@ pub struct FnParamForbiddenAttr { #[derive(Diagnostic)] #[diag(ast_passes_fn_param_forbidden_self)] #[note] -pub struct FnParamForbiddenSelf { +pub(crate) struct FnParamForbiddenSelf { #[primary_span] #[label] pub span: Span, @@ -117,7 +117,7 @@ pub struct FnParamForbiddenSelf { #[derive(Diagnostic)] #[diag(ast_passes_forbidden_default)] -pub struct ForbiddenDefault { +pub(crate) struct ForbiddenDefault { #[primary_span] pub span: Span, #[label] @@ -126,7 +126,7 @@ pub struct ForbiddenDefault { #[derive(Diagnostic)] #[diag(ast_passes_assoc_const_without_body)] -pub struct AssocConstWithoutBody { +pub(crate) struct AssocConstWithoutBody { #[primary_span] pub span: Span, #[suggestion(code = " = ;", applicability = "has-placeholders")] @@ -135,7 +135,7 @@ pub struct AssocConstWithoutBody { #[derive(Diagnostic)] #[diag(ast_passes_assoc_fn_without_body)] -pub struct AssocFnWithoutBody { +pub(crate) struct AssocFnWithoutBody { #[primary_span] pub span: Span, #[suggestion(code = " {{ }}", applicability = "has-placeholders")] @@ -144,7 +144,7 @@ pub struct AssocFnWithoutBody { #[derive(Diagnostic)] #[diag(ast_passes_assoc_type_without_body)] -pub struct AssocTypeWithoutBody { +pub(crate) struct AssocTypeWithoutBody { #[primary_span] pub span: Span, #[suggestion(code = " = ;", applicability = "has-placeholders")] @@ -153,7 +153,7 @@ pub struct AssocTypeWithoutBody { #[derive(Diagnostic)] #[diag(ast_passes_const_without_body)] -pub struct ConstWithoutBody { +pub(crate) struct ConstWithoutBody { #[primary_span] pub span: Span, #[suggestion(code = " = ;", applicability = "has-placeholders")] @@ -162,7 +162,7 @@ pub struct ConstWithoutBody { #[derive(Diagnostic)] #[diag(ast_passes_static_without_body)] -pub struct StaticWithoutBody { +pub(crate) struct StaticWithoutBody { #[primary_span] pub span: Span, #[suggestion(code = " = ;", applicability = "has-placeholders")] @@ -171,7 +171,7 @@ pub struct StaticWithoutBody { #[derive(Diagnostic)] #[diag(ast_passes_ty_alias_without_body)] -pub struct TyAliasWithoutBody { +pub(crate) struct TyAliasWithoutBody { #[primary_span] pub span: Span, #[suggestion(code = " = ;", applicability = "has-placeholders")] @@ -180,7 +180,7 @@ pub struct TyAliasWithoutBody { #[derive(Diagnostic)] #[diag(ast_passes_fn_without_body)] -pub struct FnWithoutBody { +pub(crate) struct FnWithoutBody { #[primary_span] pub span: Span, #[suggestion(code = " {{ }}", applicability = "has-placeholders")] @@ -190,7 +190,7 @@ pub struct FnWithoutBody { } #[derive(Subdiagnostic)] -pub enum ExternBlockSuggestion { +pub(crate) enum ExternBlockSuggestion { #[multipart_suggestion(ast_passes_extern_block_suggestion, applicability = "maybe-incorrect")] Implicit { #[suggestion_part(code = "extern {{")] @@ -210,7 +210,7 @@ pub enum ExternBlockSuggestion { #[derive(Diagnostic)] #[diag(ast_passes_extern_invalid_safety)] -pub struct InvalidSafetyOnExtern { +pub(crate) struct InvalidSafetyOnExtern { #[primary_span] pub item_span: Span, #[suggestion(code = "unsafe ", applicability = "machine-applicable", style = "verbose")] @@ -219,28 +219,28 @@ pub struct InvalidSafetyOnExtern { #[derive(Diagnostic)] #[diag(ast_passes_item_invalid_safety)] -pub struct InvalidSafetyOnItem { +pub(crate) struct InvalidSafetyOnItem { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_bare_fn_invalid_safety)] -pub struct InvalidSafetyOnBareFn { +pub(crate) struct InvalidSafetyOnBareFn { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_unsafe_static)] -pub struct UnsafeStatic { +pub(crate) struct UnsafeStatic { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_bound_in_context)] -pub struct BoundInContext<'a> { +pub(crate) struct BoundInContext<'a> { #[primary_span] pub span: Span, pub ctx: &'a str, @@ -249,7 +249,7 @@ pub struct BoundInContext<'a> { #[derive(Diagnostic)] #[diag(ast_passes_extern_types_cannot)] #[note(ast_passes_extern_keyword_link)] -pub struct ExternTypesCannotHave<'a> { +pub(crate) struct ExternTypesCannotHave<'a> { #[primary_span] #[suggestion(code = "", applicability = "maybe-incorrect")] pub span: Span, @@ -262,7 +262,7 @@ pub struct ExternTypesCannotHave<'a> { #[derive(Diagnostic)] #[diag(ast_passes_body_in_extern)] #[note(ast_passes_extern_keyword_link)] -pub struct BodyInExtern<'a> { +pub(crate) struct BodyInExtern<'a> { #[primary_span] #[label(ast_passes_cannot_have)] pub span: Span, @@ -277,7 +277,7 @@ pub struct BodyInExtern<'a> { #[diag(ast_passes_fn_body_extern)] #[help] #[note(ast_passes_extern_keyword_link)] -pub struct FnBodyInExtern { +pub(crate) struct FnBodyInExtern { #[primary_span] #[label(ast_passes_cannot_have)] pub span: Span, @@ -289,7 +289,7 @@ pub struct FnBodyInExtern { #[derive(Diagnostic)] #[diag(ast_passes_extern_fn_qualifiers)] -pub struct FnQualifierInExtern { +pub(crate) struct FnQualifierInExtern { #[primary_span] #[suggestion(code = "", applicability = "maybe-incorrect")] pub span: Span, @@ -300,7 +300,7 @@ pub struct FnQualifierInExtern { #[derive(Diagnostic)] #[diag(ast_passes_extern_item_ascii)] #[note] -pub struct ExternItemAscii { +pub(crate) struct ExternItemAscii { #[primary_span] pub span: Span, #[label] @@ -309,14 +309,14 @@ pub struct ExternItemAscii { #[derive(Diagnostic)] #[diag(ast_passes_bad_c_variadic)] -pub struct BadCVariadic { +pub(crate) struct BadCVariadic { #[primary_span] pub span: Vec, } #[derive(Diagnostic)] #[diag(ast_passes_item_underscore)] -pub struct ItemUnderscore<'a> { +pub(crate) struct ItemUnderscore<'a> { #[primary_span] #[label] pub span: Span, @@ -325,7 +325,7 @@ pub struct ItemUnderscore<'a> { #[derive(Diagnostic)] #[diag(ast_passes_nomangle_ascii, code = E0754)] -pub struct NoMangleAscii { +pub(crate) struct NoMangleAscii { #[primary_span] pub span: Span, } @@ -333,7 +333,7 @@ pub struct NoMangleAscii { #[derive(Diagnostic)] #[diag(ast_passes_module_nonascii, code = E0754)] #[help] -pub struct ModuleNonAscii { +pub(crate) struct ModuleNonAscii { #[primary_span] pub span: Span, pub name: Symbol, @@ -341,7 +341,7 @@ pub struct ModuleNonAscii { #[derive(Diagnostic)] #[diag(ast_passes_auto_generic, code = E0567)] -pub struct AutoTraitGeneric { +pub(crate) struct AutoTraitGeneric { #[primary_span] #[suggestion(code = "", applicability = "machine-applicable")] pub span: Span, @@ -351,7 +351,7 @@ pub struct AutoTraitGeneric { #[derive(Diagnostic)] #[diag(ast_passes_auto_super_lifetime, code = E0568)] -pub struct AutoTraitBounds { +pub(crate) struct AutoTraitBounds { #[primary_span] #[suggestion(code = "", applicability = "machine-applicable")] pub span: Span, @@ -361,7 +361,7 @@ pub struct AutoTraitBounds { #[derive(Diagnostic)] #[diag(ast_passes_auto_items, code = E0380)] -pub struct AutoTraitItems { +pub(crate) struct AutoTraitItems { #[primary_span] pub spans: Vec, #[suggestion(code = "", applicability = "machine-applicable")] @@ -372,7 +372,7 @@ pub struct AutoTraitItems { #[derive(Diagnostic)] #[diag(ast_passes_generic_before_constraints)] -pub struct ArgsBeforeConstraint { +pub(crate) struct ArgsBeforeConstraint { #[primary_span] pub arg_spans: Vec, #[label(ast_passes_constraints)] @@ -390,7 +390,7 @@ pub struct ArgsBeforeConstraint { pub arg_spans2: EmptyLabelManySpans, } -pub struct EmptyLabelManySpans(pub Vec); +pub(crate) struct EmptyLabelManySpans(pub Vec); // The derive for `Vec` does multiple calls to `span_label`, adding commas between each impl Subdiagnostic for EmptyLabelManySpans { @@ -405,28 +405,28 @@ impl Subdiagnostic for EmptyLabelManySpans { #[derive(Diagnostic)] #[diag(ast_passes_pattern_in_fn_pointer, code = E0561)] -pub struct PatternFnPointer { +pub(crate) struct PatternFnPointer { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_trait_object_single_bound, code = E0226)] -pub struct TraitObjectBound { +pub(crate) struct TraitObjectBound { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_impl_trait_path, code = E0667)] -pub struct ImplTraitPath { +pub(crate) struct ImplTraitPath { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_nested_impl_trait, code = E0666)] -pub struct NestedImplTrait { +pub(crate) struct NestedImplTrait { #[primary_span] pub span: Span, #[label(ast_passes_outer)] @@ -437,14 +437,14 @@ pub struct NestedImplTrait { #[derive(Diagnostic)] #[diag(ast_passes_at_least_one_trait)] -pub struct AtLeastOneTrait { +pub(crate) struct AtLeastOneTrait { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_out_of_order_params)] -pub struct OutOfOrderParams<'a> { +pub(crate) struct OutOfOrderParams<'a> { #[primary_span] pub spans: Vec, #[suggestion(code = "{ordered_params}", applicability = "machine-applicable")] @@ -457,14 +457,14 @@ pub struct OutOfOrderParams<'a> { #[derive(Diagnostic)] #[diag(ast_passes_obsolete_auto)] #[help] -pub struct ObsoleteAuto { +pub(crate) struct ObsoleteAuto { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_unsafe_negative_impl, code = E0198)] -pub struct UnsafeNegativeImpl { +pub(crate) struct UnsafeNegativeImpl { #[primary_span] pub span: Span, #[label(ast_passes_negative)] @@ -475,7 +475,7 @@ pub struct UnsafeNegativeImpl { #[derive(Diagnostic)] #[diag(ast_passes_inherent_cannot_be)] -pub struct InherentImplCannot<'a> { +pub(crate) struct InherentImplCannot<'a> { #[primary_span] pub span: Span, #[label(ast_passes_because)] @@ -489,7 +489,7 @@ pub struct InherentImplCannot<'a> { #[derive(Diagnostic)] #[diag(ast_passes_inherent_cannot_be, code = E0197)] -pub struct InherentImplCannotUnsafe<'a> { +pub(crate) struct InherentImplCannotUnsafe<'a> { #[primary_span] pub span: Span, #[label(ast_passes_because)] @@ -501,7 +501,7 @@ pub struct InherentImplCannotUnsafe<'a> { #[derive(Diagnostic)] #[diag(ast_passes_unsafe_item)] -pub struct UnsafeItem { +pub(crate) struct UnsafeItem { #[primary_span] pub span: Span, pub kind: &'static str, @@ -509,14 +509,14 @@ pub struct UnsafeItem { #[derive(Diagnostic)] #[diag(ast_passes_missing_unsafe_on_extern)] -pub struct MissingUnsafeOnExtern { +pub(crate) struct MissingUnsafeOnExtern { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_fieldless_union)] -pub struct FieldlessUnion { +pub(crate) struct FieldlessUnion { #[primary_span] pub span: Span, } @@ -524,7 +524,7 @@ pub struct FieldlessUnion { #[derive(Diagnostic)] #[diag(ast_passes_where_clause_after_type_alias)] #[note] -pub struct WhereClauseAfterTypeAlias { +pub(crate) struct WhereClauseAfterTypeAlias { #[primary_span] pub span: Span, #[help] @@ -534,7 +534,7 @@ pub struct WhereClauseAfterTypeAlias { #[derive(Diagnostic)] #[diag(ast_passes_where_clause_before_type_alias)] #[note] -pub struct WhereClauseBeforeTypeAlias { +pub(crate) struct WhereClauseBeforeTypeAlias { #[primary_span] pub span: Span, #[subdiagnostic] @@ -543,7 +543,7 @@ pub struct WhereClauseBeforeTypeAlias { #[derive(Subdiagnostic)] -pub enum WhereClauseBeforeTypeAliasSugg { +pub(crate) enum WhereClauseBeforeTypeAliasSugg { #[suggestion(ast_passes_remove_suggestion, applicability = "machine-applicable", code = "")] Remove { #[primary_span] @@ -565,14 +565,14 @@ pub enum WhereClauseBeforeTypeAliasSugg { #[derive(Diagnostic)] #[diag(ast_passes_generic_default_trailing)] -pub struct GenericDefaultTrailing { +pub(crate) struct GenericDefaultTrailing { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_nested_lifetimes, code = E0316)] -pub struct NestedLifetimes { +pub(crate) struct NestedLifetimes { #[primary_span] pub span: Span, } @@ -580,7 +580,7 @@ pub struct NestedLifetimes { #[derive(Diagnostic)] #[diag(ast_passes_optional_trait_supertrait)] #[note] -pub struct OptionalTraitSupertrait { +pub(crate) struct OptionalTraitSupertrait { #[primary_span] pub span: Span, pub path_str: String, @@ -588,14 +588,14 @@ pub struct OptionalTraitSupertrait { #[derive(Diagnostic)] #[diag(ast_passes_optional_trait_object)] -pub struct OptionalTraitObject { +pub(crate) struct OptionalTraitObject { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_const_bound_trait_object)] -pub struct ConstBoundTraitObject { +pub(crate) struct ConstBoundTraitObject { #[primary_span] pub span: Span, } @@ -604,7 +604,7 @@ pub struct ConstBoundTraitObject { // FIXME(effects): Provide structured suggestions (e.g., add `const` / `#[const_trait]` here). #[derive(Diagnostic)] #[diag(ast_passes_tilde_const_disallowed)] -pub struct TildeConstDisallowed { +pub(crate) struct TildeConstDisallowed { #[primary_span] pub span: Span, #[subdiagnostic] @@ -612,7 +612,7 @@ pub struct TildeConstDisallowed { } #[derive(Subdiagnostic, Copy, Clone)] -pub enum TildeConstReason { +pub(crate) enum TildeConstReason { #[note(ast_passes_closure)] Closure, #[note(ast_passes_function)] @@ -658,7 +658,7 @@ pub enum TildeConstReason { #[derive(Diagnostic)] #[diag(ast_passes_const_and_async)] -pub struct ConstAndAsync { +pub(crate) struct ConstAndAsync { #[primary_span] pub spans: Vec, #[label(ast_passes_const)] @@ -671,7 +671,7 @@ pub struct ConstAndAsync { #[derive(Diagnostic)] #[diag(ast_passes_const_and_c_variadic)] -pub struct ConstAndCVariadic { +pub(crate) struct ConstAndCVariadic { #[primary_span] pub spans: Vec, #[label(ast_passes_const)] @@ -683,7 +683,7 @@ pub struct ConstAndCVariadic { #[derive(Diagnostic)] #[diag(ast_passes_pattern_in_foreign, code = E0130)] // FIXME: deduplicate with rustc_lint (`BuiltinLintDiag::PatternsInFnsWithoutBody`) -pub struct PatternInForeign { +pub(crate) struct PatternInForeign { #[primary_span] #[label] pub span: Span, @@ -692,7 +692,7 @@ pub struct PatternInForeign { #[derive(Diagnostic)] #[diag(ast_passes_pattern_in_bodiless, code = E0642)] // FIXME: deduplicate with rustc_lint (`BuiltinLintDiag::PatternsInFnsWithoutBody`) -pub struct PatternInBodiless { +pub(crate) struct PatternInBodiless { #[primary_span] #[label] pub span: Span, @@ -701,7 +701,7 @@ pub struct PatternInBodiless { #[derive(Diagnostic)] #[diag(ast_passes_equality_in_where)] #[note] -pub struct EqualityInWhere { +pub(crate) struct EqualityInWhere { #[primary_span] #[label] pub span: Span, @@ -718,7 +718,7 @@ pub struct EqualityInWhere { style = "verbose", applicability = "maybe-incorrect" )] -pub struct AssociatedSuggestion { +pub(crate) struct AssociatedSuggestion { #[primary_span] pub span: Span, pub ident: Ident, @@ -728,7 +728,7 @@ pub struct AssociatedSuggestion { #[derive(Subdiagnostic)] #[multipart_suggestion(ast_passes_suggestion_path, applicability = "maybe-incorrect")] -pub struct AssociatedSuggestion2 { +pub(crate) struct AssociatedSuggestion2 { #[suggestion_part(code = "{args}")] pub span: Span, pub args: String, @@ -740,14 +740,14 @@ pub struct AssociatedSuggestion2 { #[derive(Diagnostic)] #[diag(ast_passes_stability_outside_std, code = E0734)] -pub struct StabilityOutsideStd { +pub(crate) struct StabilityOutsideStd { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_feature_on_non_nightly, code = E0554)] -pub struct FeatureOnNonNightly { +pub(crate) struct FeatureOnNonNightly { #[primary_span] pub span: Span, pub channel: &'static str, @@ -757,7 +757,7 @@ pub struct FeatureOnNonNightly { pub sugg: Option, } -pub struct StableFeature { +pub(crate) struct StableFeature { pub name: Symbol, pub since: Symbol, } @@ -777,7 +777,7 @@ impl Subdiagnostic for StableFeature { #[derive(Diagnostic)] #[diag(ast_passes_incompatible_features)] #[help] -pub struct IncompatibleFeatures { +pub(crate) struct IncompatibleFeatures { #[primary_span] pub spans: Vec, pub f1: Symbol, @@ -786,7 +786,7 @@ pub struct IncompatibleFeatures { #[derive(Diagnostic)] #[diag(ast_passes_show_span)] -pub struct ShowSpan { +pub(crate) struct ShowSpan { #[primary_span] pub span: Span, pub msg: &'static str, @@ -794,28 +794,28 @@ pub struct ShowSpan { #[derive(Diagnostic)] #[diag(ast_passes_negative_bound_not_supported)] -pub struct NegativeBoundUnsupported { +pub(crate) struct NegativeBoundUnsupported { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_constraint_on_negative_bound)] -pub struct ConstraintOnNegativeBound { +pub(crate) struct ConstraintOnNegativeBound { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_negative_bound_with_parenthetical_notation)] -pub struct NegativeBoundWithParentheticalNotation { +pub(crate) struct NegativeBoundWithParentheticalNotation { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(ast_passes_invalid_unnamed_field_ty)] -pub struct InvalidUnnamedFieldTy { +pub(crate) struct InvalidUnnamedFieldTy { #[primary_span] pub span: Span, #[label] @@ -824,7 +824,7 @@ pub struct InvalidUnnamedFieldTy { #[derive(Diagnostic)] #[diag(ast_passes_invalid_unnamed_field)] -pub struct InvalidUnnamedField { +pub(crate) struct InvalidUnnamedField { #[primary_span] pub span: Span, #[label] @@ -833,7 +833,7 @@ pub struct InvalidUnnamedField { #[derive(Diagnostic)] #[diag(ast_passes_anon_struct_or_union_not_allowed)] -pub struct AnonStructOrUnionNotAllowed { +pub(crate) struct AnonStructOrUnionNotAllowed { #[primary_span] #[label] pub span: Span, @@ -842,7 +842,7 @@ pub struct AnonStructOrUnionNotAllowed { #[derive(Diagnostic)] #[diag(ast_passes_match_arm_with_no_body)] -pub struct MatchArmWithNoBody { +pub(crate) struct MatchArmWithNoBody { #[primary_span] pub span: Span, #[suggestion(code = " => todo!(),", applicability = "has-placeholders")] @@ -851,7 +851,7 @@ pub struct MatchArmWithNoBody { #[derive(Diagnostic)] #[diag(ast_passes_precise_capturing_not_allowed_here)] -pub struct PreciseCapturingNotAllowedHere { +pub(crate) struct PreciseCapturingNotAllowedHere { #[primary_span] pub span: Span, pub loc: &'static str, @@ -859,7 +859,7 @@ pub struct PreciseCapturingNotAllowedHere { #[derive(Diagnostic)] #[diag(ast_passes_precise_capturing_duplicated)] -pub struct DuplicatePreciseCapturing { +pub(crate) struct DuplicatePreciseCapturing { #[primary_span] pub bound1: Span, #[label] diff --git a/compiler/rustc_ast_passes/src/lib.rs b/compiler/rustc_ast_passes/src/lib.rs index 1f4bcd59afa01..88c6bde3106d5 100644 --- a/compiler/rustc_ast_passes/src/lib.rs +++ b/compiler/rustc_ast_passes/src/lib.rs @@ -12,6 +12,7 @@ #![feature(iter_is_partitioned)] #![feature(let_chains)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end pub mod ast_validation; From f2fc87db44413bc4706980481c057e30cac2efd9 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 6 Jul 2024 21:27:29 +1000 Subject: [PATCH 08/25] Add `warn(unreachable_pub)` to `rustc_ast_pretty`. --- compiler/rustc_ast_pretty/src/lib.rs | 1 + .../rustc_ast_pretty/src/pp/convenience.rs | 2 +- compiler/rustc_ast_pretty/src/pp/ring.rs | 22 +++++++++---------- .../src/pprust/state/fixup.rs | 14 ++++++------ 4 files changed, 20 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/lib.rs b/compiler/rustc_ast_pretty/src/lib.rs index 84d9ce278a21a..602ab69ee5b5d 100644 --- a/compiler/rustc_ast_pretty/src/lib.rs +++ b/compiler/rustc_ast_pretty/src/lib.rs @@ -3,6 +3,7 @@ #![doc(rust_logo)] #![feature(box_patterns)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod helpers; diff --git a/compiler/rustc_ast_pretty/src/pp/convenience.rs b/compiler/rustc_ast_pretty/src/pp/convenience.rs index 6d46c26311be3..7559b181f7d41 100644 --- a/compiler/rustc_ast_pretty/src/pp/convenience.rs +++ b/compiler/rustc_ast_pretty/src/pp/convenience.rs @@ -89,7 +89,7 @@ impl Printer { } impl Token { - pub fn is_hardbreak_tok(&self) -> bool { + pub(crate) fn is_hardbreak_tok(&self) -> bool { *self == Printer::hardbreak_tok_offset(0) } } diff --git a/compiler/rustc_ast_pretty/src/pp/ring.rs b/compiler/rustc_ast_pretty/src/pp/ring.rs index 8187394fe30e0..003c0a999b50a 100644 --- a/compiler/rustc_ast_pretty/src/pp/ring.rs +++ b/compiler/rustc_ast_pretty/src/pp/ring.rs @@ -11,54 +11,54 @@ use std::ops::{Index, IndexMut}; /// Holding a RingBuffer whose view is elements left..right gives the ability to /// use Index and IndexMut to access elements i in the infinitely long queue for /// which left <= i < right. -pub struct RingBuffer { +pub(super) struct RingBuffer { data: VecDeque, // Abstract index of data[0] in the infinitely sized queue. offset: usize, } impl RingBuffer { - pub fn new() -> Self { + pub(super) fn new() -> Self { RingBuffer { data: VecDeque::new(), offset: 0 } } - pub fn is_empty(&self) -> bool { + pub(super) fn is_empty(&self) -> bool { self.data.is_empty() } - pub fn push(&mut self, value: T) -> usize { + pub(super) fn push(&mut self, value: T) -> usize { let index = self.offset + self.data.len(); self.data.push_back(value); index } - pub fn clear(&mut self) { + pub(super) fn clear(&mut self) { self.data.clear(); } - pub fn index_of_first(&self) -> usize { + pub(super) fn index_of_first(&self) -> usize { self.offset } - pub fn first(&self) -> Option<&T> { + pub(super) fn first(&self) -> Option<&T> { self.data.front() } - pub fn first_mut(&mut self) -> Option<&mut T> { + pub(super) fn first_mut(&mut self) -> Option<&mut T> { self.data.front_mut() } - pub fn pop_first(&mut self) -> Option { + pub(super) fn pop_first(&mut self) -> Option { let first = self.data.pop_front()?; self.offset += 1; Some(first) } - pub fn last(&self) -> Option<&T> { + pub(super) fn last(&self) -> Option<&T> { self.data.back() } - pub fn last_mut(&mut self) -> Option<&mut T> { + pub(super) fn last_mut(&mut self) -> Option<&mut T> { self.data.back_mut() } } diff --git a/compiler/rustc_ast_pretty/src/pprust/state/fixup.rs b/compiler/rustc_ast_pretty/src/pprust/state/fixup.rs index 86d4796e9ce3b..c9baca72485ef 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/fixup.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/fixup.rs @@ -110,13 +110,13 @@ impl Default for FixupContext { impl FixupContext { /// Create the initial fixup for printing an expression in statement /// position. - pub fn new_stmt() -> Self { + pub(crate) fn new_stmt() -> Self { FixupContext { stmt: true, ..FixupContext::default() } } /// Create the initial fixup for printing an expression as the right-hand /// side of a match arm. - pub fn new_match_arm() -> Self { + pub(crate) fn new_match_arm() -> Self { FixupContext { match_arm: true, ..FixupContext::default() } } @@ -124,7 +124,7 @@ impl FixupContext { /// of an `if` or `while`. There are a few other positions which are /// grammatically equivalent and also use this, such as the iterator /// expression in `for` and the scrutinee in `match`. - pub fn new_cond() -> Self { + pub(crate) fn new_cond() -> Self { FixupContext { parenthesize_exterior_struct_lit: true, ..FixupContext::default() } } @@ -139,7 +139,7 @@ impl FixupContext { /// /// Not every expression has a leftmost subexpression. For example neither /// `-$a` nor `[$a]` have one. - pub fn leftmost_subexpression(self) -> Self { + pub(crate) fn leftmost_subexpression(self) -> Self { FixupContext { stmt: false, leftmost_subexpression_in_stmt: self.stmt || self.leftmost_subexpression_in_stmt, @@ -158,7 +158,7 @@ impl FixupContext { /// current expression, and is not surrounded by a paren/bracket/brace. For /// example the `$b` in `$a + $b` and `-$b`, but not the one in `[$b]` or /// `$a.f($b)`. - pub fn subsequent_subexpression(self) -> Self { + pub(crate) fn subsequent_subexpression(self) -> Self { FixupContext { stmt: false, leftmost_subexpression_in_stmt: false, @@ -173,7 +173,7 @@ impl FixupContext { /// /// The documentation on `FixupContext::leftmost_subexpression_in_stmt` has /// examples. - pub fn would_cause_statement_boundary(self, expr: &Expr) -> bool { + pub(crate) fn would_cause_statement_boundary(self, expr: &Expr) -> bool { (self.leftmost_subexpression_in_stmt && !classify::expr_requires_semi_to_be_stmt(expr)) || (self.leftmost_subexpression_in_match_arm && classify::expr_is_complete(expr)) } @@ -189,7 +189,7 @@ impl FixupContext { /// /// - `true && false`, because otherwise this would be misinterpreted as a /// "let chain". - pub fn needs_par_as_let_scrutinee(self, expr: &Expr) -> bool { + pub(crate) fn needs_par_as_let_scrutinee(self, expr: &Expr) -> bool { self.parenthesize_exterior_struct_lit && parser::contains_exterior_struct_lit(expr) || parser::needs_par_as_let_scrutinee(expr.precedence().order()) } From 6614165eac9532a843f691fe1b7e3c37fa637ebf Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 6 Jul 2024 21:31:11 +1000 Subject: [PATCH 09/25] Add `warn(unreachable_pub)` to `rustc_attr`. --- compiler/rustc_attr/src/lib.rs | 1 + compiler/rustc_attr/src/session_diagnostics.rs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_attr/src/lib.rs b/compiler/rustc_attr/src/lib.rs index 1ecfc42ec1df4..0dad637238982 100644 --- a/compiler/rustc_attr/src/lib.rs +++ b/compiler/rustc_attr/src/lib.rs @@ -9,6 +9,7 @@ #![doc(rust_logo)] #![feature(let_chains)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod builtin; diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 92a3a385a7441..a1a10d2d36422 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -127,7 +127,7 @@ pub(crate) enum InvalidIssueStringCause { } impl InvalidIssueStringCause { - pub fn from_int_error_kind(span: Span, kind: &IntErrorKind) -> Option { + pub(crate) fn from_int_error_kind(span: Span, kind: &IntErrorKind) -> Option { match kind { IntErrorKind::Empty => Some(Self::Empty { span }), IntErrorKind::InvalidDigit => Some(Self::InvalidDigit { span }), @@ -303,7 +303,7 @@ pub(crate) enum IncorrectReprFormatGenericCause<'a> { } impl<'a> IncorrectReprFormatGenericCause<'a> { - pub fn from_lit_kind(span: Span, kind: &ast::LitKind, name: &'a str) -> Option { + pub(crate) fn from_lit_kind(span: Span, kind: &ast::LitKind, name: &'a str) -> Option { match kind { ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => { Some(Self::Int { span, name, int: int.get() }) From cb3f43569933111c99222e1d8d87d529117f0bd6 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 6 Jul 2024 21:35:12 +1000 Subject: [PATCH 10/25] Don't add `warn(unreachable_pub)` to `rustc_baked_icu`. But explain why. --- compiler/rustc_baked_icu_data/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_baked_icu_data/src/lib.rs b/compiler/rustc_baked_icu_data/src/lib.rs index e964a709757cf..f86a9db61c600 100644 --- a/compiler/rustc_baked_icu_data/src/lib.rs +++ b/compiler/rustc_baked_icu_data/src/lib.rs @@ -25,6 +25,7 @@ #![allow(internal_features)] #![doc(rust_logo)] #![feature(rustdoc_internals)] +// #![warn(unreachable_pub)] // don't use because this crate is mostly generated code // tidy-alphabetical-end mod data { From 0685c978434b21c18ae2575cbbd72b6234b7701e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 6 Jul 2024 21:53:49 +1000 Subject: [PATCH 11/25] Add `warn(unreachable_pub)` to `rustc_borrowck`. --- .../rustc_borrowck/src/borrowck_errors.rs | 2 +- compiler/rustc_borrowck/src/dataflow.rs | 4 +- compiler/rustc_borrowck/src/def_use.rs | 4 +- .../src/diagnostics/conflict_errors.rs | 8 ++-- .../rustc_borrowck/src/diagnostics/mod.rs | 4 +- .../src/diagnostics/move_errors.rs | 2 +- .../src/diagnostics/mutability_errors.rs | 2 +- .../src/diagnostics/outlives_suggestion.rs | 2 +- .../src/diagnostics/region_errors.rs | 14 ++++--- compiler/rustc_borrowck/src/lib.rs | 26 +++++++----- compiler/rustc_borrowck/src/prefixes.rs | 2 +- .../rustc_borrowck/src/region_infer/mod.rs | 12 +++--- .../src/region_infer/opaque_types.rs | 8 ++-- compiler/rustc_borrowck/src/type_check/mod.rs | 2 +- .../src/type_check/relate_tys.rs | 4 +- .../rustc_borrowck/src/universal_regions.rs | 42 +++++++++---------- .../rustc_borrowck/src/util/collect_writes.rs | 2 +- compiler/rustc_borrowck/src/util/mod.rs | 2 +- 18 files changed, 74 insertions(+), 68 deletions(-) diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs index 76e39fe94af43..86f46b55bfb44 100644 --- a/compiler/rustc_borrowck/src/borrowck_errors.rs +++ b/compiler/rustc_borrowck/src/borrowck_errors.rs @@ -9,7 +9,7 @@ use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::Span; impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { - pub fn dcx(&self) -> DiagCtxtHandle<'infcx> { + pub(crate) fn dcx(&self) -> DiagCtxtHandle<'infcx> { self.infcx.dcx() } diff --git a/compiler/rustc_borrowck/src/dataflow.rs b/compiler/rustc_borrowck/src/dataflow.rs index 77794a8525f8d..2795bc7162fc8 100644 --- a/compiler/rustc_borrowck/src/dataflow.rs +++ b/compiler/rustc_borrowck/src/dataflow.rs @@ -14,7 +14,7 @@ use rustc_mir_dataflow::{Analysis, AnalysisDomain, GenKill, Results, ResultsVisi use crate::{places_conflict, BorrowSet, PlaceConflictBias, PlaceExt, RegionInferenceContext}; /// The results of the dataflow analyses used by the borrow checker. -pub struct BorrowckResults<'a, 'mir, 'tcx> { +pub(crate) struct BorrowckResults<'a, 'mir, 'tcx> { pub(crate) borrows: Results<'tcx, Borrows<'a, 'mir, 'tcx>>, pub(crate) uninits: Results<'tcx, MaybeUninitializedPlaces<'a, 'mir, 'tcx>>, pub(crate) ever_inits: Results<'tcx, EverInitializedPlaces<'a, 'mir, 'tcx>>, @@ -22,7 +22,7 @@ pub struct BorrowckResults<'a, 'mir, 'tcx> { /// The transient state of the dataflow analyses used by the borrow checker. #[derive(Debug)] -pub struct BorrowckFlowState<'a, 'mir, 'tcx> { +pub(crate) struct BorrowckFlowState<'a, 'mir, 'tcx> { pub(crate) borrows: as AnalysisDomain<'tcx>>::Domain, pub(crate) uninits: as AnalysisDomain<'tcx>>::Domain, pub(crate) ever_inits: as AnalysisDomain<'tcx>>::Domain, diff --git a/compiler/rustc_borrowck/src/def_use.rs b/compiler/rustc_borrowck/src/def_use.rs index 1f0b0981c8f29..7eb9e689afe82 100644 --- a/compiler/rustc_borrowck/src/def_use.rs +++ b/compiler/rustc_borrowck/src/def_use.rs @@ -4,13 +4,13 @@ use rustc_middle::mir::visit::{ }; #[derive(Eq, PartialEq, Clone)] -pub enum DefUse { +pub(crate) enum DefUse { Def, Use, Drop, } -pub fn categorize(context: PlaceContext) -> Option { +pub(crate) fn categorize(context: PlaceContext) -> Option { match context { /////////////////////////////////////////////////////////////////////////// // DEFS diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 2b46e5597f778..cd35427b914c2 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -645,7 +645,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { } } - pub fn suggest_reborrow( + pub(crate) fn suggest_reborrow( &self, err: &mut Diag<'infcx>, span: Span, @@ -1891,10 +1891,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { struct FindUselessClone<'tcx> { tcx: TyCtxt<'tcx>, typeck_results: &'tcx ty::TypeckResults<'tcx>, - pub clones: Vec<&'tcx hir::Expr<'tcx>>, + clones: Vec<&'tcx hir::Expr<'tcx>>, } impl<'tcx> FindUselessClone<'tcx> { - pub fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self { + fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self { Self { tcx, typeck_results: tcx.typeck(def_id), clones: vec![] } } } @@ -1916,7 +1916,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { let body = hir.body(body_id).value; expr_finder.visit_expr(body); - pub struct Holds<'tcx> { + struct Holds<'tcx> { ty: Ty<'tcx>, } diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index a2e5c7b85145a..33f91d7ad3043 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -58,11 +58,11 @@ pub(crate) use region_name::{RegionName, RegionNameSource}; pub(crate) use rustc_middle::util::CallKind; pub(super) struct DescribePlaceOpt { - pub including_downcast: bool, + including_downcast: bool, /// Enable/Disable tuple fields. /// For example `x` tuple. if it's `true` `x.0`. Otherwise `x` - pub including_tuple_field: bool, + including_tuple_field: bool, } pub(super) struct IncludingTupleField(pub(super) bool); diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 792f1548e081e..42b1ffd58ad3e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -16,7 +16,7 @@ use crate::prefixes::PrefixSet; use crate::MirBorrowckCtxt; #[derive(Debug)] -pub enum IllegalMoveOriginKind<'tcx> { +pub(crate) enum IllegalMoveOriginKind<'tcx> { /// Illegal move due to attempt to move from behind a reference. BorrowedContent { /// The place the reference refers to: if erroneous code was trying to diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 0303b80cace45..7b791928689c9 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -1374,7 +1374,7 @@ impl<'tcx> Visitor<'tcx> for BindingFinder { } } -pub fn mut_borrow_of_mutable_ref(local_decl: &LocalDecl<'_>, local_name: Option) -> bool { +fn mut_borrow_of_mutable_ref(local_decl: &LocalDecl<'_>, local_name: Option) -> bool { debug!("local_info: {:?}, ty.kind(): {:?}", local_decl.local_info, local_decl.ty.kind()); match *local_decl.local_info() { diff --git a/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs b/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs index de0df3474299a..a59b7b3cde914 100644 --- a/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs +++ b/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs @@ -31,7 +31,7 @@ enum SuggestedConstraint { /// /// Adds a help note suggesting adding a where clause with the needed constraints. #[derive(Default)] -pub struct OutlivesSuggestionBuilder { +pub(crate) struct OutlivesSuggestionBuilder { /// The list of outlives constraints that need to be added. Specifically, we map each free /// region to all other regions that it must outlive. I will use the shorthand `fr: /// outlived_frs`. Not all of these regions will already have names necessarily. Some could be diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 451e8bcb16da4..ab48a09cfa4ce 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -72,22 +72,24 @@ impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> { pub(crate) struct RegionErrors<'tcx>(Vec<(RegionErrorKind<'tcx>, ErrorGuaranteed)>, TyCtxt<'tcx>); impl<'tcx> RegionErrors<'tcx> { - pub fn new(tcx: TyCtxt<'tcx>) -> Self { + pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self { Self(vec![], tcx) } #[track_caller] - pub fn push(&mut self, val: impl Into>) { + pub(crate) fn push(&mut self, val: impl Into>) { let val = val.into(); let guar = self.1.sess.dcx().delayed_bug(format!("{val:?}")); self.0.push((val, guar)); } - pub fn is_empty(&self) -> bool { + pub(crate) fn is_empty(&self) -> bool { self.0.is_empty() } - pub fn into_iter(self) -> impl Iterator, ErrorGuaranteed)> { + pub(crate) fn into_iter( + self, + ) -> impl Iterator, ErrorGuaranteed)> { self.0.into_iter() } - pub fn has_errors(&self) -> Option { + pub(crate) fn has_errors(&self) -> Option { self.0.get(0).map(|x| x.1) } } @@ -141,7 +143,7 @@ pub(crate) enum RegionErrorKind<'tcx> { /// Information about the various region constraints involved in a borrow checker error. #[derive(Clone, Debug)] -pub struct ErrorConstraintInfo<'tcx> { +pub(crate) struct ErrorConstraintInfo<'tcx> { // fr: outlived_fr pub(super) fr: RegionVid, pub(super) fr_is_local: bool, diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 30dd45d847c9b..5d54204bf800a 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -12,6 +12,7 @@ #![feature(rustdoc_internals)] #![feature(stmt_expr_attributes)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end #[macro_use] @@ -2444,7 +2445,7 @@ mod diags { } } - pub struct BorrowckDiags<'infcx, 'tcx> { + pub(crate) struct BorrowckDiags<'infcx, 'tcx> { /// This field keeps track of move errors that are to be reported for given move indices. /// /// There are situations where many errors can be reported for a single move out (see @@ -2468,7 +2469,7 @@ mod diags { } impl<'infcx, 'tcx> BorrowckDiags<'infcx, 'tcx> { - pub fn new() -> Self { + pub(crate) fn new() -> Self { BorrowckDiags { buffered_move_errors: BTreeMap::new(), buffered_mut_errors: Default::default(), @@ -2476,25 +2477,25 @@ mod diags { } } - pub fn buffer_error(&mut self, diag: Diag<'infcx>) { + pub(crate) fn buffer_error(&mut self, diag: Diag<'infcx>) { self.buffered_diags.push(BufferedDiag::Error(diag)); } - pub fn buffer_non_error(&mut self, diag: Diag<'infcx, ()>) { + pub(crate) fn buffer_non_error(&mut self, diag: Diag<'infcx, ()>) { self.buffered_diags.push(BufferedDiag::NonError(diag)); } } impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { - pub fn buffer_error(&mut self, diag: Diag<'infcx>) { + pub(crate) fn buffer_error(&mut self, diag: Diag<'infcx>) { self.diags.buffer_error(diag); } - pub fn buffer_non_error(&mut self, diag: Diag<'infcx, ()>) { + pub(crate) fn buffer_non_error(&mut self, diag: Diag<'infcx, ()>) { self.diags.buffer_non_error(diag); } - pub fn buffer_move_error( + pub(crate) fn buffer_move_error( &mut self, move_out_indices: Vec, place_and_err: (PlaceRef<'tcx>, Diag<'infcx>), @@ -2510,16 +2511,19 @@ mod diags { } } - pub fn get_buffered_mut_error(&mut self, span: Span) -> Option<(Diag<'infcx>, usize)> { + pub(crate) fn get_buffered_mut_error( + &mut self, + span: Span, + ) -> Option<(Diag<'infcx>, usize)> { // FIXME(#120456) - is `swap_remove` correct? self.diags.buffered_mut_errors.swap_remove(&span) } - pub fn buffer_mut_error(&mut self, span: Span, diag: Diag<'infcx>, count: usize) { + pub(crate) fn buffer_mut_error(&mut self, span: Span, diag: Diag<'infcx>, count: usize) { self.diags.buffered_mut_errors.insert(span, (diag, count)); } - pub fn emit_errors(&mut self) -> Option { + pub(crate) fn emit_errors(&mut self) -> Option { let mut res = None; // Buffer any move errors that we collected and de-duplicated. @@ -2553,7 +2557,7 @@ mod diags { self.diags.buffered_diags.is_empty() } - pub fn has_move_error( + pub(crate) fn has_move_error( &self, move_out_indices: &[MoveOutIndex], ) -> Option<&(PlaceRef<'tcx>, Diag<'infcx>)> { diff --git a/compiler/rustc_borrowck/src/prefixes.rs b/compiler/rustc_borrowck/src/prefixes.rs index d3bfd1c418fe4..39d831378cde6 100644 --- a/compiler/rustc_borrowck/src/prefixes.rs +++ b/compiler/rustc_borrowck/src/prefixes.rs @@ -8,7 +8,7 @@ use rustc_middle::mir::{PlaceRef, ProjectionElem}; use super::MirBorrowckCtxt; -pub trait IsPrefixOf<'tcx> { +pub(crate) trait IsPrefixOf<'tcx> { fn is_prefix_of(&self, other: PlaceRef<'tcx>) -> bool; } diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index c8dc012de4a29..6cbdd890b5e8b 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -42,9 +42,9 @@ mod graphviz; mod opaque_types; mod reverse_sccs; -pub mod values; +pub(crate) mod values; -pub type ConstraintSccs = Sccs; +pub(crate) type ConstraintSccs = Sccs; /// An annotation for region graph SCCs that tracks /// the values of its elements. @@ -226,7 +226,7 @@ pub(crate) struct AppliedMemberConstraint { } #[derive(Debug)] -pub struct RegionDefinition<'tcx> { +pub(crate) struct RegionDefinition<'tcx> { /// What kind of variable is this -- a free region? existential /// variable? etc. (See the `NllRegionVariableOrigin` for more /// info.) @@ -288,7 +288,7 @@ pub(crate) enum Cause { /// `InferCtxt::process_registered_region_obligations` and /// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`. #[derive(Clone, Debug)] -pub struct TypeTest<'tcx> { +pub(crate) struct TypeTest<'tcx> { /// The type `T` that must outlive the region. pub generic_kind: GenericKind<'tcx>, @@ -320,7 +320,7 @@ enum Trace<'tcx> { } #[derive(Clone, PartialEq, Eq, Debug)] -pub enum ExtraConstraintInfo { +pub(crate) enum ExtraConstraintInfo { PlaceholderFromPredicate(Span), } @@ -2259,7 +2259,7 @@ impl<'tcx> RegionDefinition<'tcx> { } #[derive(Clone, Debug)] -pub struct BlameConstraint<'tcx> { +pub(crate) struct BlameConstraint<'tcx> { pub category: ConstraintCategory<'tcx>, pub from_closure: bool, pub cause: ObligationCause<'tcx>, diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index 1073ea4069483..cd66acd0a8f21 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -473,20 +473,20 @@ struct LazyOpaqueTyEnv<'tcx> { } impl<'tcx> LazyOpaqueTyEnv<'tcx> { - pub fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self { + fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self { Self { tcx, def_id, canonical_args: std::cell::OnceCell::new() } } - pub fn param_equal_static(&self, param_index: usize) -> bool { + fn param_equal_static(&self, param_index: usize) -> bool { self.get_canonical_args()[param_index].expect_region().is_static() } - pub fn params_equal(&self, param1: usize, param2: usize) -> bool { + fn params_equal(&self, param1: usize, param2: usize) -> bool { let canonical_args = self.get_canonical_args(); canonical_args[param1] == canonical_args[param2] } - pub fn param_is_error(&self, param_index: usize) -> Result<(), ErrorGuaranteed> { + fn param_is_error(&self, param_index: usize) -> Result<(), ErrorGuaranteed> { self.get_canonical_args()[param_index].error_reported() } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index a2669da1b04e8..bbcc2bbdc1086 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -86,7 +86,7 @@ macro_rules! span_mirbug_and_err { mod canonical; mod constraint_conversion; -pub mod free_region_relations; +pub(crate) mod free_region_relations; mod input_output; pub(crate) mod liveness; mod relate_tys; diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index 8da4d80badfec..35d8e2573fe17 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -57,7 +57,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } -pub struct NllTypeRelating<'me, 'bccx, 'tcx> { +struct NllTypeRelating<'me, 'bccx, 'tcx> { type_checker: &'me mut TypeChecker<'bccx, 'tcx>, /// Where (and why) is this relation taking place? @@ -82,7 +82,7 @@ pub struct NllTypeRelating<'me, 'bccx, 'tcx> { } impl<'me, 'bccx, 'tcx> NllTypeRelating<'me, 'bccx, 'tcx> { - pub fn new( + fn new( type_checker: &'me mut TypeChecker<'bccx, 'tcx>, locations: Locations, category: ConstraintCategory<'tcx>, diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 1ad80cb122ab6..2e41c91877431 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -39,7 +39,7 @@ use crate::renumber::RegionCtxt; use crate::BorrowckInferCtxt; #[derive(Debug)] -pub struct UniversalRegions<'tcx> { +pub(crate) struct UniversalRegions<'tcx> { indices: UniversalRegionIndices<'tcx>, /// The vid assigned to `'static` @@ -95,7 +95,7 @@ pub struct UniversalRegions<'tcx> { /// regions appear free in the defining type and late-bound regions /// appear bound in the signature. #[derive(Copy, Clone, Debug)] -pub enum DefiningTy<'tcx> { +pub(crate) enum DefiningTy<'tcx> { /// The MIR is a closure. The signature is found via /// `ClosureArgs::closure_sig_ty`. Closure(DefId, GenericArgsRef<'tcx>), @@ -131,7 +131,7 @@ impl<'tcx> DefiningTy<'tcx> { /// not a closure or coroutine, there are no upvars, and hence it /// will be an empty list. The order of types in this list will /// match up with the upvar order in the HIR, typesystem, and MIR. - pub fn upvar_tys(self) -> &'tcx ty::List> { + pub(crate) fn upvar_tys(self) -> &'tcx ty::List> { match self { DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(), DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().upvar_tys(), @@ -145,7 +145,7 @@ impl<'tcx> DefiningTy<'tcx> { /// Number of implicit inputs -- notably the "environment" /// parameter for closures -- that appear in MIR but not in the /// user's code. - pub fn implicit_inputs(self) -> usize { + pub(crate) fn implicit_inputs(self) -> usize { match self { DefiningTy::Closure(..) | DefiningTy::CoroutineClosure(..) @@ -154,15 +154,15 @@ impl<'tcx> DefiningTy<'tcx> { } } - pub fn is_fn_def(&self) -> bool { + pub(crate) fn is_fn_def(&self) -> bool { matches!(*self, DefiningTy::FnDef(..)) } - pub fn is_const(&self) -> bool { + pub(crate) fn is_const(&self) -> bool { matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..)) } - pub fn def_id(&self) -> DefId { + pub(crate) fn def_id(&self) -> DefId { match *self { DefiningTy::Closure(def_id, ..) | DefiningTy::CoroutineClosure(def_id, ..) @@ -196,7 +196,7 @@ struct UniversalRegionIndices<'tcx> { } #[derive(Debug, PartialEq)] -pub enum RegionClassification { +pub(crate) enum RegionClassification { /// A **global** region is one that can be named from /// anywhere. There is only one, `'static`. Global, @@ -246,7 +246,7 @@ impl<'tcx> UniversalRegions<'tcx> { /// MIR -- that is, all the regions that appear in the function's /// signature. This will also compute the relationships that are /// known between those regions. - pub fn new( + pub(crate) fn new( infcx: &BorrowckInferCtxt<'tcx>, mir_def: LocalDefId, param_env: ty::ParamEnv<'tcx>, @@ -263,7 +263,7 @@ impl<'tcx> UniversalRegions<'tcx> { /// if the `ClosureRegionRequirements` contains something like /// `'1: '2`, then the caller would impose the constraint that /// `V[1]: V[2]`. - pub fn closure_mapping( + pub(crate) fn closure_mapping( tcx: TyCtxt<'tcx>, closure_args: GenericArgsRef<'tcx>, expected_num_vars: usize, @@ -289,13 +289,13 @@ impl<'tcx> UniversalRegions<'tcx> { } /// Returns `true` if `r` is a member of this set of universal regions. - pub fn is_universal_region(&self, r: RegionVid) -> bool { + pub(crate) fn is_universal_region(&self, r: RegionVid) -> bool { (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index()) } /// Classifies `r` as a universal region, returning `None` if this /// is not a member of this set of universal regions. - pub fn region_classification(&self, r: RegionVid) -> Option { + pub(crate) fn region_classification(&self, r: RegionVid) -> Option { let index = r.index(); if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) { Some(RegionClassification::Global) @@ -310,17 +310,17 @@ impl<'tcx> UniversalRegions<'tcx> { /// Returns an iterator over all the RegionVids corresponding to /// universally quantified free regions. - pub fn universal_regions(&self) -> impl Iterator { + pub(crate) fn universal_regions(&self) -> impl Iterator { (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize) } /// Returns `true` if `r` is classified as a local region. - pub fn is_local_free_region(&self, r: RegionVid) -> bool { + pub(crate) fn is_local_free_region(&self, r: RegionVid) -> bool { self.region_classification(r) == Some(RegionClassification::Local) } /// Returns the number of universal regions created in any category. - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { self.num_universals } @@ -329,19 +329,19 @@ impl<'tcx> UniversalRegions<'tcx> { /// closure type (versus those bound in the closure /// signature). They are therefore the regions between which the /// closure may impose constraints that its creator must verify. - pub fn num_global_and_external_regions(&self) -> usize { + pub(crate) fn num_global_and_external_regions(&self) -> usize { self.first_local_index } /// Gets an iterator over all the early-bound regions that have names. - pub fn named_universal_regions<'s>( + pub(crate) fn named_universal_regions<'s>( &'s self, ) -> impl Iterator, ty::RegionVid)> + 's { self.indices.indices.iter().map(|(&r, &v)| (r, v)) } /// See `UniversalRegionIndices::to_region_vid`. - pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid { + pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid { self.indices.to_region_vid(r) } @@ -416,7 +416,7 @@ impl<'tcx> UniversalRegions<'tcx> { } } - pub fn tainted_by_errors(&self) -> Option { + pub(crate) fn tainted_by_errors(&self) -> Option { self.indices.tainted_by_errors.get() } } @@ -880,7 +880,7 @@ impl<'tcx> UniversalRegionIndices<'tcx> { /// reference those regions from the `ParamEnv`. It is also used /// during initialization. Relies on the `indices` map having been /// fully initialized. - pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid { + fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid { if let ty::ReVar(..) = *r { r.as_var() } else if let ty::ReError(guar) = *r { @@ -899,7 +899,7 @@ impl<'tcx> UniversalRegionIndices<'tcx> { /// Replaces all free regions in `value` with region vids, as /// returned by `to_region_vid`. - pub fn fold_to_region_vids(&self, tcx: TyCtxt<'tcx>, value: T) -> T + fn fold_to_region_vids(&self, tcx: TyCtxt<'tcx>, value: T) -> T where T: TypeFoldable>, { diff --git a/compiler/rustc_borrowck/src/util/collect_writes.rs b/compiler/rustc_borrowck/src/util/collect_writes.rs index 93c7810b54517..55f1073176aef 100644 --- a/compiler/rustc_borrowck/src/util/collect_writes.rs +++ b/compiler/rustc_borrowck/src/util/collect_writes.rs @@ -1,7 +1,7 @@ use rustc_middle::mir::visit::{PlaceContext, Visitor}; use rustc_middle::mir::{Body, Local, Location}; -pub trait FindAssignments { +pub(crate) trait FindAssignments { // Finds all statements that assign directly to local (i.e., X = ...) // and returns their locations. fn find_assignments(&self, local: Local) -> Vec; diff --git a/compiler/rustc_borrowck/src/util/mod.rs b/compiler/rustc_borrowck/src/util/mod.rs index 7377d4de7274f..5f2960b768b29 100644 --- a/compiler/rustc_borrowck/src/util/mod.rs +++ b/compiler/rustc_borrowck/src/util/mod.rs @@ -1,3 +1,3 @@ mod collect_writes; -pub use collect_writes::FindAssignments; +pub(crate) use collect_writes::FindAssignments; From 0544d3a952056da8d4c69130cc52ca52e8f78bf3 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 6 Jul 2024 22:08:04 +1000 Subject: [PATCH 12/25] Add `warn(unreachable_pub)` to `rustc_builtin_macros`. --- .../src/deriving/generic/mod.rs | 10 +-- .../src/deriving/generic/ty.rs | 18 ++--- .../src/deriving/smart_ptr.rs | 2 +- compiler/rustc_builtin_macros/src/errors.rs | 2 +- .../src/format_foreign.rs | 68 +++++++++---------- compiler/rustc_builtin_macros/src/lib.rs | 1 + 6 files changed, 51 insertions(+), 50 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index c90a916488606..289e92a69b2c0 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -351,15 +351,15 @@ struct TypeParameter { pub(crate) struct BlockOrExpr(ThinVec, Option>); impl BlockOrExpr { - pub fn new_stmts(stmts: ThinVec) -> BlockOrExpr { + pub(crate) fn new_stmts(stmts: ThinVec) -> BlockOrExpr { BlockOrExpr(stmts, None) } - pub fn new_expr(expr: P) -> BlockOrExpr { + pub(crate) fn new_expr(expr: P) -> BlockOrExpr { BlockOrExpr(ThinVec::new(), Some(expr)) } - pub fn new_mixed(stmts: ThinVec, expr: Option>) -> BlockOrExpr { + pub(crate) fn new_mixed(stmts: ThinVec, expr: Option>) -> BlockOrExpr { BlockOrExpr(stmts, expr) } @@ -461,7 +461,7 @@ fn find_type_parameters( } impl<'a> TraitDef<'a> { - pub fn expand( + pub(crate) fn expand( self, cx: &ExtCtxt<'_>, mitem: &ast::MetaItem, @@ -471,7 +471,7 @@ impl<'a> TraitDef<'a> { self.expand_ext(cx, mitem, item, push, false); } - pub fn expand_ext( + pub(crate) fn expand_ext( self, cx: &ExtCtxt<'_>, mitem: &ast::MetaItem, diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs index 747da2ee43bdf..42855e255a806 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs @@ -27,17 +27,17 @@ pub(crate) enum PathKind { } impl Path { - pub fn new(path: Vec) -> Path { + pub(crate) fn new(path: Vec) -> Path { Path::new_(path, Vec::new(), PathKind::Std) } - pub fn new_local(path: Symbol) -> Path { + pub(crate) fn new_local(path: Symbol) -> Path { Path::new_(vec![path], Vec::new(), PathKind::Local) } - pub fn new_(path: Vec, params: Vec>, kind: PathKind) -> Path { + pub(crate) fn new_(path: Vec, params: Vec>, kind: PathKind) -> Path { Path { path, params, kind } } - pub fn to_ty( + pub(crate) fn to_ty( &self, cx: &ExtCtxt<'_>, span: Span, @@ -46,7 +46,7 @@ impl Path { ) -> P { cx.ty_path(self.to_path(cx, span, self_ty, self_generics)) } - pub fn to_path( + pub(crate) fn to_path( &self, cx: &ExtCtxt<'_>, span: Span, @@ -87,7 +87,7 @@ pub(crate) fn self_ref() -> Ty { } impl Ty { - pub fn to_ty( + pub(crate) fn to_ty( &self, cx: &ExtCtxt<'_>, span: Span, @@ -108,7 +108,7 @@ impl Ty { } } - pub fn to_path( + pub(crate) fn to_path( &self, cx: &ExtCtxt<'_>, span: Span, @@ -167,10 +167,10 @@ pub(crate) struct Bounds { } impl Bounds { - pub fn empty() -> Bounds { + pub(crate) fn empty() -> Bounds { Bounds { bounds: Vec::new() } } - pub fn to_generics( + pub(crate) fn to_generics( &self, cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs index 7eb1f17a59ce3..c88c5bd35a526 100644 --- a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs +++ b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs @@ -18,7 +18,7 @@ macro_rules! path { ($span:expr, $($part:ident)::*) => { vec![$(Ident::new(sym::$part, $span),)*] } } -pub fn expand_deriving_smart_ptr( +pub(crate) fn expand_deriving_smart_ptr( cx: &ExtCtxt<'_>, span: Span, _mitem: &MetaItem, diff --git a/compiler/rustc_builtin_macros/src/errors.rs b/compiler/rustc_builtin_macros/src/errors.rs index 6ca43441e0582..4fffffb91c8b4 100644 --- a/compiler/rustc_builtin_macros/src/errors.rs +++ b/compiler/rustc_builtin_macros/src/errors.rs @@ -930,7 +930,7 @@ pub(crate) struct ExpectedItem<'a> { #[derive(Diagnostic)] #[diag(builtin_macros_naked_functions_testing_attribute, code = E0736)] -pub struct NakedFunctionTestingAttribute { +pub(crate) struct NakedFunctionTestingAttribute { #[primary_span] #[label(builtin_macros_naked_attribute)] pub naked_span: Span, diff --git a/compiler/rustc_builtin_macros/src/format_foreign.rs b/compiler/rustc_builtin_macros/src/format_foreign.rs index b52f606f342e2..866ec72f11646 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign.rs @@ -5,7 +5,7 @@ pub(crate) mod printf { /// Represents a single `printf`-style substitution. #[derive(Clone, PartialEq, Debug)] - pub enum Substitution<'a> { + pub(crate) enum Substitution<'a> { /// A formatted output substitution with its internal byte offset. Format(Format<'a>), /// A literal `%%` escape, with its start and end indices. @@ -13,21 +13,21 @@ pub(crate) mod printf { } impl<'a> Substitution<'a> { - pub fn as_str(&self) -> &str { + pub(crate) fn as_str(&self) -> &str { match self { Substitution::Format(fmt) => fmt.span, Substitution::Escape(_) => "%%", } } - pub fn position(&self) -> InnerSpan { + pub(crate) fn position(&self) -> InnerSpan { match self { Substitution::Format(fmt) => fmt.position, &Substitution::Escape((start, end)) => InnerSpan::new(start, end), } } - pub fn set_position(&mut self, start: usize, end: usize) { + pub(crate) fn set_position(&mut self, start: usize, end: usize) { match self { Substitution::Format(fmt) => fmt.position = InnerSpan::new(start, end), Substitution::Escape(pos) => *pos = (start, end), @@ -38,7 +38,7 @@ pub(crate) mod printf { /// /// This ignores cases where the substitution does not have an exact equivalent, or where /// the substitution would be unnecessary. - pub fn translate(&self) -> Result> { + pub(crate) fn translate(&self) -> Result> { match self { Substitution::Format(fmt) => fmt.translate(), Substitution::Escape(_) => Err(None), @@ -48,23 +48,23 @@ pub(crate) mod printf { #[derive(Clone, PartialEq, Debug)] /// A single `printf`-style formatting directive. - pub struct Format<'a> { + pub(crate) struct Format<'a> { /// The entire original formatting directive. - pub span: &'a str, + span: &'a str, /// The (1-based) parameter to be converted. - pub parameter: Option, + parameter: Option, /// Formatting flags. - pub flags: &'a str, + flags: &'a str, /// Minimum width of the output. - pub width: Option, + width: Option, /// Precision of the conversion. - pub precision: Option, + precision: Option, /// Length modifier for the conversion. - pub length: Option<&'a str>, + length: Option<&'a str>, /// Type of parameter being converted. - pub type_: &'a str, + type_: &'a str, /// Byte offset for the start and end of this formatting directive. - pub position: InnerSpan, + position: InnerSpan, } impl Format<'_> { @@ -72,7 +72,7 @@ pub(crate) mod printf { /// /// Returns `Err` in cases where the `printf` directive does not have an exact Rust /// equivalent, rather than guessing. - pub fn translate(&self) -> Result> { + pub(crate) fn translate(&self) -> Result> { use std::fmt::Write; let (c_alt, c_zero, c_left, c_plus) = { @@ -249,7 +249,7 @@ pub(crate) mod printf { /// A general number used in a `printf` formatting directive. #[derive(Copy, Clone, PartialEq, Debug)] - pub enum Num { + enum Num { // The range of these values is technically bounded by `NL_ARGMAX`... but, at least for GNU // libc, it apparently has no real fixed limit. A `u16` is used here on the basis that it // is *vanishingly* unlikely that *anyone* is going to try formatting something wider, or @@ -288,12 +288,12 @@ pub(crate) mod printf { } /// Returns an iterator over all substitutions in a given string. - pub fn iter_subs(s: &str, start_pos: usize) -> Substitutions<'_> { + pub(crate) fn iter_subs(s: &str, start_pos: usize) -> Substitutions<'_> { Substitutions { s, pos: start_pos } } /// Iterator over substitutions in a string. - pub struct Substitutions<'a> { + pub(crate) struct Substitutions<'a> { s: &'a str, pos: usize, } @@ -327,7 +327,7 @@ pub(crate) mod printf { } /// Parse the next substitution from the input string. - pub fn parse_next_substitution(s: &str) -> Option<(Substitution<'_>, &str)> { + fn parse_next_substitution(s: &str) -> Option<(Substitution<'_>, &str)> { use self::State::*; let at = { @@ -615,20 +615,20 @@ pub(crate) mod printf { mod tests; } -pub mod shell { +pub(crate) mod shell { use rustc_span::InnerSpan; use super::strcursor::StrCursor as Cur; #[derive(Clone, PartialEq, Debug)] - pub enum Substitution<'a> { + pub(crate) enum Substitution<'a> { Ordinal(u8, (usize, usize)), Name(&'a str, (usize, usize)), Escape((usize, usize)), } impl Substitution<'_> { - pub fn as_str(&self) -> String { + pub(crate) fn as_str(&self) -> String { match self { Substitution::Ordinal(n, _) => format!("${n}"), Substitution::Name(n, _) => format!("${n}"), @@ -636,17 +636,17 @@ pub mod shell { } } - pub fn position(&self) -> InnerSpan { + pub(crate) fn position(&self) -> InnerSpan { let (Self::Ordinal(_, pos) | Self::Name(_, pos) | Self::Escape(pos)) = self; InnerSpan::new(pos.0, pos.1) } - pub fn set_position(&mut self, start: usize, end: usize) { + fn set_position(&mut self, start: usize, end: usize) { let (Self::Ordinal(_, pos) | Self::Name(_, pos) | Self::Escape(pos)) = self; *pos = (start, end); } - pub fn translate(&self) -> Result> { + pub(crate) fn translate(&self) -> Result> { match self { Substitution::Ordinal(n, _) => Ok(format!("{{{}}}", n)), Substitution::Name(n, _) => Ok(format!("{{{}}}", n)), @@ -656,12 +656,12 @@ pub mod shell { } /// Returns an iterator over all substitutions in a given string. - pub fn iter_subs(s: &str, start_pos: usize) -> Substitutions<'_> { + pub(crate) fn iter_subs(s: &str, start_pos: usize) -> Substitutions<'_> { Substitutions { s, pos: start_pos } } /// Iterator over substitutions in a string. - pub struct Substitutions<'a> { + pub(crate) struct Substitutions<'a> { s: &'a str, pos: usize, } @@ -683,7 +683,7 @@ pub mod shell { } /// Parse the next substitution from the input string. - pub fn parse_next_substitution(s: &str) -> Option<(Substitution<'_>, &str)> { + fn parse_next_substitution(s: &str) -> Option<(Substitution<'_>, &str)> { let at = { let start = s.find('$')?; match s[start + 1..].chars().next()? { @@ -743,24 +743,24 @@ pub mod shell { } mod strcursor { - pub struct StrCursor<'a> { + pub(crate) struct StrCursor<'a> { s: &'a str, pub at: usize, } impl<'a> StrCursor<'a> { - pub fn new_at(s: &'a str, at: usize) -> StrCursor<'a> { + pub(crate) fn new_at(s: &'a str, at: usize) -> StrCursor<'a> { StrCursor { s, at } } - pub fn at_next_cp(mut self) -> Option> { + pub(crate) fn at_next_cp(mut self) -> Option> { match self.try_seek_right_cp() { true => Some(self), false => None, } } - pub fn next_cp(mut self) -> Option<(char, StrCursor<'a>)> { + pub(crate) fn next_cp(mut self) -> Option<(char, StrCursor<'a>)> { let cp = self.cp_after()?; self.seek_right(cp.len_utf8()); Some((cp, self)) @@ -770,11 +770,11 @@ mod strcursor { &self.s[0..self.at] } - pub fn slice_after(&self) -> &'a str { + pub(crate) fn slice_after(&self) -> &'a str { &self.s[self.at..] } - pub fn slice_between(&self, until: StrCursor<'a>) -> Option<&'a str> { + pub(crate) fn slice_between(&self, until: StrCursor<'a>) -> Option<&'a str> { if !str_eq_literal(self.s, until.s) { None } else { diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs index a9ba7334d930e..30e1c8d262216 100644 --- a/compiler/rustc_builtin_macros/src/lib.rs +++ b/compiler/rustc_builtin_macros/src/lib.rs @@ -16,6 +16,7 @@ #![feature(proc_macro_quote)] #![feature(rustdoc_internals)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end extern crate proc_macro; From 61627438ebb72977c8480a2d8b573137cfecefb1 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 6 Jul 2024 22:26:42 +1000 Subject: [PATCH 13/25] Add `warn(unreachable_pub)` to `rustc_codegen_llvm`. --- compiler/rustc_codegen_llvm/src/abi.rs | 14 ++--- compiler/rustc_codegen_llvm/src/attributes.rs | 20 +++---- .../rustc_codegen_llvm/src/back/archive.rs | 2 +- compiler/rustc_codegen_llvm/src/back/lto.rs | 10 ++-- .../rustc_codegen_llvm/src/back/profiling.rs | 8 +-- compiler/rustc_codegen_llvm/src/back/write.rs | 20 +++---- compiler/rustc_codegen_llvm/src/base.rs | 15 +++-- compiler/rustc_codegen_llvm/src/builder.rs | 58 +++++++++++-------- compiler/rustc_codegen_llvm/src/callee.rs | 2 +- compiler/rustc_codegen_llvm/src/common.rs | 22 +++---- compiler/rustc_codegen_llvm/src/consts.rs | 2 +- compiler/rustc_codegen_llvm/src/context.rs | 10 ++-- .../src/coverageinfo/ffi.rs | 18 +++--- .../src/coverageinfo/map_data.rs | 8 +-- .../src/coverageinfo/mapgen.rs | 2 +- .../src/coverageinfo/mod.rs | 8 +-- .../src/debuginfo/create_scope_map.rs | 2 +- .../rustc_codegen_llvm/src/debuginfo/gdb.rs | 8 ++- .../src/debuginfo/metadata.rs | 22 ++++--- .../src/debuginfo/metadata/enums/mod.rs | 2 +- .../src/debuginfo/metadata/type_map.rs | 24 ++++---- .../rustc_codegen_llvm/src/debuginfo/mod.rs | 26 ++++----- .../src/debuginfo/namespace.rs | 4 +- .../rustc_codegen_llvm/src/debuginfo/utils.rs | 10 ++-- compiler/rustc_codegen_llvm/src/declare.rs | 16 ++--- compiler/rustc_codegen_llvm/src/errors.rs | 4 +- compiler/rustc_codegen_llvm/src/lib.rs | 9 +-- compiler/rustc_codegen_llvm/src/llvm_util.rs | 32 +++++----- compiler/rustc_codegen_llvm/src/type_.rs | 2 +- compiler/rustc_codegen_llvm/src/type_of.rs | 8 +-- compiler/rustc_codegen_llvm/src/value.rs | 2 +- 31 files changed, 206 insertions(+), 184 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs index 5ff580e295a60..dea574a53cd7b 100644 --- a/compiler/rustc_codegen_llvm/src/abi.rs +++ b/compiler/rustc_codegen_llvm/src/abi.rs @@ -6,13 +6,13 @@ use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue}; use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::MemFlags; use rustc_middle::ty::layout::LayoutOf; -pub use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; +pub(crate) use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; use rustc_middle::ty::Ty; use rustc_middle::{bug, ty}; use rustc_session::config; -pub use rustc_target::abi::call::*; +pub(crate) use rustc_target::abi::call::*; use rustc_target::abi::{self, HasDataLayout, Int, Size}; -pub use rustc_target::spec::abi::Abi; +pub(crate) use rustc_target::spec::abi::Abi; use rustc_target::spec::SanitizerSet; use smallvec::SmallVec; @@ -25,7 +25,7 @@ use crate::type_of::LayoutLlvmExt; use crate::value::Value; use crate::{attributes, llvm_util}; -pub trait ArgAttributesExt { +trait ArgAttributesExt { fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value); fn apply_attrs_to_callsite( &self, @@ -111,7 +111,7 @@ impl ArgAttributesExt for ArgAttributes { } } -pub trait LlvmType { +pub(crate) trait LlvmType { fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type; } @@ -171,7 +171,7 @@ impl LlvmType for CastTarget { } } -pub trait ArgAbiExt<'ll, 'tcx> { +trait ArgAbiExt<'ll, 'tcx> { fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type; fn store( &self, @@ -307,7 +307,7 @@ impl<'ll, 'tcx> ArgAbiMethods<'tcx> for Builder<'_, 'll, 'tcx> { } } -pub trait FnAbiLlvmExt<'ll, 'tcx> { +pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> { fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type; fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type; fn llvm_cconv(&self) -> llvm::CallConv; diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index fde95104093e5..317e970d70485 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -1,6 +1,6 @@ //! Set and unset common attributes on LLVM values. -pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr}; +use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr}; use rustc_codegen_ssa::traits::*; use rustc_hir::def_id::DefId; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, PatchableFunctionEntry}; @@ -17,13 +17,13 @@ use crate::llvm::{self, AllocKindFlags, Attribute, AttributeKind, AttributePlace use crate::value::Value; use crate::{attributes, llvm_util}; -pub fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) { +pub(crate) fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) { if !attrs.is_empty() { llvm::AddFunctionAttributes(llfn, idx, attrs); } } -pub fn apply_to_callsite(callsite: &Value, idx: AttributePlace, attrs: &[&Attribute]) { +pub(crate) fn apply_to_callsite(callsite: &Value, idx: AttributePlace, attrs: &[&Attribute]) { if !attrs.is_empty() { llvm::AddCallSiteAttributes(callsite, idx, attrs); } @@ -80,7 +80,7 @@ fn patchable_function_entry_attrs<'ll>( /// Get LLVM sanitize attributes. #[inline] -pub fn sanitize_attrs<'ll>( +pub(crate) fn sanitize_attrs<'ll>( cx: &CodegenCx<'ll, '_>, no_sanitize: SanitizerSet, ) -> SmallVec<[&'ll Attribute; 4]> { @@ -120,7 +120,7 @@ pub fn sanitize_attrs<'ll>( /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function. #[inline] -pub fn uwtable_attr(llcx: &llvm::Context, use_sync_unwind: Option) -> &Attribute { +pub(crate) fn uwtable_attr(llcx: &llvm::Context, use_sync_unwind: Option) -> &Attribute { // NOTE: We should determine if we even need async unwind tables, as they // take have more overhead and if we can use sync unwind tables we // probably should. @@ -128,7 +128,7 @@ pub fn uwtable_attr(llcx: &llvm::Context, use_sync_unwind: Option) -> &Att llvm::CreateUWTableAttr(llcx, async_unwind) } -pub fn frame_pointer_type_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> { +pub(crate) fn frame_pointer_type_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> { let mut fp = cx.sess().target.frame_pointer; let opts = &cx.sess().opts; // "mcount" function relies on stack pointer. @@ -280,19 +280,19 @@ fn backchain_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> { if found_positive { Some(llvm::CreateAttrString(cx.llcx, "backchain")) } else { None } } -pub fn target_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll Attribute { +pub(crate) fn target_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll Attribute { let target_cpu = llvm_util::target_cpu(cx.tcx.sess); llvm::CreateAttrStringValue(cx.llcx, "target-cpu", target_cpu) } -pub fn tune_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> { +pub(crate) fn tune_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> { llvm_util::tune_cpu(cx.tcx.sess) .map(|tune_cpu| llvm::CreateAttrStringValue(cx.llcx, "tune-cpu", tune_cpu)) } /// Get the `NonLazyBind` LLVM attribute, /// if the codegen options allow skipping the PLT. -pub fn non_lazy_bind_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> { +pub(crate) fn non_lazy_bind_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> { // Don't generate calls through PLT if it's not necessary if !cx.sess().needs_plt() { Some(AttributeKind::NonLazyBind.create_attr(cx.llcx)) @@ -327,7 +327,7 @@ fn create_alloc_family_attr(llcx: &llvm::Context) -> &llvm::Attribute { /// Helper for `FnAbi::apply_attrs_llfn`: /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`) /// attributes. -pub fn llfn_attrs_from_instance<'ll, 'tcx>( +pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value, instance: ty::Instance<'tcx>, diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index a2ab19ac800b7..8bc989538c3f8 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -102,7 +102,7 @@ impl<'a> ArchiveBuilder for LlvmArchiveBuilder<'a> { } } -pub struct LlvmArchiveBuilderBuilder; +pub(crate) struct LlvmArchiveBuilderBuilder; impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder { fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box { diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index f68155f523a6e..d06b240671251 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -33,9 +33,9 @@ use crate::{LlvmCodegenBackend, ModuleLlvm}; /// We keep track of the computed LTO cache keys from the previous /// session to determine which CGUs we can reuse. -pub const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin"; +const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin"; -pub fn crate_type_allows_lto(crate_type: CrateType) -> bool { +fn crate_type_allows_lto(crate_type: CrateType) -> bool { match crate_type { CrateType::Executable | CrateType::Dylib @@ -710,7 +710,7 @@ impl Drop for ThinBuffer { } } -pub unsafe fn optimize_thin_module( +pub(crate) unsafe fn optimize_thin_module( thin_module: ThinModule, cgcx: &CodegenContext, ) -> Result, FatalError> { @@ -806,7 +806,7 @@ pub unsafe fn optimize_thin_module( /// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys #[derive(Debug, Default)] -pub struct ThinLTOKeysMap { +struct ThinLTOKeysMap { // key = llvm name of importing module, value = LLVM cache key keys: BTreeMap, } @@ -863,7 +863,7 @@ fn module_name_to_str(c_str: &CStr) -> &str { }) } -pub fn parse_module<'a>( +pub(crate) fn parse_module<'a>( cx: &'a llvm::Context, name: &CStr, data: &[u8], diff --git a/compiler/rustc_codegen_llvm/src/back/profiling.rs b/compiler/rustc_codegen_llvm/src/back/profiling.rs index 26fb4a96f846b..79794775b7b66 100644 --- a/compiler/rustc_codegen_llvm/src/back/profiling.rs +++ b/compiler/rustc_codegen_llvm/src/back/profiling.rs @@ -21,14 +21,14 @@ fn llvm_args_to_string_id(profiler: &SelfProfiler, pass_name: &str, ir_name: &st EventId::from_label(profiler.alloc_string(components.as_slice())) } -pub struct LlvmSelfProfiler<'a> { +pub(crate) struct LlvmSelfProfiler<'a> { profiler: Arc, stack: Vec>, llvm_pass_event_kind: StringId, } impl<'a> LlvmSelfProfiler<'a> { - pub fn new(profiler: Arc) -> Self { + pub(crate) fn new(profiler: Arc) -> Self { let llvm_pass_event_kind = profiler.alloc_string("LLVM Pass"); Self { profiler, stack: Vec::default(), llvm_pass_event_kind } } @@ -43,7 +43,7 @@ impl<'a> LlvmSelfProfiler<'a> { } } -pub unsafe extern "C" fn selfprofile_before_pass_callback( +pub(crate) unsafe extern "C" fn selfprofile_before_pass_callback( llvm_self_profiler: *mut c_void, pass_name: *const c_char, ir_name: *const c_char, @@ -56,7 +56,7 @@ pub unsafe extern "C" fn selfprofile_before_pass_callback( } } -pub unsafe extern "C" fn selfprofile_after_pass_callback(llvm_self_profiler: *mut c_void) { +pub(crate) unsafe extern "C" fn selfprofile_after_pass_callback(llvm_self_profiler: *mut c_void) { let llvm_self_profiler = unsafe { &mut *(llvm_self_profiler as *mut LlvmSelfProfiler<'_>) }; llvm_self_profiler.after_pass_callback(); } diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index a1f2433ab6f3b..853321ef1c7d7 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -43,14 +43,14 @@ use crate::llvm::{self, DiagnosticInfo, PassManager}; use crate::type_::Type; use crate::{base, common, llvm_util, LlvmCodegenBackend, ModuleLlvm}; -pub fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> FatalError { +pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> FatalError { match llvm::last_error() { Some(llvm_err) => dcx.emit_almost_fatal(WithLlvmError(err, llvm_err)), None => dcx.emit_almost_fatal(err), } } -pub fn write_output_file<'ll>( +fn write_output_file<'ll>( dcx: DiagCtxtHandle<'_>, target: &'ll llvm::TargetMachine, pm: &llvm::PassManager<'ll>, @@ -95,7 +95,7 @@ pub fn write_output_file<'ll>( } } -pub fn create_informational_target_machine( +pub(crate) fn create_informational_target_machine( sess: &Session, only_base_features: bool, ) -> OwnedTargetMachine { @@ -107,7 +107,7 @@ pub fn create_informational_target_machine( .unwrap_or_else(|err| llvm_err(sess.dcx(), err).raise()) } -pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine { +pub(crate) fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine { let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() { tcx.output_filenames(()).split_dwarf_path( tcx.sess.split_debuginfo(), @@ -130,9 +130,7 @@ pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMach .unwrap_or_else(|err| llvm_err(tcx.dcx(), err).raise()) } -pub fn to_llvm_opt_settings( - cfg: config::OptLevel, -) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) { +fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) { use self::config::OptLevel::*; match cfg { No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone), @@ -179,7 +177,7 @@ pub(crate) fn to_llvm_code_model(code_model: Option) -> llvm::CodeMod } } -pub fn target_machine_factory( +pub(crate) fn target_machine_factory( sess: &Session, optlvl: config::OptLevel, target_features: &[String], @@ -320,7 +318,7 @@ pub(crate) fn save_temp_bitcode( } /// In what context is a dignostic handler being attached to a codegen unit? -pub enum CodegenDiagnosticsStage { +pub(crate) enum CodegenDiagnosticsStage { /// Prelink optimization stage. Opt, /// LTO/ThinLTO postlink optimization stage. @@ -329,14 +327,14 @@ pub enum CodegenDiagnosticsStage { Codegen, } -pub struct DiagnosticHandlers<'a> { +pub(crate) struct DiagnosticHandlers<'a> { data: *mut (&'a CodegenContext, DiagCtxtHandle<'a>), llcx: &'a llvm::Context, old_handler: Option<&'a llvm::DiagnosticHandler>, } impl<'a> DiagnosticHandlers<'a> { - pub fn new( + pub(crate) fn new( cgcx: &'a CodegenContext, dcx: DiagCtxtHandle<'a>, llcx: &'a llvm::Context, diff --git a/compiler/rustc_codegen_llvm/src/base.rs b/compiler/rustc_codegen_llvm/src/base.rs index e8236b45c8966..0ba8d82406a82 100644 --- a/compiler/rustc_codegen_llvm/src/base.rs +++ b/compiler/rustc_codegen_llvm/src/base.rs @@ -32,7 +32,7 @@ use crate::context::CodegenCx; use crate::value::Value; use crate::{attributes, llvm}; -pub struct ValueIter<'ll> { +pub(crate) struct ValueIter<'ll> { cur: Option<&'ll Value>, step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>, } @@ -49,11 +49,14 @@ impl<'ll> Iterator for ValueIter<'ll> { } } -pub fn iter_globals(llmod: &llvm::Module) -> ValueIter<'_> { +pub(crate) fn iter_globals(llmod: &llvm::Module) -> ValueIter<'_> { unsafe { ValueIter { cur: llvm::LLVMGetFirstGlobal(llmod), step: llvm::LLVMGetNextGlobal } } } -pub fn compile_codegen_unit(tcx: TyCtxt<'_>, cgu_name: Symbol) -> (ModuleCodegen, u64) { +pub(crate) fn compile_codegen_unit( + tcx: TyCtxt<'_>, + cgu_name: Symbol, +) -> (ModuleCodegen, u64) { let start_time = Instant::now(); let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx); @@ -140,7 +143,7 @@ pub fn compile_codegen_unit(tcx: TyCtxt<'_>, cgu_name: Symbol) -> (ModuleCodegen (module, cost) } -pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) { +pub(crate) fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) { let Some(sect) = attrs.link_section else { return }; unsafe { let buf = SmallCStr::new(sect.as_str()); @@ -148,7 +151,7 @@ pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) { } } -pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage { +pub(crate) fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage { match linkage { Linkage::External => llvm::Linkage::ExternalLinkage, Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage, @@ -164,7 +167,7 @@ pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage { } } -pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility { +pub(crate) fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility { match linkage { Visibility::Default => llvm::Visibility::Default, Visibility::Hidden => llvm::Visibility::Hidden, diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index cc081f29e128e..40783825cae57 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -36,7 +36,7 @@ use crate::{attributes, llvm_util}; // All Builders must have an llfn associated with them #[must_use] -pub struct Builder<'a, 'll, 'tcx> { +pub(crate) struct Builder<'a, 'll, 'tcx> { pub llbuilder: &'ll mut llvm::Builder<'ll>, pub cx: &'a CodegenCx<'ll, 'tcx>, } @@ -1343,7 +1343,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { Builder { llbuilder, cx } } - pub fn llfn(&self) -> &'ll Value { + pub(crate) fn llfn(&self) -> &'ll Value { unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) } } @@ -1375,7 +1375,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { } } - pub fn set_unpredictable(&mut self, inst: &'ll Value) { + pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) { unsafe { llvm::LLVMSetMetadata( inst, @@ -1385,15 +1385,15 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { } } - pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value { + pub(crate) fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) } } - pub fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value { + pub(crate) fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) } } - pub fn insert_element( + pub(crate) fn insert_element( &mut self, vec: &'ll Value, elt: &'ll Value, @@ -1402,7 +1402,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) } } - pub fn shuffle_vector( + pub(crate) fn shuffle_vector( &mut self, v1: &'ll Value, v2: &'ll Value, @@ -1411,65 +1411,77 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) } } - pub fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) } } - pub fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) } } - pub fn vector_reduce_fadd_reassoc(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_fadd_reassoc( + &mut self, + acc: &'ll Value, + src: &'ll Value, + ) -> &'ll Value { unsafe { let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src); llvm::LLVMRustSetAllowReassoc(instr); instr } } - pub fn vector_reduce_fmul_reassoc(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_fmul_reassoc( + &mut self, + acc: &'ll Value, + src: &'ll Value, + ) -> &'ll Value { unsafe { let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src); llvm::LLVMRustSetAllowReassoc(instr); instr } } - pub fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) } } - pub fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) } } - pub fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) } } - pub fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) } } - pub fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) } } - pub fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false) } } - pub fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value { + pub(crate) fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false) } } - pub fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value { + pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) } } - pub fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value { + pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value { unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) } } - pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) { + pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) { unsafe { llvm::LLVMAddClause(landing_pad, clause); } } - pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value { + pub(crate) fn catch_ret( + &mut self, + funclet: &Funclet<'ll>, + unwind: &'ll BasicBlock, + ) -> &'ll Value { let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) }; ret.expect("LLVM does not have support for catchret") } @@ -1515,7 +1527,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { Cow::Owned(casted_args) } - pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value { + pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value { unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) } } diff --git a/compiler/rustc_codegen_llvm/src/callee.rs b/compiler/rustc_codegen_llvm/src/callee.rs index 663c5be46e5e4..949fd1bc124f5 100644 --- a/compiler/rustc_codegen_llvm/src/callee.rs +++ b/compiler/rustc_codegen_llvm/src/callee.rs @@ -20,7 +20,7 @@ use crate::value::Value; /// /// - `cx`: the crate context /// - `instance`: the instance to be instantiated -pub fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>) -> &'ll Value { +pub(crate) fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>) -> &'ll Value { let tcx = cx.tcx(); debug!("get_fn(instance={:?})", instance); diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index a399790018439..ef6560ecbe59e 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -13,7 +13,7 @@ use rustc_target::abi::{self, AddressSpace, HasDataLayout, Pointer}; use tracing::debug; use crate::consts::const_alloc_to_llvm; -pub use crate::context::CodegenCx; +pub(crate) use crate::context::CodegenCx; use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, OperandBundleDef, True}; use crate::type_::Type; use crate::value::Value; @@ -58,21 +58,21 @@ use crate::value::Value; /// When inside of a landing pad, each function call in LLVM IR needs to be /// annotated with which landing pad it's a part of. This is accomplished via /// the `OperandBundleDef` value created for MSVC landing pads. -pub struct Funclet<'ll> { +pub(crate) struct Funclet<'ll> { cleanuppad: &'ll Value, operand: OperandBundleDef<'ll>, } impl<'ll> Funclet<'ll> { - pub fn new(cleanuppad: &'ll Value) -> Self { + pub(crate) fn new(cleanuppad: &'ll Value) -> Self { Funclet { cleanuppad, operand: OperandBundleDef::new("funclet", &[cleanuppad]) } } - pub fn cleanuppad(&self) -> &'ll Value { + pub(crate) fn cleanuppad(&self) -> &'ll Value { self.cleanuppad } - pub fn bundle(&self) -> &OperandBundleDef<'ll> { + pub(crate) fn bundle(&self) -> &OperandBundleDef<'ll> { &self.operand } } @@ -92,16 +92,16 @@ impl<'ll> BackendTypes for CodegenCx<'ll, '_> { } impl<'ll> CodegenCx<'ll, '_> { - pub fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value { + pub(crate) fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value { let len = u64::try_from(elts.len()).expect("LLVMConstArray2 elements len overflow"); unsafe { llvm::LLVMConstArray2(ty, elts.as_ptr(), len) } } - pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value { + pub(crate) fn const_bytes(&self, bytes: &[u8]) -> &'ll Value { bytes_in_context(self.llcx, bytes) } - pub fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value { + pub(crate) fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value { unsafe { let idx = c_uint::try_from(idx).expect("LLVMGetAggregateElement index overflow"); let r = llvm::LLVMGetAggregateElement(v, idx).unwrap(); @@ -339,18 +339,18 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> { } /// Get the [LLVM type][Type] of a [`Value`]. -pub fn val_ty(v: &Value) -> &Type { +pub(crate) fn val_ty(v: &Value) -> &Type { unsafe { llvm::LLVMTypeOf(v) } } -pub fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value { +pub(crate) fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value { unsafe { let ptr = bytes.as_ptr() as *const c_char; llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), True) } } -pub fn struct_in_context<'ll>( +fn struct_in_context<'ll>( llcx: &'ll llvm::Context, elts: &[&'ll Value], packed: bool, diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 75b298f14ca1e..18fadca8d33f0 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -29,7 +29,7 @@ use crate::type_of::LayoutLlvmExt; use crate::value::Value; use crate::{base, debuginfo}; -pub fn const_alloc_to_llvm<'ll>( +pub(crate) fn const_alloc_to_llvm<'ll>( cx: &CodegenCx<'ll, '_>, alloc: ConstAllocation<'_>, is_static: bool, diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index dd3f39eceadb6..7b12ff2fd8868 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -39,7 +39,7 @@ use crate::{attributes, coverageinfo, debuginfo, llvm, llvm_util}; /// There is one `CodegenCx` per compilation unit. Each one has its own LLVM /// `llvm::Context` so that several compilation units may be optimized in parallel. /// All other LLVM data structures in the `CodegenCx` are tied to that `llvm::Context`. -pub struct CodegenCx<'ll, 'tcx> { +pub(crate) struct CodegenCx<'ll, 'tcx> { pub tcx: TyCtxt<'tcx>, pub use_dll_storage_attrs: bool, pub tls_model: llvm::ThreadLocalMode, @@ -110,7 +110,7 @@ fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode { } } -pub unsafe fn create_module<'ll>( +pub(crate) unsafe fn create_module<'ll>( tcx: TyCtxt<'_>, llcx: &'ll llvm::Context, mod_name: &str, @@ -531,7 +531,9 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { } #[inline] - pub fn coverage_context(&self) -> Option<&coverageinfo::CrateCoverageContext<'ll, 'tcx>> { + pub(crate) fn coverage_context( + &self, + ) -> Option<&coverageinfo::CrateCoverageContext<'ll, 'tcx>> { self.coverage_cx.as_ref() } @@ -1064,7 +1066,7 @@ impl<'ll> CodegenCx<'ll, '_> { impl CodegenCx<'_, '_> { /// Generates a new symbol name with the given prefix. This symbol name must /// only be used for definitions with `internal` or `private` linkage. - pub fn generate_local_symbol_name(&self, prefix: &str) -> String { + pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String { let idx = self.local_gen_sym_counter.get(); self.local_gen_sym_counter.set(idx + 1); // Include a '.' character, so there can be no accidental conflicts with diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs index 584d033d6bdd1..cabdd310d1fc8 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs @@ -80,7 +80,7 @@ pub struct CounterExpression { /// Must match the layout of `LLVMRustCounterMappingRegionKind`. #[derive(Copy, Clone, Debug)] #[repr(C)] -pub enum RegionKind { +enum RegionKind { /// A CodeRegion associates some code with a counter CodeRegion = 0, @@ -110,13 +110,13 @@ pub enum RegionKind { MCDCBranchRegion = 6, } -pub mod mcdc { +mod mcdc { use rustc_middle::mir::coverage::{ConditionInfo, DecisionInfo}; /// Must match the layout of `LLVMRustMCDCDecisionParameters`. #[repr(C)] #[derive(Clone, Copy, Debug, Default)] - pub struct DecisionParameters { + pub(crate) struct DecisionParameters { bitmap_idx: u32, num_conditions: u16, } @@ -127,14 +127,14 @@ pub mod mcdc { /// Must match the layout of `LLVMRustMCDCBranchParameters`. #[repr(C)] #[derive(Clone, Copy, Debug, Default)] - pub struct BranchParameters { + pub(crate) struct BranchParameters { condition_id: LLVMConditionId, condition_ids: [LLVMConditionId; 2], } #[repr(C)] #[derive(Clone, Copy, Debug)] - pub enum ParameterTag { + enum ParameterTag { None = 0, Decision = 1, Branch = 2, @@ -142,24 +142,24 @@ pub mod mcdc { /// Same layout with `LLVMRustMCDCParameters` #[repr(C)] #[derive(Clone, Copy, Debug)] - pub struct Parameters { + pub(crate) struct Parameters { tag: ParameterTag, decision_params: DecisionParameters, branch_params: BranchParameters, } impl Parameters { - pub fn none() -> Self { + pub(crate) fn none() -> Self { Self { tag: ParameterTag::None, decision_params: Default::default(), branch_params: Default::default(), } } - pub fn decision(decision_params: DecisionParameters) -> Self { + pub(crate) fn decision(decision_params: DecisionParameters) -> Self { Self { tag: ParameterTag::Decision, decision_params, branch_params: Default::default() } } - pub fn branch(branch_params: BranchParameters) -> Self { + pub(crate) fn branch(branch_params: BranchParameters) -> Self { Self { tag: ParameterTag::Branch, decision_params: Default::default(), branch_params } } } diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs index 9433385c23a5b..44eafab6060b3 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs @@ -14,7 +14,7 @@ use crate::coverageinfo::ffi::{Counter, CounterExpression, ExprKind}; /// Holds all of the coverage mapping data associated with a function instance, /// collected during traversal of `Coverage` statements in the function's MIR. #[derive(Debug)] -pub struct FunctionCoverageCollector<'tcx> { +pub(crate) struct FunctionCoverageCollector<'tcx> { /// Coverage info that was attached to this function by the instrumentor. function_coverage_info: &'tcx FunctionCoverageInfo, is_used: bool, @@ -32,7 +32,7 @@ pub struct FunctionCoverageCollector<'tcx> { impl<'tcx> FunctionCoverageCollector<'tcx> { /// Creates a new set of coverage data for a used (called) function. - pub fn new( + pub(crate) fn new( instance: Instance<'tcx>, function_coverage_info: &'tcx FunctionCoverageInfo, ) -> Self { @@ -40,7 +40,7 @@ impl<'tcx> FunctionCoverageCollector<'tcx> { } /// Creates a new set of coverage data for an unused (never called) function. - pub fn unused( + pub(crate) fn unused( instance: Instance<'tcx>, function_coverage_info: &'tcx FunctionCoverageInfo, ) -> Self { @@ -195,7 +195,7 @@ impl<'tcx> FunctionCoverage<'tcx> { /// Return the source hash, generated from the HIR node structure, and used to indicate whether /// or not the source code structure changed between different compilations. - pub fn source_hash(&self) -> u64 { + pub(crate) fn source_hash(&self) -> u64 { if self.is_used { self.function_coverage_info.function_source_hash } else { 0 } } diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index f8929a26011ab..069b62af5e748 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -27,7 +27,7 @@ use crate::{coverageinfo, llvm}; /// implementing this Rust version, and though the format documentation is very explicit and /// detailed, some undocumented details in Clang's implementation (that may or may not be important) /// were also replicated for Rust's Coverage Map. -pub fn finalize(cx: &CodegenCx<'_, '_>) { +pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { let tcx = cx.tcx; // Ensure that LLVM is using a version of the coverage mapping format that diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index 20a713b856419..69babc7c9cf3e 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -22,10 +22,10 @@ use crate::llvm; pub(crate) mod ffi; pub(crate) mod map_data; -pub mod mapgen; +mod mapgen; /// A context object for maintaining all state needed by the coverageinfo module. -pub struct CrateCoverageContext<'ll, 'tcx> { +pub(crate) struct CrateCoverageContext<'ll, 'tcx> { /// Coverage data for each instrumented function identified by DefId. pub(crate) function_coverage_map: RefCell, FunctionCoverageCollector<'tcx>>>, @@ -34,7 +34,7 @@ pub struct CrateCoverageContext<'ll, 'tcx> { } impl<'ll, 'tcx> CrateCoverageContext<'ll, 'tcx> { - pub fn new() -> Self { + pub(crate) fn new() -> Self { Self { function_coverage_map: Default::default(), pgo_func_name_var_map: Default::default(), @@ -42,7 +42,7 @@ impl<'ll, 'tcx> CrateCoverageContext<'ll, 'tcx> { } } - pub fn take_function_coverage_map( + fn take_function_coverage_map( &self, ) -> FxIndexMap, FunctionCoverageCollector<'tcx>> { self.function_coverage_map.replace(FxIndexMap::default()) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs index efe616838bfe4..19100ed3f3312 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs @@ -15,7 +15,7 @@ use crate::llvm::debuginfo::{DILocation, DIScope}; /// Produces DIScope DIEs for each MIR Scope which has variables defined in it. // FIXME(eddyb) almost all of this should be in `rustc_codegen_ssa::mir::debuginfo`. -pub fn compute_mir_scopes<'ll, 'tcx>( +pub(crate) fn compute_mir_scopes<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>, mir: &Body<'tcx>, diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index 5a08f2f00e5be..42b03fd053796 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -16,7 +16,7 @@ use crate::value::Value; /// Inserts a side-effect free instruction sequence that makes sure that the /// .debug_gdb_scripts global is referenced, so it isn't removed by the linker. -pub fn insert_reference_to_gdb_debug_scripts_section_global(bx: &mut Builder<'_, '_, '_>) { +pub(crate) fn insert_reference_to_gdb_debug_scripts_section_global(bx: &mut Builder<'_, '_, '_>) { if needs_gdb_debug_scripts_section(bx) { let gdb_debug_scripts_section = get_or_insert_gdb_debug_scripts_section_global(bx); // Load just the first byte as that's all that's necessary to force @@ -30,7 +30,9 @@ pub fn insert_reference_to_gdb_debug_scripts_section_global(bx: &mut Builder<'_, /// Allocates the global variable responsible for the .debug_gdb_scripts binary /// section. -pub fn get_or_insert_gdb_debug_scripts_section_global<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll Value { +pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>( + cx: &CodegenCx<'ll, '_>, +) -> &'ll Value { let c_section_var_name = c"__rustc_debug_gdb_scripts_section__"; let section_var_name = c_section_var_name.to_str().unwrap(); @@ -83,7 +85,7 @@ pub fn get_or_insert_gdb_debug_scripts_section_global<'ll>(cx: &CodegenCx<'ll, ' }) } -pub fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool { +pub(crate) fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool { let omit_gdb_pretty_printer_section = attr::contains_name(cx.tcx.hir().krate_attrs(), sym::omit_gdb_pretty_printer_section); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 87bea22d8ddaf..26999d8103536 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -85,7 +85,7 @@ const NO_GENERICS: for<'ll> fn(&CodegenCx<'ll, '_>) -> SmallVec<&'ll DIType> = | // SmallVec is used quite a bit in this module, so create a shorthand. // The actual number of elements is not so important. -pub type SmallVec = smallvec::SmallVec<[T; 16]>; +type SmallVec = smallvec::SmallVec<[T; 16]>; mod enums; mod type_map; @@ -425,7 +425,7 @@ fn build_slice_type_di_node<'ll, 'tcx>( /// /// This function will look up the debuginfo node in the TypeMap. If it can't find it, it /// will create the node by dispatching to the corresponding `build_*_di_node()` function. -pub fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType { +pub(crate) fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType { let unique_type_id = UniqueTypeId::for_ty(cx.tcx, t); if let Some(existing_di_node) = debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) @@ -531,7 +531,7 @@ fn hex_encode(data: &[u8]) -> String { hex_string } -pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile { +pub(crate) fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile { let cache_key = Some((source_file.stable_id, source_file.src_hash)); return debug_context(cx) .created_files @@ -644,7 +644,7 @@ pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> } } -pub fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile { +fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile { debug_context(cx).created_files.borrow_mut().entry(None).or_insert_with(|| unsafe { let file_name = ""; let directory = ""; @@ -859,7 +859,7 @@ fn build_param_type_di_node<'ll, 'tcx>( } } -pub fn build_compile_unit_di_node<'ll, 'tcx>( +pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>( tcx: TyCtxt<'tcx>, codegen_unit_name: &str, debug_context: &CodegenUnitDebugContext<'ll, 'tcx>, @@ -1319,7 +1319,11 @@ fn build_generic_type_param_di_nodes<'ll, 'tcx>( /// Creates debug information for the given global variable. /// /// Adds the created debuginfo nodes directly to the crate's IR. -pub fn build_global_var_di_node<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) { +pub(crate) fn build_global_var_di_node<'ll>( + cx: &CodegenCx<'ll, '_>, + def_id: DefId, + global: &'ll Value, +) { if cx.dbg_cx.is_none() { return; } @@ -1559,7 +1563,7 @@ pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( /// given type. /// /// Adds the created metadata nodes directly to the crate's IR. -pub fn create_vtable_di_node<'ll, 'tcx>( +pub(crate) fn create_vtable_di_node<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, poly_trait_ref: Option>, @@ -1604,7 +1608,7 @@ pub fn create_vtable_di_node<'ll, 'tcx>( } /// Creates an "extension" of an existing `DIScope` into another file. -pub fn extend_scope_to_file<'ll>( +pub(crate) fn extend_scope_to_file<'ll>( cx: &CodegenCx<'ll, '_>, scope_metadata: &'ll DIScope, file: &SourceFile, @@ -1613,7 +1617,7 @@ pub fn extend_scope_to_file<'ll>( unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) } } -pub fn tuple_field_name(field_index: usize) -> Cow<'static, str> { +fn tuple_field_name(field_index: usize) -> Cow<'static, str> { const TUPLE_FIELD_NAMES: [&'static str; 16] = [ "__0", "__1", "__2", "__3", "__4", "__5", "__6", "__7", "__8", "__9", "__10", "__11", "__12", "__13", "__14", "__15", diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs index fc3adaf068111..373ccc77f9200 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs @@ -301,7 +301,7 @@ fn build_enum_variant_struct_type_di_node<'ll, 'tcx>( /// ---> DW_TAG_structure_type (type of variant 3) /// /// ``` -pub fn build_coroutine_variant_struct_type_di_node<'ll, 'tcx>( +fn build_coroutine_variant_struct_type_di_node<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, variant_index: VariantIdx, coroutine_type_and_layout: TyAndLayout<'tcx>, diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs index 25b2df9c52c3a..6d21f4204e361 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs @@ -22,7 +22,7 @@ mod private { // `UniqueTypeId` from being constructed directly, without asserting // the preconditions. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, HashStable)] - pub struct HiddenZst; + pub(crate) struct HiddenZst; } /// A unique identifier for anything that we create a debuginfo node for. @@ -48,17 +48,17 @@ pub(super) enum UniqueTypeId<'tcx> { } impl<'tcx> UniqueTypeId<'tcx> { - pub fn for_ty(tcx: TyCtxt<'tcx>, t: Ty<'tcx>) -> Self { + pub(crate) fn for_ty(tcx: TyCtxt<'tcx>, t: Ty<'tcx>) -> Self { assert_eq!(t, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)); UniqueTypeId::Ty(t, private::HiddenZst) } - pub fn for_enum_variant_part(tcx: TyCtxt<'tcx>, enum_ty: Ty<'tcx>) -> Self { + pub(crate) fn for_enum_variant_part(tcx: TyCtxt<'tcx>, enum_ty: Ty<'tcx>) -> Self { assert_eq!(enum_ty, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)); UniqueTypeId::VariantPart(enum_ty, private::HiddenZst) } - pub fn for_enum_variant_struct_type( + pub(crate) fn for_enum_variant_struct_type( tcx: TyCtxt<'tcx>, enum_ty: Ty<'tcx>, variant_idx: VariantIdx, @@ -67,7 +67,7 @@ impl<'tcx> UniqueTypeId<'tcx> { UniqueTypeId::VariantStructType(enum_ty, variant_idx, private::HiddenZst) } - pub fn for_enum_variant_struct_type_wrapper( + pub(crate) fn for_enum_variant_struct_type_wrapper( tcx: TyCtxt<'tcx>, enum_ty: Ty<'tcx>, variant_idx: VariantIdx, @@ -76,7 +76,7 @@ impl<'tcx> UniqueTypeId<'tcx> { UniqueTypeId::VariantStructTypeCppLikeWrapper(enum_ty, variant_idx, private::HiddenZst) } - pub fn for_vtable_ty( + pub(crate) fn for_vtable_ty( tcx: TyCtxt<'tcx>, self_type: Ty<'tcx>, implemented_trait: Option>, @@ -93,7 +93,7 @@ impl<'tcx> UniqueTypeId<'tcx> { /// argument of the various `LLVMRustDIBuilderCreate*Type()` methods. /// /// Right now this takes the form of a hex-encoded opaque hash value. - pub fn generate_unique_id_string(self, tcx: TyCtxt<'tcx>) -> String { + fn generate_unique_id_string(self, tcx: TyCtxt<'tcx>) -> String { let mut hasher = StableHasher::new(); tcx.with_stable_hashing_context(|mut hcx| { hcx.while_hashing_spans(false, |hcx| self.hash_stable(hcx, &mut hasher)) @@ -101,7 +101,7 @@ impl<'tcx> UniqueTypeId<'tcx> { hasher.finish::().to_hex() } - pub fn expect_ty(self) -> Ty<'tcx> { + pub(crate) fn expect_ty(self) -> Ty<'tcx> { match self { UniqueTypeId::Ty(ty, _) => ty, _ => bug!("Expected `UniqueTypeId::Ty` but found `{:?}`", self), @@ -133,25 +133,25 @@ impl<'ll, 'tcx> TypeMap<'ll, 'tcx> { } } -pub struct DINodeCreationResult<'ll> { +pub(crate) struct DINodeCreationResult<'ll> { pub di_node: &'ll DIType, pub already_stored_in_typemap: bool, } impl<'ll> DINodeCreationResult<'ll> { - pub fn new(di_node: &'ll DIType, already_stored_in_typemap: bool) -> Self { + pub(crate) fn new(di_node: &'ll DIType, already_stored_in_typemap: bool) -> Self { DINodeCreationResult { di_node, already_stored_in_typemap } } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub enum Stub<'ll> { +pub(crate) enum Stub<'ll> { Struct, Union, VTableTy { vtable_holder: &'ll DIType }, } -pub struct StubInfo<'ll, 'tcx> { +pub(crate) struct StubInfo<'ll, 'tcx> { metadata: &'ll DIType, unique_type_id: UniqueTypeId<'tcx>, } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index b23e05182ca1b..50d08441025a9 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -40,13 +40,13 @@ use crate::llvm::debuginfo::{ use crate::value::Value; mod create_scope_map; -pub mod gdb; -pub mod metadata; +mod gdb; +pub(crate) mod metadata; mod namespace; mod utils; -pub use self::create_scope_map::compute_mir_scopes; -pub use self::metadata::build_global_var_di_node; +use self::create_scope_map::compute_mir_scopes; +pub(crate) use self::metadata::build_global_var_di_node; #[allow(non_upper_case_globals)] const DW_TAG_auto_variable: c_uint = 0x100; @@ -54,7 +54,7 @@ const DW_TAG_auto_variable: c_uint = 0x100; const DW_TAG_arg_variable: c_uint = 0x101; /// A context object for maintaining all state needed by the debuginfo module. -pub struct CodegenUnitDebugContext<'ll, 'tcx> { +pub(crate) struct CodegenUnitDebugContext<'ll, 'tcx> { llcontext: &'ll llvm::Context, llmod: &'ll llvm::Module, builder: &'ll mut DIBuilder<'ll>, @@ -74,7 +74,7 @@ impl Drop for CodegenUnitDebugContext<'_, '_> { } impl<'ll, 'tcx> CodegenUnitDebugContext<'ll, 'tcx> { - pub fn new(llmod: &'ll llvm::Module) -> Self { + pub(crate) fn new(llmod: &'ll llvm::Module) -> Self { debug!("CodegenUnitDebugContext::new"); let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) }; // DIBuilder inherits context from the module, so we'd better use the same one @@ -90,7 +90,7 @@ impl<'ll, 'tcx> CodegenUnitDebugContext<'ll, 'tcx> { } } - pub fn finalize(&self, sess: &Session) { + pub(crate) fn finalize(&self, sess: &Session) { unsafe { llvm::LLVMRustDIBuilderFinalize(self.builder); @@ -134,7 +134,7 @@ impl<'ll, 'tcx> CodegenUnitDebugContext<'ll, 'tcx> { } /// Creates any deferred debug metadata nodes -pub fn finalize(cx: &CodegenCx<'_, '_>) { +pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { if let Some(dbg_cx) = &cx.dbg_cx { debug!("finalize"); @@ -241,13 +241,13 @@ impl<'ll> DebugInfoBuilderMethods for Builder<'_, 'll, '_> { // FIXME(eddyb) rename this to better indicate it's a duplicate of // `rustc_span::Loc` rather than `DILocation`, perhaps by making // `lookup_char_pos` return the right information instead. -pub struct DebugLoc { +struct DebugLoc { /// Information about the original source file. - pub file: Lrc, + file: Lrc, /// The (1-based) line number. - pub line: u32, + line: u32, /// The (1-based) column number. - pub col: u32, + col: u32, } impl CodegenCx<'_, '_> { @@ -255,7 +255,7 @@ impl CodegenCx<'_, '_> { // FIXME(eddyb) rename this to better indicate it's a duplicate of // `lookup_char_pos` rather than `dbg_loc`, perhaps by making // `lookup_char_pos` return the right information instead. - pub fn lookup_debug_loc(&self, pos: BytePos) -> DebugLoc { + fn lookup_debug_loc(&self, pos: BytePos) -> DebugLoc { let (file, line, col) = match self.sess().source_map().lookup_line(pos) { Ok(SourceFileAndLine { sf: file, line }) => { let line_pos = file.lines()[line]; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs b/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs index 5c4f8fe99e3d9..83d7a82dadc4d 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs @@ -9,7 +9,7 @@ use crate::common::CodegenCx; use crate::llvm; use crate::llvm::debuginfo::DIScope; -pub fn mangled_name_of_instance<'a, 'tcx>( +pub(crate) fn mangled_name_of_instance<'a, 'tcx>( cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>, ) -> ty::SymbolName<'tcx> { @@ -17,7 +17,7 @@ pub fn mangled_name_of_instance<'a, 'tcx>( tcx.symbol_name(instance) } -pub fn item_namespace<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll DIScope { +pub(crate) fn item_namespace<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll DIScope { if let Some(&scope) = debug_context(cx).namespace_map.borrow().get(&def_id) { return scope; } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs b/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs index e542aa96e8a23..321553a3df0bd 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs @@ -11,7 +11,7 @@ use crate::common::CodegenCx; use crate::llvm; use crate::llvm::debuginfo::{DIArray, DIBuilder, DIDescriptor, DIScope}; -pub fn is_node_local_to_unit(cx: &CodegenCx<'_, '_>, def_id: DefId) -> bool { +pub(crate) fn is_node_local_to_unit(cx: &CodegenCx<'_, '_>, def_id: DefId) -> bool { // The is_local_to_unit flag indicates whether a function is local to the // current compilation unit (i.e., if it is *static* in the C-sense). The // *reachable* set should provide a good approximation of this, as it @@ -24,7 +24,7 @@ pub fn is_node_local_to_unit(cx: &CodegenCx<'_, '_>, def_id: DefId) -> bool { } #[allow(non_snake_case)] -pub fn create_DIArray<'ll>( +pub(crate) fn create_DIArray<'ll>( builder: &DIBuilder<'ll>, arr: &[Option<&'ll DIDescriptor>], ) -> &'ll DIArray { @@ -32,7 +32,7 @@ pub fn create_DIArray<'ll>( } #[inline] -pub fn debug_context<'a, 'll, 'tcx>( +pub(crate) fn debug_context<'a, 'll, 'tcx>( cx: &'a CodegenCx<'ll, 'tcx>, ) -> &'a CodegenUnitDebugContext<'ll, 'tcx> { cx.dbg_cx.as_ref().unwrap() @@ -40,11 +40,11 @@ pub fn debug_context<'a, 'll, 'tcx>( #[inline] #[allow(non_snake_case)] -pub fn DIB<'a, 'll>(cx: &'a CodegenCx<'ll, '_>) -> &'a DIBuilder<'ll> { +pub(crate) fn DIB<'a, 'll>(cx: &'a CodegenCx<'ll, '_>) -> &'a DIBuilder<'ll> { cx.dbg_cx.as_ref().unwrap().builder } -pub fn get_namespace_for_item<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll DIScope { +pub(crate) fn get_namespace_for_item<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll DIScope { item_namespace(cx, cx.tcx.parent(def_id)) } diff --git a/compiler/rustc_codegen_llvm/src/declare.rs b/compiler/rustc_codegen_llvm/src/declare.rs index 2aa349b278234..4e4500b637328 100644 --- a/compiler/rustc_codegen_llvm/src/declare.rs +++ b/compiler/rustc_codegen_llvm/src/declare.rs @@ -65,7 +65,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// /// If there’s a value with the same name already declared, the function will /// return its Value instead. - pub fn declare_global(&self, name: &str, ty: &'ll Type) -> &'ll Value { + pub(crate) fn declare_global(&self, name: &str, ty: &'ll Type) -> &'ll Value { debug!("declare_global(name={:?})", name); unsafe { llvm::LLVMRustGetOrInsertGlobal(self.llmod, name.as_ptr().cast(), name.len(), ty) } } @@ -77,7 +77,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// /// If there’s a value with the same name already declared, the function will /// update the declaration and return existing Value instead. - pub fn declare_cfn( + pub(crate) fn declare_cfn( &self, name: &str, unnamed: llvm::UnnamedAddr, @@ -100,7 +100,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// /// If there’s a value with the same name already declared, the function will /// update the declaration and return existing Value instead. - pub fn declare_entry_fn( + pub(crate) fn declare_entry_fn( &self, name: &str, callconv: llvm::CallConv, @@ -119,7 +119,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// /// If there’s a value with the same name already declared, the function will /// update the declaration and return existing Value instead. - pub fn declare_fn( + pub(crate) fn declare_fn( &self, name: &str, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, @@ -199,7 +199,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// return `None` if the name already has a definition associated with it. In that /// case an error should be reported to the user, because it usually happens due /// to user’s fault (e.g., misuse of `#[no_mangle]` or `#[export_name]` attributes). - pub fn define_global(&self, name: &str, ty: &'ll Type) -> Option<&'ll Value> { + pub(crate) fn define_global(&self, name: &str, ty: &'ll Type) -> Option<&'ll Value> { if self.get_defined_value(name).is_some() { None } else { @@ -210,19 +210,19 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// Declare a private global /// /// Use this function when you intend to define a global without a name. - pub fn define_private_global(&self, ty: &'ll Type) -> &'ll Value { + pub(crate) fn define_private_global(&self, ty: &'ll Type) -> &'ll Value { unsafe { llvm::LLVMRustInsertPrivateGlobal(self.llmod, ty) } } /// Gets declared value by name. - pub fn get_declared_value(&self, name: &str) -> Option<&'ll Value> { + pub(crate) fn get_declared_value(&self, name: &str) -> Option<&'ll Value> { debug!("get_declared_value(name={:?})", name); unsafe { llvm::LLVMRustGetNamedValue(self.llmod, name.as_ptr().cast(), name.len()) } } /// Gets defined or externally defined (AvailableExternally linkage) value by /// name. - pub fn get_defined_value(&self, name: &str) -> Option<&'ll Value> { + pub(crate) fn get_defined_value(&self, name: &str) -> Option<&'ll Value> { self.get_declared_value(name).and_then(|val| { let declaration = unsafe { llvm::LLVMIsDeclaration(val) != 0 }; if !declaration { Some(val) } else { None } diff --git a/compiler/rustc_codegen_llvm/src/errors.rs b/compiler/rustc_codegen_llvm/src/errors.rs index 7e53d32ce8cd3..766f8db1788fa 100644 --- a/compiler/rustc_codegen_llvm/src/errors.rs +++ b/compiler/rustc_codegen_llvm/src/errors.rs @@ -214,13 +214,13 @@ pub(crate) struct CopyBitcode { #[derive(Diagnostic)] #[diag(codegen_llvm_unknown_debuginfo_compression)] -pub struct UnknownCompression { +pub(crate) struct UnknownCompression { pub algorithm: &'static str, } #[derive(Diagnostic)] #[diag(codegen_llvm_mismatch_data_layout)] -pub struct MismatchedDataLayout<'a> { +pub(crate) struct MismatchedDataLayout<'a> { pub rustc_target: &'a str, pub rustc_layout: &'a str, pub llvm_target: &'a str, diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 43164390a1c6c..7f26bbd7f8757 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -16,6 +16,7 @@ #![feature(iter_intersperse)] #![feature(let_chains)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::any::Any; @@ -45,11 +46,11 @@ use rustc_session::Session; use rustc_span::symbol::Symbol; mod back { - pub mod archive; - pub mod lto; - pub mod owned_target_machine; + pub(crate) mod archive; + pub(crate) mod lto; + pub(crate) mod owned_target_machine; mod profiling; - pub mod write; + pub(crate) mod write; } mod abi; diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 9fd8ca43789dd..7af5eb9278f38 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -136,14 +136,14 @@ unsafe fn configure_llvm(sess: &Session) { unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) }; } -pub fn time_trace_profiler_finish(file_name: &Path) { +pub(crate) fn time_trace_profiler_finish(file_name: &Path) { unsafe { let file_name = path_to_c_string(file_name); llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr()); } } -pub enum TargetFeatureFoldStrength<'a> { +enum TargetFeatureFoldStrength<'a> { // The feature is only tied when enabling the feature, disabling // this feature shouldn't disable the tied feature. EnableOnly(&'a str), @@ -160,28 +160,28 @@ impl<'a> TargetFeatureFoldStrength<'a> { } } -pub struct LLVMFeature<'a> { - pub llvm_feature_name: &'a str, - pub dependency: Option>, +pub(crate) struct LLVMFeature<'a> { + llvm_feature_name: &'a str, + dependency: Option>, } impl<'a> LLVMFeature<'a> { - pub fn new(llvm_feature_name: &'a str) -> Self { + fn new(llvm_feature_name: &'a str) -> Self { Self { llvm_feature_name, dependency: None } } - pub fn with_dependency( + fn with_dependency( llvm_feature_name: &'a str, dependency: TargetFeatureFoldStrength<'a>, ) -> Self { Self { llvm_feature_name, dependency: Some(dependency) } } - pub fn contains(&self, feat: &str) -> bool { + fn contains(&self, feat: &str) -> bool { self.iter().any(|dep| dep == feat) } - pub fn iter(&'a self) -> impl Iterator { + fn iter(&'a self) -> impl Iterator { let dependencies = self.dependency.iter().map(|feat| feat.as_str()); std::iter::once(self.llvm_feature_name).chain(dependencies) } @@ -209,7 +209,7 @@ impl<'a> IntoIterator for LLVMFeature<'a> { // Though note that Rust can also be build with an external precompiled version of LLVM // which might lead to failures if the oldest tested / supported LLVM version // doesn't yet support the relevant intrinsics -pub fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> LLVMFeature<'a> { +pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> LLVMFeature<'a> { let arch = if sess.target.arch == "x86_64" { "x86" } else if sess.target.arch == "arm64ec" { @@ -257,7 +257,7 @@ pub fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> LLVMFeature<'a> { /// Given a map from target_features to whether they are enabled or disabled, /// ensure only valid combinations are allowed. -pub fn check_tied_features( +pub(crate) fn check_tied_features( sess: &Session, features: &FxHashMap<&str, bool>, ) -> Option<&'static [&'static str]> { @@ -337,19 +337,19 @@ pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec { .collect() } -pub fn print_version() { +pub(crate) fn print_version() { let (major, minor, patch) = get_version(); println!("LLVM version: {major}.{minor}.{patch}"); } -pub fn get_version() -> (u32, u32, u32) { +pub(crate) fn get_version() -> (u32, u32, u32) { // Can be called without initializing LLVM unsafe { (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch()) } } -pub fn print_passes() { +pub(crate) fn print_passes() { // Can be called without initializing LLVM unsafe { llvm::LLVMRustPrintPasses(); @@ -479,7 +479,7 @@ fn handle_native(name: &str) -> &str { } } -pub fn target_cpu(sess: &Session) -> &str { +pub(crate) fn target_cpu(sess: &Session) -> &str { match sess.opts.cg.target_cpu { Some(ref name) => handle_native(name), None => handle_native(sess.target.cpu.as_ref()), @@ -699,7 +699,7 @@ fn backend_feature_name<'a>(sess: &Session, s: &'a str) -> Option<&'a str> { Some(feature) } -pub fn tune_cpu(sess: &Session) -> Option<&str> { +pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> { let name = sess.opts.unstable_opts.tune_cpu.as_ref()?; Some(handle_native(name)) } diff --git a/compiler/rustc_codegen_llvm/src/type_.rs b/compiler/rustc_codegen_llvm/src/type_.rs index 7e3ab19898d36..ec1e2cb809421 100644 --- a/compiler/rustc_codegen_llvm/src/type_.rs +++ b/compiler/rustc_codegen_llvm/src/type_.rs @@ -12,7 +12,7 @@ use rustc_target::abi::{AddressSpace, Align, Integer, Size}; use crate::abi::{FnAbiLlvmExt, LlvmType}; use crate::context::CodegenCx; -pub use crate::llvm::Type; +pub(crate) use crate::llvm::Type; use crate::llvm::{Bool, False, True}; use crate::type_of::LayoutLlvmExt; use crate::value::Value; diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index 4755fa08afb7c..6e429a1674ade 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -139,21 +139,21 @@ fn struct_llfields<'a, 'tcx>( } impl<'a, 'tcx> CodegenCx<'a, 'tcx> { - pub fn align_of(&self, ty: Ty<'tcx>) -> Align { + pub(crate) fn align_of(&self, ty: Ty<'tcx>) -> Align { self.layout_of(ty).align.abi } - pub fn size_of(&self, ty: Ty<'tcx>) -> Size { + pub(crate) fn size_of(&self, ty: Ty<'tcx>) -> Size { self.layout_of(ty).size } - pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) { + pub(crate) fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) { let layout = self.layout_of(ty); (layout.size, layout.align.abi) } } -pub trait LayoutLlvmExt<'tcx> { +pub(crate) trait LayoutLlvmExt<'tcx> { fn is_llvm_immediate(&self) -> bool; fn is_llvm_scalar_pair(&self) -> bool; fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type; diff --git a/compiler/rustc_codegen_llvm/src/value.rs b/compiler/rustc_codegen_llvm/src/value.rs index 6295b0de35649..2eabac3be8c56 100644 --- a/compiler/rustc_codegen_llvm/src/value.rs +++ b/compiler/rustc_codegen_llvm/src/value.rs @@ -2,7 +2,7 @@ use std::hash::{Hash, Hasher}; use std::{fmt, ptr}; use crate::llvm; -pub use crate::llvm::Value; +pub(crate) use crate::llvm::Value; impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { From cc8444274b33ffd01fd8cb35199f02697e632852 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 6 Jul 2024 22:30:39 +1000 Subject: [PATCH 14/25] Add `warn(unreachable_pub)` to `rustc_codegen_ssa`. --- compiler/rustc_codegen_ssa/src/back/link.rs | 4 ++-- compiler/rustc_codegen_ssa/src/back/write.rs | 2 +- compiler/rustc_codegen_ssa/src/lib.rs | 1 + compiler/rustc_codegen_ssa/src/mir/analyze.rs | 8 ++++---- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 7bad9d33e7d31..8d271f61a9c75 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -1207,7 +1207,7 @@ mod win { /// Get the Windows system OEM code page. This is most notably the code page /// used for link.exe's output. - pub fn oem_code_page() -> u32 { + pub(super) fn oem_code_page() -> u32 { unsafe { let mut cp: u32 = 0; // We're using the `LOCALE_RETURN_NUMBER` flag to return a u32. @@ -1230,7 +1230,7 @@ mod win { /// /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains /// any invalid bytes for the expected encoding. - pub fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option { + pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option { // `MultiByteToWideChar` requires a length to be a "positive integer". if s.len() > isize::MAX as usize { return None; diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 70b45a852ca0e..7ad31802454f2 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -754,7 +754,7 @@ pub(crate) enum WorkItem { } impl WorkItem { - pub fn module_kind(&self) -> ModuleKind { + fn module_kind(&self) -> ModuleKind { match *self { WorkItem::Optimize(ref m) => m.kind, WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular, diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs index cb6d9d6f66e78..c89bfca668789 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -12,6 +12,7 @@ #![feature(rustdoc_internals)] #![feature(strict_provenance)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end //! This crate contains codegen code that is used by all codegen backends (LLVM and others). diff --git a/compiler/rustc_codegen_ssa/src/mir/analyze.rs b/compiler/rustc_codegen_ssa/src/mir/analyze.rs index 6794365c9beef..5f3766421f0f1 100644 --- a/compiler/rustc_codegen_ssa/src/mir/analyze.rs +++ b/compiler/rustc_codegen_ssa/src/mir/analyze.rs @@ -13,7 +13,7 @@ use tracing::debug; use super::FunctionCx; use crate::traits::*; -pub fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( +pub(crate) fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( fx: &FunctionCx<'a, 'tcx, Bx>, ) -> BitSet { let mir = fx.mir; @@ -251,14 +251,14 @@ impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> Visitor<'tcx> } #[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum CleanupKind { +pub(crate) enum CleanupKind { NotCleanup, Funclet, Internal { funclet: mir::BasicBlock }, } impl CleanupKind { - pub fn funclet_bb(self, for_bb: mir::BasicBlock) -> Option { + pub(crate) fn funclet_bb(self, for_bb: mir::BasicBlock) -> Option { match self { CleanupKind::NotCleanup => None, CleanupKind::Funclet => Some(for_bb), @@ -270,7 +270,7 @@ impl CleanupKind { /// MSVC requires unwinding code to be split to a tree of *funclets*, where each funclet can only /// branch to itself or to its parent. Luckily, the code we generates matches this pattern. /// Recover that structure in an analyze pass. -pub fn cleanup_kinds(mir: &mir::Body<'_>) -> IndexVec { +pub(crate) fn cleanup_kinds(mir: &mir::Body<'_>) -> IndexVec { fn discover_masters<'tcx>( result: &mut IndexSlice, mir: &mir::Body<'tcx>, From e91f32829ccfb60e13fcb07dab4947c382a376c9 Mon Sep 17 00:00:00 2001 From: Stephen Lazaro Date: Tue, 20 Aug 2024 17:53:30 -0700 Subject: [PATCH 15/25] Deduplicate Spans in Uninitialized Check Prevents reporting labels or diagnostics on spans that are produced multiple times. --- .../src/diagnostics/conflict_errors.rs | 5 +++-- tests/ui/duplicate-label-E0381-issue-129274.rs | 13 +++++++++++++ .../ui/duplicate-label-E0381-issue-129274.stderr | 15 +++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 tests/ui/duplicate-label-E0381-issue-129274.rs create mode 100644 tests/ui/duplicate-label-E0381-issue-129274.stderr diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 2b46e5597f778..4106a5de070a5 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -678,14 +678,15 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { let inits = &self.move_data.init_path_map[mpi]; let move_path = &self.move_data.move_paths[mpi]; let decl_span = self.body.local_decls[move_path.place.local].source_info.span; - let mut spans = vec![]; + let mut spans_set = FxIndexSet::default(); for init_idx in inits { let init = &self.move_data.inits[*init_idx]; let span = init.span(self.body); if !span.is_dummy() { - spans.push(span); + spans_set.insert(span); } } + let spans: Vec<_> = spans_set.into_iter().collect(); let (name, desc) = match self.describe_place_with_options( moved_place, diff --git a/tests/ui/duplicate-label-E0381-issue-129274.rs b/tests/ui/duplicate-label-E0381-issue-129274.rs new file mode 100644 index 0000000000000..b2156e630c87f --- /dev/null +++ b/tests/ui/duplicate-label-E0381-issue-129274.rs @@ -0,0 +1,13 @@ +fn main() { + fn test() { + loop { + let blah: Option; + if true { + blah = Some("".to_string()); + } + if let Some(blah) = blah.as_ref() { //~ ERROR E0381 + } + } + } + println!("{:?}", test()) +} diff --git a/tests/ui/duplicate-label-E0381-issue-129274.stderr b/tests/ui/duplicate-label-E0381-issue-129274.stderr new file mode 100644 index 0000000000000..7f8bddb17c5a8 --- /dev/null +++ b/tests/ui/duplicate-label-E0381-issue-129274.stderr @@ -0,0 +1,15 @@ +error[E0381]: used binding `blah` is possibly-uninitialized + --> $DIR/duplicate-label-E0381-issue-129274.rs:8:33 + | +LL | let blah: Option; + | ---- binding declared here but left uninitialized +LL | if true { +LL | blah = Some("".to_string()); + | ---- binding initialized here in some conditions +LL | } +LL | if let Some(blah) = blah.as_ref() { + | ^^^^ `blah` used here but it is possibly-uninitialized + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0381`. From 988bc1c654a1319a7b6fb198184459d503b249be Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 22 Aug 2024 14:25:54 -0400 Subject: [PATCH 16/25] fix typos in new pointer conversion docs --- library/core/src/ptr/const_ptr.rs | 2 +- library/core/src/ptr/mod.rs | 2 +- library/core/src/ptr/mut_ptr.rs | 8 ++++---- library/core/src/ptr/non_null.rs | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 8b9f7b57d0053..d7eea937ef847 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -239,7 +239,7 @@ impl *const T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// /// # Examples /// diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index b2fb365d22745..a7d6602287b90 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -87,7 +87,7 @@ //! even if they only modify `UnsafeCell` data. //! //! If a pointer follows all of these rules, it is said to be -//! *convertable to a reference*. +//! *convertible to a reference*. // ^ we use this term instead of saying that the produced reference must // be valid, as the validity of a reference is easily confused for the // validity of the thing it refers to, and while the two concepts are diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index fb393ffadd5cd..d7bb18590ed5e 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -247,7 +247,7 @@ impl *mut T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// @@ -296,7 +296,7 @@ impl *mut T { /// /// # Safety /// - /// When calling this method, you have to ensure that the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion) + /// When calling this method, you have to ensure that the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) /// /// # Examples /// @@ -330,7 +330,7 @@ impl *mut T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion). + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// Note that because the created reference is to `MaybeUninit`, the /// source pointer can point to uninitialized memory. /// @@ -566,7 +566,7 @@ impl *mut T { /// /// When calling this method, you have to ensure that *either* /// the pointer is null *or* - /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// /// /// # Examples diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index 1e1cf780c28f0..5d5d9d401a295 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -129,7 +129,7 @@ impl NonNull { /// # Safety /// /// When calling this method, you have to ensure that - /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion). + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// Note that because the created reference is to `MaybeUninit`, the /// source pointer can point to uninitialized memory. #[inline] @@ -153,7 +153,7 @@ impl NonNull { /// # Safety /// /// When calling this method, you have to ensure that - /// the pointer is [convirtible to a reference](crate::ptr#pointer-to-reference-conversion). + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// Note that because the created reference is to `MaybeUninit`, the /// source pointer can point to uninitialized memory. #[inline] From 2540070fd45defe48d02aa7af974c8f295b326a4 Mon Sep 17 00:00:00 2001 From: Jack Wrenn Date: Mon, 12 Aug 2024 22:52:59 +0000 Subject: [PATCH 17/25] document & impl the transmutation modeled by `BikeshedIntrinsicFrom` Documents that `BikeshedIntrinsicFrom` models transmute-via-union, which is slightly more expressive than the transmute-via-cast implemented by `transmute_copy`. Additionally, we provide an implementation of transmute-via-union as a method on the `BikeshedIntrinsicFrom` trait with additional documentation on the boundary between trait invariants and caller obligations. Whether or not transmute-via-union is the right kind of transmute to model remains up for discussion [1]. Regardless, it seems wise to document the present behavior. [1] https://rust-lang.zulipchat.com/#narrow/stream/216762-project-safe-transmute/topic/What.20'kind'.20of.20transmute.20to.20model.3F/near/426331967 --- compiler/rustc_ty_utils/src/instance.rs | 5 + library/core/src/mem/transmutability.rs | 371 +++++++++++++++++- .../issue_72181_1.main.built.after.mir | 2 +- ...inhabited.LowerIntrinsics.panic-abort.diff | 2 +- ...nhabited.LowerIntrinsics.panic-unwind.diff | 2 +- ...e_ref_dst.LowerIntrinsics.panic-abort.diff | 2 +- ..._ref_dst.LowerIntrinsics.panic-unwind.diff | 2 +- ...inhabited.LowerIntrinsics.panic-abort.diff | 2 +- ...nhabited.LowerIntrinsics.panic-unwind.diff | 2 +- ...inhabited.LowerIntrinsics.panic-abort.diff | 2 +- ...nhabited.LowerIntrinsics.panic-unwind.diff | 2 +- ...inhabited.LowerIntrinsics.panic-abort.diff | 2 +- ...nhabited.LowerIntrinsics.panic-unwind.diff | 2 +- ...inhabited.LowerIntrinsics.panic-abort.diff | 2 +- ...nhabited.LowerIntrinsics.panic-unwind.diff | 2 +- .../closures/coerce-unsafe-to-closure.stderr | 4 +- tests/ui/intrinsics/reify-intrinsic.stderr | 4 +- 17 files changed, 372 insertions(+), 38 deletions(-) diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index c7ed6e6110fab..d77c3a277bfe8 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -363,6 +363,11 @@ fn resolve_associated_item<'tcx>( tcx.item_name(trait_item_id) ), } + } else if tcx.is_lang_item(trait_ref.def_id, LangItem::TransmuteTrait) { + let name = tcx.item_name(trait_item_id); + assert_eq!(name, sym::transmute); + let args = tcx.erase_regions(rcvr_args); + Some(ty::Instance::new(trait_item_id, args)) } else { Instance::try_resolve_item_for_coroutine(tcx, trait_item_id, trait_id, rcvr_args) } diff --git a/library/core/src/mem/transmutability.rs b/library/core/src/mem/transmutability.rs index ea73c5b80ba44..62d454a5289b1 100644 --- a/library/core/src/mem/transmutability.rs +++ b/library/core/src/mem/transmutability.rs @@ -1,10 +1,88 @@ use crate::marker::{ConstParamTy_, UnsizedConstParamTy}; -/// Are values of a type transmutable into values of another type? +/// Marks that `Src` is transmutable into `Self`. /// -/// This trait is implemented on-the-fly by the compiler for types `Src` and `Self` when the bits of -/// any value of type `Self` are safely transmutable into a value of type `Dst`, in a given `Context`, -/// notwithstanding whatever safety checks you have asked the compiler to [`Assume`] are satisfied. +/// # Implementation +/// +/// This trait cannot be implemented explicitly. It is implemented on-the-fly by +/// the compiler for all types `Src` and `Self` such that, given a set of safety +/// obligations on the programmer (see [`Assume`]), the compiler has proved that +/// the bits of a value of type `Src` can be soundly reinterpreted as a `Self`. +/// +/// # Safety +/// +/// If `Dst: BikeshedIntrinsicFrom`, the compiler guarantees +/// that `Src` is soundly *union-transmutable* into a value of type `Dst`, +/// provided that the programmer has guaranteed that the given +/// [`ASSUMPTIONS`](Assume) are satisfied. +/// +/// A union-transmute is any bit-reinterpretation conversion in the form of: +/// +/// ```rust +/// pub unsafe fn transmute_via_union(src: Src) -> Dst { +/// use core::mem::ManuallyDrop; +/// +/// #[repr(C)] +/// union Transmute { +/// src: ManuallyDrop, +/// dst: ManuallyDrop, +/// } +/// +/// let transmute = Transmute { +/// src: ManuallyDrop::new(src), +/// }; +/// +/// let dst = transmute.dst; +/// +/// ManuallyDrop::into_inner(dst) +/// } +/// ``` +/// +/// Note that this construction is more permissive than +/// [`mem::transmute_copy`](super::transmute_copy); union-transmutes permit +/// conversions that extend the bits of `Src` with trailing padding to fill +/// trailing uninitialized bytes of `Self`; e.g.: +/// +#[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] +#[cfg_attr(not(bootstrap), doc = "```rust")] +/// #![feature(transmutability)] +/// +/// use core::mem::{Assume, BikeshedIntrinsicFrom}; +/// +/// let src = 42u8; // size = 1 +/// +/// #[repr(C, align(2))] +/// struct Dst(u8); // size = 2 +// +/// let _ = unsafe { +/// >::transmute(src) +/// }; +/// ``` +/// +/// # Caveats +/// +/// ## Portability +/// +/// Implementations of this trait do not provide any guarantee of portability +/// across toolchains, targets or compilations. This trait may be implemented +/// for certain combinations of `Src`, `Self` and `ASSUME` on some toolchains, +/// targets or compilations, but not others. For example, if the layouts of +/// `Src` or `Self` are non-deterministic, the presence or absence of an +/// implementation of this trait may also be non-deterministic. Even if `Src` +/// and `Self` have deterministic layouts (e.g., they are `repr(C)` structs), +/// Rust does not specify the alignments of its primitive integer types, and +/// layouts that involve these types may vary across toolchains, targets or +/// compilations. +/// +/// ## Stability +/// +/// Implementations of this trait do not provide any guarantee of SemVer +/// stability across the crate versions that define the `Src` and `Self` types. +/// If SemVer stability is crucial to your application, you must consult the +/// documentation of `Src` and `Self`s' defining crates. Note that the presence +/// of `repr(C)`, alone, does not carry a safety invariant of SemVer stability. +/// Furthermore, stability does not imply portability. For example, the size of +/// `usize` is stable, but not portable. #[unstable(feature = "transmutability", issue = "99571")] #[lang = "transmute_trait"] #[rustc_deny_explicit_impl(implement_via_object = false)] @@ -13,28 +91,207 @@ pub unsafe trait BikeshedIntrinsicFrom Self + where + Src: Sized, + Self: Sized, + { + use super::ManuallyDrop; + + #[repr(C)] + union Transmute { + src: ManuallyDrop, + dst: ManuallyDrop, + } + + let transmute = Transmute { src: ManuallyDrop::new(src) }; + + // SAFETY: It is safe to reinterpret the bits of `src` as a value of + // type `Self`, because, by combination of invariant on this trait and + // contract on the caller, `src` has been proven to satisfy both the + // language and library invariants of `Self`. For all invariants not + // `ASSUME`'d by the caller, the safety obligation is supplied by the + // compiler. Conversely, for all invariants `ASSUME`'d by the caller, + // the safety obligation is supplied by contract on the caller. + let dst = unsafe { transmute.dst }; + + ManuallyDrop::into_inner(dst) + } } -/// What transmutation safety conditions shall the compiler assume that *you* are checking? +/// Configurable proof assumptions of [`BikeshedIntrinsicFrom`]. +/// +/// When `false`, the respective proof obligation belongs to the compiler. When +/// `true`, the onus of the safety proof belongs to the programmer. +/// [`BikeshedIntrinsicFrom`]. #[unstable(feature = "transmutability", issue = "99571")] #[lang = "transmute_opts"] #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub struct Assume { - /// When `true`, the compiler assumes that *you* are ensuring (either dynamically or statically) that - /// destination referents do not have stricter alignment requirements than source referents. + /// When `false`, [`BikeshedIntrinsicFrom`] is not implemented for + /// transmutations that might violate the the alignment requirements of + /// references; e.g.: + /// + #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] + #[cfg_attr(not(bootstrap), doc = "```compile_fail,E0277")] + /// #![feature(transmutability)] + /// use core::mem::{align_of, BikeshedIntrinsicFrom}; + /// + /// assert_eq!(align_of::<[u8; 2]>(), 1); + /// assert_eq!(align_of::(), 2); + /// + /// let src: &[u8; 2] = &[0xFF, 0xFF]; + /// + /// // SAFETY: No safety obligations. + /// let dst: &u16 = unsafe { + /// <_ as BikeshedIntrinsicFrom<_>>::transmute(src) + /// }; + /// ``` + /// + /// When `true`, [`BikeshedIntrinsicFrom`] assumes that *you* have ensured + /// that references in the transmuted value satisfy the alignment + /// requirements of their referent types; e.g.: + /// + #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] + #[cfg_attr(not(bootstrap), doc = "```rust")] + /// #![feature(pointer_is_aligned_to, transmutability)] + /// use core::mem::{align_of, Assume, BikeshedIntrinsicFrom}; + /// + /// let src: &[u8; 2] = &[0xFF, 0xFF]; + /// + /// let maybe_dst: Option<&u16> = if <*const _>::is_aligned_to(src, align_of::()) { + /// // SAFETY: We have checked above that the address of `src` satisfies the + /// // alignment requirements of `u16`. + /// Some(unsafe { + /// <_ as BikeshedIntrinsicFrom<_, { Assume::ALIGNMENT }>>::transmute(src) + /// }) + /// } else { + /// None + /// }; + /// + /// assert!(matches!(maybe_dst, Some(&u16::MAX) | None)); + /// ``` pub alignment: bool, - /// When `true`, the compiler assume that *you* are ensuring that lifetimes are not extended in a manner - /// that violates Rust's memory model. + /// When `false`, [`BikeshedIntrinsicFrom`] is not implemented for + /// transmutations that extend the lifetimes of references. + /// + /// When `true`, [`BikeshedIntrinsicFrom`] assumes that *you* have ensured + /// that references in the transmuted value do not outlive their referents. pub lifetimes: bool, - /// When `true`, the compiler assumes that *you* have ensured that no - /// unsoundness will arise from violating the safety invariants of the - /// destination type (and sometimes of the source type, too). + /// When `false`, [`BikeshedIntrinsicFrom`] is not implemented for + /// transmutations that might violate the library safety invariants of the + /// destination type; e.g.: + /// + #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] + #[cfg_attr(not(bootstrap), doc = "```compile_fail,E0277")] + /// #![feature(transmutability)] + /// use core::mem::BikeshedIntrinsicFrom; + /// + /// let src: u8 = 3; + /// + /// struct EvenU8 { + /// // SAFETY: `val` must be an even number. + /// val: u8, + /// } + /// + /// // SAFETY: No safety obligations. + /// let dst: EvenU8 = unsafe { + /// <_ as BikeshedIntrinsicFrom<_>>::transmute(src) + /// }; + /// ``` + /// + /// When `true`, [`BikeshedIntrinsicFrom`] assumes that *you* have ensured + /// that undefined behavior does not arise from using the transmuted value; + /// e.g.: + /// + #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] + #[cfg_attr(not(bootstrap), doc = "```rust")] + /// #![feature(transmutability)] + /// use core::mem::{Assume, BikeshedIntrinsicFrom}; + /// + /// let src: u8 = 42; + /// + /// struct EvenU8 { + /// // SAFETY: `val` must be an even number. + /// val: u8, + /// } + /// + /// let maybe_dst: Option = if src % 2 == 0 { + /// // SAFETY: We have checked above that the value of `src` is even. + /// Some(unsafe { + /// <_ as BikeshedIntrinsicFrom<_, { Assume::SAFETY }>>::transmute(src) + /// }) + /// } else { + /// None + /// }; + /// + /// assert!(matches!(maybe_dst, Some(EvenU8 { val: 42 }))); + /// ``` pub safety: bool, - /// When `true`, the compiler assumes that *you* are ensuring that the source type is actually a valid - /// instance of the destination type. + /// When `false`, [`BikeshedIntrinsicFrom`] is not implemented for + /// transmutations that might violate the language-level bit-validity + /// invariant of the destination type; e.g.: + /// + #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] + #[cfg_attr(not(bootstrap), doc = "```compile_fail,E0277")] + /// #![feature(transmutability)] + /// use core::mem::BikeshedIntrinsicFrom; + /// + /// let src: u8 = 3; + /// + /// // SAFETY: No safety obligations. + /// let dst: bool = unsafe { + /// <_ as BikeshedIntrinsicFrom<_>>::transmute(src) + /// }; + /// ``` + /// + /// When `true`, [`BikeshedIntrinsicFrom`] assumes that *you* have ensured + /// that the value being transmuted is a bit-valid instance of the + /// transmuted value; e.g.: + /// + #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] + #[cfg_attr(not(bootstrap), doc = "```rust")] + /// #![feature(transmutability)] + /// use core::mem::{Assume, BikeshedIntrinsicFrom}; + /// + /// let src: u8 = 1; + /// + /// let maybe_dst: Option = if src == 0 || src == 1 { + /// // SAFETY: We have checked above that the value of `src` is a bit-valid + /// // instance of `bool`. + /// Some(unsafe { + /// <_ as BikeshedIntrinsicFrom<_, { Assume::VALIDITY }>>::transmute(src) + /// }) + /// } else { + /// None + /// }; + /// + /// assert_eq!(maybe_dst, Some(true)); + /// ``` pub validity: bool, } @@ -44,29 +301,87 @@ impl ConstParamTy_ for Assume {} impl UnsizedConstParamTy for Assume {} impl Assume { - /// Do not assume that *you* have ensured any safety properties are met. + /// With this, [`BikeshedIntrinsicFrom`] does not assume you have ensured + /// any safety obligations are met, and relies only upon its own analysis to + /// (dis)prove transmutability. #[unstable(feature = "transmutability", issue = "99571")] pub const NOTHING: Self = Self { alignment: false, lifetimes: false, safety: false, validity: false }; - /// Assume only that alignment conditions are met. + /// With this, [`BikeshedIntrinsicFrom`] assumes only that you have ensured + /// that references in the transmuted value satisfy the alignment + /// requirements of their referent types. See [`Assume::alignment`] for + /// examples. #[unstable(feature = "transmutability", issue = "99571")] pub const ALIGNMENT: Self = Self { alignment: true, ..Self::NOTHING }; - /// Assume only that lifetime conditions are met. + /// With this, [`BikeshedIntrinsicFrom`] assumes only that you have ensured + /// that references in the transmuted value do not outlive their referents. + /// See [`Assume::lifetimes`] for examples. #[unstable(feature = "transmutability", issue = "99571")] pub const LIFETIMES: Self = Self { lifetimes: true, ..Self::NOTHING }; - /// Assume only that safety conditions are met. + /// With this, [`BikeshedIntrinsicFrom`] assumes only that you have ensured + /// that undefined behavior does not arise from using the transmuted value. + /// See [`Assume::safety`] for examples. #[unstable(feature = "transmutability", issue = "99571")] pub const SAFETY: Self = Self { safety: true, ..Self::NOTHING }; - /// Assume only that dynamically-satisfiable validity conditions are met. + /// With this, [`BikeshedIntrinsicFrom`] assumes only that you have ensured + /// that the value being transmuted is a bit-valid instance of the + /// transmuted value. See [`Assume::validity`] for examples. #[unstable(feature = "transmutability", issue = "99571")] pub const VALIDITY: Self = Self { validity: true, ..Self::NOTHING }; - /// Assume both `self` and `other_assumptions`. + /// Combine the assumptions of `self` and `other_assumptions`. + /// + /// This is especially useful for extending [`Assume`] in generic contexts; + /// e.g.: + /// + #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] + #[cfg_attr(not(bootstrap), doc = "```rust")] #[unstable(feature = "transmutability", issue = "99571")] + /// #![feature( + /// adt_const_params, + /// generic_const_exprs, + /// pointer_is_aligned_to, + /// transmutability, + /// )] + /// #![allow(incomplete_features)] + /// use core::mem::{align_of, Assume, BikeshedIntrinsicFrom}; + /// + /// /// Attempts to transmute `src` to `&Dst`. + /// /// + /// /// Returns `None` if `src` violates the alignment requirements of `&Dst`. + /// /// + /// /// # Safety + /// /// + /// /// The caller guarantees that the obligations required by `ASSUME`, except + /// /// alignment, are satisfied. + /// unsafe fn try_transmute_ref<'a, Src, Dst, const ASSUME: Assume>(src: &'a Src) -> Option<&'a Dst> + /// where + /// &'a Dst: BikeshedIntrinsicFrom<&'a Src, { ASSUME.and(Assume::ALIGNMENT) }>, + /// { + /// if <*const _>::is_aligned_to(src, align_of::()) { + /// // SAFETY: By the above dynamic check, we have ensured that the address + /// // of `src` satisfies the alignment requirements of `&Dst`. By contract + /// // on the caller, the safety obligations required by `ASSUME` have also + /// // been satisfied. + /// Some(unsafe { + /// <_ as BikeshedIntrinsicFrom<_, { ASSUME.and(Assume::ALIGNMENT) }>>::transmute(src) + /// }) + /// } else { + /// None + /// } + /// } + /// + /// let src: &[u8; 2] = &[0xFF, 0xFF]; + /// + /// // SAFETY: No safety obligations. + /// let maybe_dst: Option<&u16> = unsafe { + /// try_transmute_ref::<_, _, { Assume::NOTHING }>(src) + /// }; + ///``` pub const fn and(self, other_assumptions: Self) -> Self { Self { alignment: self.alignment || other_assumptions.alignment, @@ -76,7 +391,21 @@ impl Assume { } } - /// Assume `self`, excepting `other_assumptions`. + /// Remove `other_assumptions` the obligations of `self`; e.g.: + /// + #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] + #[cfg_attr(not(bootstrap), doc = "```rust")] + /// #![feature(transmutability)] + /// use core::mem::Assume; + /// + /// let assumptions = Assume::ALIGNMENT.and(Assume::SAFETY); + /// let to_be_removed = Assume::SAFETY.and(Assume::VALIDITY); + /// + /// assert_eq!( + /// assumptions.but_not(to_be_removed), + /// Assume::ALIGNMENT, + /// ); + /// ``` #[unstable(feature = "transmutability", issue = "99571")] pub const fn but_not(self, other_assumptions: Self) -> Self { Self { diff --git a/tests/mir-opt/issue_72181_1.main.built.after.mir b/tests/mir-opt/issue_72181_1.main.built.after.mir index e8ad5cd8d16a8..293aa37944dd2 100644 --- a/tests/mir-opt/issue_72181_1.main.built.after.mir +++ b/tests/mir-opt/issue_72181_1.main.built.after.mir @@ -19,7 +19,7 @@ fn main() -> () { StorageLive(_2); StorageLive(_3); _3 = (); - _2 = transmute::<(), Void>(move _3) -> bb4; + _2 = std::intrinsics::transmute::<(), Void>(move _3) -> bb4; } bb1: { diff --git a/tests/mir-opt/lower_intrinsics.transmute_inhabited.LowerIntrinsics.panic-abort.diff b/tests/mir-opt/lower_intrinsics.transmute_inhabited.LowerIntrinsics.panic-abort.diff index 71e84fdd8816e..b1104c70e4696 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_inhabited.LowerIntrinsics.panic-abort.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_inhabited.LowerIntrinsics.panic-abort.diff @@ -9,7 +9,7 @@ bb0: { StorageLive(_2); _2 = copy _1; -- _0 = transmute::(move _2) -> [return: bb1, unwind unreachable]; +- _0 = std::intrinsics::transmute::(move _2) -> [return: bb1, unwind unreachable]; + _0 = move _2 as i8 (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_inhabited.LowerIntrinsics.panic-unwind.diff b/tests/mir-opt/lower_intrinsics.transmute_inhabited.LowerIntrinsics.panic-unwind.diff index 71e84fdd8816e..b1104c70e4696 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_inhabited.LowerIntrinsics.panic-unwind.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_inhabited.LowerIntrinsics.panic-unwind.diff @@ -9,7 +9,7 @@ bb0: { StorageLive(_2); _2 = copy _1; -- _0 = transmute::(move _2) -> [return: bb1, unwind unreachable]; +- _0 = std::intrinsics::transmute::(move _2) -> [return: bb1, unwind unreachable]; + _0 = move _2 as i8 (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_ref_dst.LowerIntrinsics.panic-abort.diff b/tests/mir-opt/lower_intrinsics.transmute_ref_dst.LowerIntrinsics.panic-abort.diff index 37232b826c129..169e48a31ddb9 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_ref_dst.LowerIntrinsics.panic-abort.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_ref_dst.LowerIntrinsics.panic-abort.diff @@ -9,7 +9,7 @@ bb0: { StorageLive(_2); _2 = copy _1; -- _0 = transmute::<&T, *const T>(move _2) -> [return: bb1, unwind unreachable]; +- _0 = std::intrinsics::transmute::<&T, *const T>(move _2) -> [return: bb1, unwind unreachable]; + _0 = move _2 as *const T (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_ref_dst.LowerIntrinsics.panic-unwind.diff b/tests/mir-opt/lower_intrinsics.transmute_ref_dst.LowerIntrinsics.panic-unwind.diff index 37232b826c129..169e48a31ddb9 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_ref_dst.LowerIntrinsics.panic-unwind.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_ref_dst.LowerIntrinsics.panic-unwind.diff @@ -9,7 +9,7 @@ bb0: { StorageLive(_2); _2 = copy _1; -- _0 = transmute::<&T, *const T>(move _2) -> [return: bb1, unwind unreachable]; +- _0 = std::intrinsics::transmute::<&T, *const T>(move _2) -> [return: bb1, unwind unreachable]; + _0 = move _2 as *const T (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-abort.diff b/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-abort.diff index 8ac70f99ad2f0..7098b4d316882 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-abort.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-abort.diff @@ -11,7 +11,7 @@ bb0: { StorageLive(_1); -- _1 = transmute::>(const 1_usize) -> [return: bb1, unwind unreachable]; +- _1 = std::intrinsics::transmute::>(const 1_usize) -> [return: bb1, unwind unreachable]; + _1 = const 1_usize as std::boxed::Box (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-unwind.diff b/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-unwind.diff index 8ac70f99ad2f0..7098b4d316882 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-unwind.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-unwind.diff @@ -11,7 +11,7 @@ bb0: { StorageLive(_1); -- _1 = transmute::>(const 1_usize) -> [return: bb1, unwind unreachable]; +- _1 = std::intrinsics::transmute::>(const 1_usize) -> [return: bb1, unwind unreachable]; + _1 = const 1_usize as std::boxed::Box (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_to_mut_uninhabited.LowerIntrinsics.panic-abort.diff b/tests/mir-opt/lower_intrinsics.transmute_to_mut_uninhabited.LowerIntrinsics.panic-abort.diff index c2c4ec0003c26..06225fffd7c2d 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_to_mut_uninhabited.LowerIntrinsics.panic-abort.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_to_mut_uninhabited.LowerIntrinsics.panic-abort.diff @@ -10,7 +10,7 @@ bb0: { StorageLive(_1); -- _1 = transmute::(const 1_usize) -> [return: bb1, unwind unreachable]; +- _1 = std::intrinsics::transmute::(const 1_usize) -> [return: bb1, unwind unreachable]; + _1 = const 1_usize as &mut Never (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_to_mut_uninhabited.LowerIntrinsics.panic-unwind.diff b/tests/mir-opt/lower_intrinsics.transmute_to_mut_uninhabited.LowerIntrinsics.panic-unwind.diff index c2c4ec0003c26..06225fffd7c2d 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_to_mut_uninhabited.LowerIntrinsics.panic-unwind.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_to_mut_uninhabited.LowerIntrinsics.panic-unwind.diff @@ -10,7 +10,7 @@ bb0: { StorageLive(_1); -- _1 = transmute::(const 1_usize) -> [return: bb1, unwind unreachable]; +- _1 = std::intrinsics::transmute::(const 1_usize) -> [return: bb1, unwind unreachable]; + _1 = const 1_usize as &mut Never (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_to_ref_uninhabited.LowerIntrinsics.panic-abort.diff b/tests/mir-opt/lower_intrinsics.transmute_to_ref_uninhabited.LowerIntrinsics.panic-abort.diff index 1b516a1f53b39..dd6ab3a9c97e5 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_to_ref_uninhabited.LowerIntrinsics.panic-abort.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_to_ref_uninhabited.LowerIntrinsics.panic-abort.diff @@ -10,7 +10,7 @@ bb0: { StorageLive(_1); -- _1 = transmute::(const 1_usize) -> [return: bb1, unwind unreachable]; +- _1 = std::intrinsics::transmute::(const 1_usize) -> [return: bb1, unwind unreachable]; + _1 = const 1_usize as &Never (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_to_ref_uninhabited.LowerIntrinsics.panic-unwind.diff b/tests/mir-opt/lower_intrinsics.transmute_to_ref_uninhabited.LowerIntrinsics.panic-unwind.diff index 1b516a1f53b39..dd6ab3a9c97e5 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_to_ref_uninhabited.LowerIntrinsics.panic-unwind.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_to_ref_uninhabited.LowerIntrinsics.panic-unwind.diff @@ -10,7 +10,7 @@ bb0: { StorageLive(_1); -- _1 = transmute::(const 1_usize) -> [return: bb1, unwind unreachable]; +- _1 = std::intrinsics::transmute::(const 1_usize) -> [return: bb1, unwind unreachable]; + _1 = const 1_usize as &Never (Transmute); + goto -> bb1; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_uninhabited.LowerIntrinsics.panic-abort.diff b/tests/mir-opt/lower_intrinsics.transmute_uninhabited.LowerIntrinsics.panic-abort.diff index eab969e9fe5bb..6571f3d9db81a 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_uninhabited.LowerIntrinsics.panic-abort.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_uninhabited.LowerIntrinsics.panic-abort.diff @@ -9,7 +9,7 @@ bb0: { StorageLive(_2); _2 = copy _1; -- _0 = transmute::<(), Never>(move _2) -> unwind unreachable; +- _0 = std::intrinsics::transmute::<(), Never>(move _2) -> unwind unreachable; + _0 = move _2 as Never (Transmute); + unreachable; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_uninhabited.LowerIntrinsics.panic-unwind.diff b/tests/mir-opt/lower_intrinsics.transmute_uninhabited.LowerIntrinsics.panic-unwind.diff index eab969e9fe5bb..6571f3d9db81a 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_uninhabited.LowerIntrinsics.panic-unwind.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_uninhabited.LowerIntrinsics.panic-unwind.diff @@ -9,7 +9,7 @@ bb0: { StorageLive(_2); _2 = copy _1; -- _0 = transmute::<(), Never>(move _2) -> unwind unreachable; +- _0 = std::intrinsics::transmute::<(), Never>(move _2) -> unwind unreachable; + _0 = move _2 as Never (Transmute); + unreachable; } diff --git a/tests/ui/closures/coerce-unsafe-to-closure.stderr b/tests/ui/closures/coerce-unsafe-to-closure.stderr index cb718ca160f8b..2538fc0361c37 100644 --- a/tests/ui/closures/coerce-unsafe-to-closure.stderr +++ b/tests/ui/closures/coerce-unsafe-to-closure.stderr @@ -1,4 +1,4 @@ -error[E0277]: expected a `FnOnce(&str)` closure, found `unsafe extern "rust-intrinsic" fn(_) -> _ {transmute::<_, _>}` +error[E0277]: expected a `FnOnce(&str)` closure, found `unsafe extern "rust-intrinsic" fn(_) -> _ {std::intrinsics::transmute::<_, _>}` --> $DIR/coerce-unsafe-to-closure.rs:2:44 | LL | let x: Option<&[u8]> = Some("foo").map(std::mem::transmute); @@ -6,7 +6,7 @@ LL | let x: Option<&[u8]> = Some("foo").map(std::mem::transmute); | | | required by a bound introduced by this call | - = help: the trait `FnOnce(&str)` is not implemented for fn item `unsafe extern "rust-intrinsic" fn(_) -> _ {transmute::<_, _>}` + = help: the trait `FnOnce(&str)` is not implemented for fn item `unsafe extern "rust-intrinsic" fn(_) -> _ {std::intrinsics::transmute::<_, _>}` = note: unsafe function cannot be called generically without an unsafe block note: required by a bound in `Option::::map` --> $SRC_DIR/core/src/option.rs:LL:COL diff --git a/tests/ui/intrinsics/reify-intrinsic.stderr b/tests/ui/intrinsics/reify-intrinsic.stderr index 0119a1a6650d0..21b7bf4e1cb83 100644 --- a/tests/ui/intrinsics/reify-intrinsic.stderr +++ b/tests/ui/intrinsics/reify-intrinsic.stderr @@ -7,9 +7,9 @@ LL | let _: unsafe extern "rust-intrinsic" fn(isize) -> usize = std::mem::tr | expected due to this | = note: expected fn pointer `unsafe extern "rust-intrinsic" fn(isize) -> usize` - found fn item `unsafe extern "rust-intrinsic" fn(_) -> _ {transmute::<_, _>}` + found fn item `unsafe extern "rust-intrinsic" fn(_) -> _ {std::intrinsics::transmute::<_, _>}` -error[E0606]: casting `unsafe extern "rust-intrinsic" fn(_) -> _ {transmute::<_, _>}` as `unsafe extern "rust-intrinsic" fn(isize) -> usize` is invalid +error[E0606]: casting `unsafe extern "rust-intrinsic" fn(_) -> _ {std::intrinsics::transmute::<_, _>}` as `unsafe extern "rust-intrinsic" fn(isize) -> usize` is invalid --> $DIR/reify-intrinsic.rs:11:13 | LL | let _ = std::mem::transmute as unsafe extern "rust-intrinsic" fn(isize) -> usize; From b581fed15ef93b4d048097afe728dd052e5668ea Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 25 Aug 2024 16:18:59 +0200 Subject: [PATCH 18/25] Generate missing source link on impl associated types --- src/librustdoc/html/render/mod.rs | 2 ++ tests/rustdoc/anchors.no_type_anchor2.html | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index c1b2ee7d8ae92..47f321a4c4a2a 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -1730,6 +1730,7 @@ fn render_impl( let source_id = format!("{item_type}.{name}"); let id = cx.derive_id(&source_id); write!(w, "
"); + render_rightside(w, cx, item, render_mode); if trait_.is_some() { // Anchors are only used on trait impls. write!(w, "§"); @@ -1751,6 +1752,7 @@ fn render_impl( let source_id = format!("{item_type}.{name}"); let id = cx.derive_id(&source_id); write!(w, "
"); + render_rightside(w, cx, item, render_mode); if trait_.is_some() { // Anchors are only used on trait impls. write!(w, "§"); diff --git a/tests/rustdoc/anchors.no_type_anchor2.html b/tests/rustdoc/anchors.no_type_anchor2.html index 71e93990e29e9..9127104ded4af 100644 --- a/tests/rustdoc/anchors.no_type_anchor2.html +++ b/tests/rustdoc/anchors.no_type_anchor2.html @@ -1 +1 @@ -

pub type Y = u32

\ No newline at end of file +
source

pub type Y = u32

\ No newline at end of file From ca6be7414a4f01d4369ebc21773008532f8081ea Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 25 Aug 2024 16:19:17 +0200 Subject: [PATCH 19/25] Add regression test for impl associated types source link --- tests/rustdoc/assoc-type-source-link.rs | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 tests/rustdoc/assoc-type-source-link.rs diff --git a/tests/rustdoc/assoc-type-source-link.rs b/tests/rustdoc/assoc-type-source-link.rs new file mode 100644 index 0000000000000..34b156b964957 --- /dev/null +++ b/tests/rustdoc/assoc-type-source-link.rs @@ -0,0 +1,26 @@ +// This test ensures that the source links are generated for impl associated types. + +#![crate_name = "foo"] +#![feature(inherent_associated_types)] +#![allow(incomplete_features)] + +//@ has 'foo/struct.Bar.html' +pub struct Bar; + +impl Bar { + //@ has - '//*[@id="implementations-list"]//*[@id="associatedtype.Y"]/a' 'source' + //@ has - '//*[@id="implementations-list"]//*[@id="associatedtype.Y"]/a/@href' \ + // '../src/foo/assoc-type-source-link.rs.html#14' + pub type Y = u8; +} + +pub trait Foo { + type Z; +} + +impl Foo for Bar { + //@ has - '//*[@id="trait-implementations-list"]//*[@id="associatedtype.Z"]/a' 'source' + //@ has - '//*[@id="trait-implementations-list"]//*[@id="associatedtype.Z"]/a/@href' \ + // '../src/foo/assoc-type-source-link.rs.html#25' + type Z = u8; +} From 00c435d9b37540d16489862446d934e98e58dfb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 18 Aug 2024 18:59:26 +0000 Subject: [PATCH 20/25] Do not ICE on non-ADT rcvr type when looking for crate version collision When looking for multiple versions of the same crate, do not blindly construct the receiver type. Follow up to #128786. Fix #129205. --- .../rustc_hir_typeck/src/method/suggest.rs | 14 ++++++++------ .../missing-method-on-type-parameter.rs | 6 ++++++ .../missing-method-on-type-parameter.stderr | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 tests/ui/methods/missing-method-on-type-parameter.rs create mode 100644 tests/ui/methods/missing-method-on-type-parameter.stderr diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index ffd46ea13b908..8b8bb29dacdbd 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -3498,7 +3498,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err, pick.item.def_id, rcvr.hir_id, - *rcvr_ty, + Some(*rcvr_ty), ); if pick.autoderefs == 0 && !trait_in_other_version_found { err.span_label( @@ -3689,8 +3689,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let SelfSource::QPath(ty) = source && !valid_out_of_scope_traits.is_empty() && let hir::TyKind::Path(path) = ty.kind - && let hir::QPath::Resolved(_, path) = path - && let Some(def_id) = path.res.opt_def_id() + && let hir::QPath::Resolved(..) = path && let Some(assoc) = self .tcx .associated_items(valid_out_of_scope_traits[0]) @@ -3700,7 +3699,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // See if the `Type::function(val)` where `function` wasn't found corresponds to a // `Trait` that is imported directly, but `Type` came from a different version of the // same crate. - let rcvr_ty = self.tcx.type_of(def_id).instantiate_identity(); + + let rcvr_ty = self.node_ty_opt(ty.hir_id); trait_in_other_version_found = self.detect_and_explain_multiple_crate_versions( err, assoc.def_id, @@ -4080,7 +4080,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err: &mut Diag<'_>, item_def_id: DefId, hir_id: hir::HirId, - rcvr_ty: Ty<'_>, + rcvr_ty: Option>, ) -> bool { let hir_id = self.tcx.parent_hir_id(hir_id); let Some(traits) = self.tcx.in_scope_traits(hir_id) else { return false }; @@ -4110,8 +4110,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut multi_span: MultiSpan = trait_span.into(); multi_span.push_span_label(trait_span, format!("this is the trait that is needed")); let descr = self.tcx.associated_item(item_def_id).descr(); + let rcvr_ty = + rcvr_ty.map(|t| format!("`{t}`")).unwrap_or_else(|| "the receiver".to_string()); multi_span - .push_span_label(item_span, format!("the {descr} is available for `{rcvr_ty}` here")); + .push_span_label(item_span, format!("the {descr} is available for {rcvr_ty} here")); for (def_id, import_def_id) in candidates { if let Some(import_def_id) = import_def_id { multi_span.push_span_label( diff --git a/tests/ui/methods/missing-method-on-type-parameter.rs b/tests/ui/methods/missing-method-on-type-parameter.rs new file mode 100644 index 0000000000000..cbcbeea4d4cd0 --- /dev/null +++ b/tests/ui/methods/missing-method-on-type-parameter.rs @@ -0,0 +1,6 @@ +// Regression test for https://github.com/rust-lang/rust/issues/129205 +fn x() { + T::try_from(); //~ ERROR E0599 +} + +fn main() {} diff --git a/tests/ui/methods/missing-method-on-type-parameter.stderr b/tests/ui/methods/missing-method-on-type-parameter.stderr new file mode 100644 index 0000000000000..c53d7afe4e2d9 --- /dev/null +++ b/tests/ui/methods/missing-method-on-type-parameter.stderr @@ -0,0 +1,19 @@ +error[E0599]: no function or associated item named `try_from` found for type parameter `T` in the current scope + --> $DIR/missing-method-on-type-parameter.rs:3:8 + | +LL | fn x() { + | - function or associated item `try_from` not found for this type parameter +LL | T::try_from(); + | ^^^^^^^^ function or associated item not found in `T` + | + = help: items from traits can only be used if the trait is in scope +help: there is an associated function `from` with a similar name + --> $SRC_DIR/core/src/convert/mod.rs:LL:COL +help: trait `TryFrom` which provides `try_from` is implemented but not in scope; perhaps you want to import it + | +LL + use std::convert::TryFrom; + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0599`. From 4a088d90708830ac6217554545badb89904f19b0 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 26 Aug 2024 13:07:01 -0400 Subject: [PATCH 21/25] Remove crashes from type_of on resolution that doesn't have a type_of --- tests/crashes/129205.rs | 5 ----- tests/crashes/129216.rs | 12 ------------ 2 files changed, 17 deletions(-) delete mode 100644 tests/crashes/129205.rs delete mode 100644 tests/crashes/129216.rs diff --git a/tests/crashes/129205.rs b/tests/crashes/129205.rs deleted file mode 100644 index f328fca247ac5..0000000000000 --- a/tests/crashes/129205.rs +++ /dev/null @@ -1,5 +0,0 @@ -//@ known-bug: rust-lang/rust#129205 - -fn x() { - T::try_from(); -} diff --git a/tests/crashes/129216.rs b/tests/crashes/129216.rs deleted file mode 100644 index 0ad6bc5c71baf..0000000000000 --- a/tests/crashes/129216.rs +++ /dev/null @@ -1,12 +0,0 @@ -//@ known-bug: rust-lang/rust#129216 -//@ only-linux - -trait Mirror { - type Assoc; -} - -struct Foo; - -fn main() { - ::Assoc::new(); -} From b11e0a883b0e932edb79ebba17e09952c8eb0084 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Mon, 26 Aug 2024 12:36:58 -0700 Subject: [PATCH 22/25] Apply suggestions from code review --- library/core/src/ptr/const_ptr.rs | 4 ++-- library/core/src/ptr/mod.rs | 2 +- library/core/src/ptr/mut_ptr.rs | 8 ++++---- library/core/src/ptr/non_null.rs | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index d7eea937ef847..77fb2e8abb9f0 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -286,7 +286,7 @@ impl *const T { /// # Safety /// /// When calling this method, you have to ensure that - /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// /// # Examples /// @@ -317,7 +317,7 @@ impl *const T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// /// # Examples /// diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index a7d6602287b90..338659c46ed9c 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -72,7 +72,7 @@ //! * The pointer must point to a valid value of type `T`. //! This means that the created reference can only refer to //! uninitialized memory through careful use of `MaybeUninit`, -//! or if the uninitialized memory is entirly contained within +//! or if the uninitialized memory is entirely contained within //! padding bytes, since //! [padding has the same validity invariant as `MaybeUninit`][ucg-pad]. //! diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index d7bb18590ed5e..64ed5a98bce8e 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -247,7 +247,7 @@ impl *mut T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// /// # Examples /// @@ -296,7 +296,7 @@ impl *mut T { /// /// # Safety /// - /// When calling this method, you have to ensure that the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// When calling this method, you have to ensure that the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// /// # Examples /// @@ -616,7 +616,7 @@ impl *mut T { /// # Safety /// /// When calling this method, you have to ensure that - /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// /// # Examples /// @@ -651,7 +651,7 @@ impl *mut T { /// # Safety /// /// When calling this method, you have to ensure that *either* the pointer is null *or* - /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). #[inline] #[unstable(feature = "ptr_as_uninit", issue = "75402")] #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index 5d5d9d401a295..ee9f23d61c787 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -342,7 +342,7 @@ impl NonNull { /// # Safety /// /// When calling this method, you have to ensure that - /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// /// # Examples /// @@ -379,7 +379,7 @@ impl NonNull { /// # Safety /// /// When calling this method, you have to ensure that - /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion) + /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). /// # Examples /// /// ``` From 4e1555462f136d3d1f312537d189c9b8d7bc921a Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Mon, 26 Aug 2024 19:52:14 +0000 Subject: [PATCH 23/25] Remove a couple of unused feature enables --- compiler/rustc_infer/src/lib.rs | 2 -- compiler/rustc_macros/src/lib.rs | 2 -- 2 files changed, 4 deletions(-) diff --git a/compiler/rustc_infer/src/lib.rs b/compiler/rustc_infer/src/lib.rs index 25ac8ba974bb6..30dc666128cb1 100644 --- a/compiler/rustc_infer/src/lib.rs +++ b/compiler/rustc_infer/src/lib.rs @@ -27,8 +27,6 @@ #![feature(iterator_try_collect)] #![feature(let_chains)] #![feature(rustdoc_internals)] -#![feature(try_blocks)] -#![feature(yeet_expr)] #![recursion_limit = "512"] // For rustdoc // tidy-alphabetical-end diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index c59f86b0a9bbe..929bc2df6f6b5 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -1,7 +1,5 @@ // tidy-alphabetical-start -#![allow(internal_features)] #![allow(rustc::default_hash_types)] -#![feature(allow_internal_unstable)] #![feature(if_let_guard)] #![feature(let_chains)] #![feature(never_type)] From b4d3fa4829c5366d1b7837f0d73c67def517b66d Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 26 Aug 2024 14:41:21 -0400 Subject: [PATCH 24/25] Remove ParamMode::ExplicitNamed --- compiler/rustc_ast_lowering/src/item.rs | 13 +------------ compiler/rustc_ast_lowering/src/lib.rs | 2 -- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index eef87879c2492..258a6cdf60e8b 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -764,18 +764,7 @@ impl<'hir> LoweringContext<'_, 'hir> { &mut self, (index, f): (usize, &FieldDef), ) -> hir::FieldDef<'hir> { - let ty = if let TyKind::Path(qself, path) = &f.ty.kind { - let t = self.lower_path_ty( - &f.ty, - qself, - path, - ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124) - ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy), - ); - self.arena.alloc(t) - } else { - self.lower_ty(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy)) - }; + let ty = self.lower_ty(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy)); let hir_id = self.lower_node_id(f.id); self.lower_attrs(hir_id, &f.attrs); hir::FieldDef { diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 4b8c47ac4b411..b968860a85e6a 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -481,8 +481,6 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> { enum ParamMode { /// Any path in a type context. Explicit, - /// Path in a type definition, where the anonymous lifetime `'_` is not allowed. - ExplicitNamed, /// The `module::Type` in `module::Type::method` in an expression. Optional, } From 2db1d2e261187fd8031af91b6af168100f453e4f Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 26 Aug 2024 13:59:21 -0400 Subject: [PATCH 25/25] Rename ParenthesizedGenericArgs to GenericArgsMode --- compiler/rustc_ast_lowering/src/delegation.rs | 4 +- compiler/rustc_ast_lowering/src/expr.rs | 4 +- compiler/rustc_ast_lowering/src/lib.rs | 2 +- compiler/rustc_ast_lowering/src/path.rs | 37 +++++++++---------- 4 files changed, 23 insertions(+), 24 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 9c073130827c8..800773482041a 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -51,7 +51,7 @@ use rustc_span::Span; use rustc_target::spec::abi; use {rustc_ast as ast, rustc_hir as hir}; -use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs}; +use super::{GenericArgsMode, ImplTraitContext, LoweringContext, ParamMode}; use crate::{ImplTraitPosition, ResolverAstLoweringExt}; pub(crate) struct DelegationResults<'hir> { @@ -323,7 +323,7 @@ impl<'hir> LoweringContext<'_, 'hir> { delegation.path.span, ast_segment, ParamMode::Optional, - ParenthesizedGenericArgs::Err, + GenericArgsMode::Err, ImplTraitContext::Disallowed(ImplTraitPosition::Path), None, ); diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index bb86e5c9325f9..a6c7714a182bf 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -20,7 +20,7 @@ use super::errors::{ NeverPatternWithBody, NeverPatternWithGuard, UnderscoreExprLhsAssign, }; use super::{ - ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs, ResolverAstLoweringExt, + GenericArgsMode, ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt, }; use crate::errors::YieldInClosure; use crate::{fluent_generated, FnDeclKind, ImplTraitPosition}; @@ -107,7 +107,7 @@ impl<'hir> LoweringContext<'_, 'hir> { e.span, seg, ParamMode::Optional, - ParenthesizedGenericArgs::Err, + GenericArgsMode::Err, ImplTraitContext::Disallowed(ImplTraitPosition::Path), // Method calls can't have bound modifiers None, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 4b8c47ac4b411..939517d7ef5a0 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -487,7 +487,7 @@ enum ParamMode { Optional, } -enum ParenthesizedGenericArgs { +enum GenericArgsMode { ParenSugar, Err, } diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 077b06acd7c8c..2ab30eff6d864 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -15,8 +15,8 @@ use super::errors::{ GenericTypeWithParentheses, UseAngleBrackets, }; use super::{ - GenericArgsCtor, ImplTraitContext, LifetimeRes, LoweringContext, ParamMode, - ParenthesizedGenericArgs, ResolverAstLoweringExt, + GenericArgsCtor, GenericArgsMode, ImplTraitContext, LifetimeRes, LoweringContext, ParamMode, + ResolverAstLoweringExt, }; use crate::ImplTraitPosition; @@ -90,10 +90,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { _ => param_mode, }; - let parenthesized_generic_args = match base_res { + let generic_args_mode = match base_res { // `a::b::Trait(Args)` Res::Def(DefKind::Trait, _) if i + 1 == proj_start => { - ParenthesizedGenericArgs::ParenSugar + GenericArgsMode::ParenSugar } // `a::b::Trait(Args)::TraitItem` Res::Def(DefKind::AssocFn, _) @@ -101,19 +101,19 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { | Res::Def(DefKind::AssocTy, _) if i + 2 == proj_start => { - ParenthesizedGenericArgs::ParenSugar + GenericArgsMode::ParenSugar } // Avoid duplicated errors. - Res::Err => ParenthesizedGenericArgs::ParenSugar, + Res::Err => GenericArgsMode::ParenSugar, // An error - _ => ParenthesizedGenericArgs::Err, + _ => GenericArgsMode::Err, }; self.lower_path_segment( p.span, segment, param_mode, - parenthesized_generic_args, + generic_args_mode, itctx, bound_modifier_allowed_features.clone(), ) @@ -168,7 +168,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { p.span, segment, param_mode, - ParenthesizedGenericArgs::Err, + GenericArgsMode::Err, itctx, None, )); @@ -210,7 +210,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { p.span, segment, param_mode, - ParenthesizedGenericArgs::Err, + GenericArgsMode::Err, ImplTraitContext::Disallowed(ImplTraitPosition::Path), None, ) @@ -224,7 +224,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { path_span: Span, segment: &PathSegment, param_mode: ParamMode, - parenthesized_generic_args: ParenthesizedGenericArgs, + generic_args_mode: GenericArgsMode, itctx: ImplTraitContext, // Additional features ungated with a bound modifier like `async`. // This is passed down to the implicit associated type binding in @@ -237,14 +237,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { GenericArgs::AngleBracketed(data) => { self.lower_angle_bracketed_parameter_data(data, param_mode, itctx) } - GenericArgs::Parenthesized(data) => match parenthesized_generic_args { - ParenthesizedGenericArgs::ParenSugar => self - .lower_parenthesized_parameter_data( - data, - itctx, - bound_modifier_allowed_features, - ), - ParenthesizedGenericArgs::Err => { + GenericArgs::Parenthesized(data) => match generic_args_mode { + GenericArgsMode::ParenSugar => self.lower_parenthesized_parameter_data( + data, + itctx, + bound_modifier_allowed_features, + ), + GenericArgsMode::Err => { // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait` let sub = if !data.inputs.is_empty() { // Start of the span to the 1st character of 1st argument