rust: add `#[macro_export_scoped]` for scoped declarative macro
Subsystems (12)
Gary Guo
maintainerv2 cover rust: add `#[macro_export_scoped]` for scoped declarative macro
Rust's declarative macro scoping rule is confusing because it was historically purely textual scoped and the path-based scoping is added as an afterthought.
#[macro_export] will make the macro available for use outside the crate, but it also adds the macro to the root of crate. This has the issue where it prevents us from cleanly put things in modules where they belong. Macro 2.0 is supposed to address this issue, but currently it seems that we are unlikely to get macro 2.0 any time soon.
There is a way to approximate the scoping -- hide the macro from the crate root using #[doc(hidden)], and then re-export the macro from where they are supposed to appear, and undo the #[doc(hidden)] with #[doc(inline)]. We have used this approach for a few macros already. This is not fully bullet-proof; users can still reference the items from crate root, as it is hidden from documentation but is still present in name resolution.
Introduce a macro #[macro_export_scoped], that implements the above trick, so people can create new properly-scoped macros easily. Also, adopt a solution where we assign the macros non-guessable names, and then just re-export them under intended name. This removes the possibility of using the macro from incorrect path unintentionally.
---
Changes in v2:
- Rebased against rust-next, re-introduced the file() helper
- Keep cfgs on macro (Sashiko)
- Fixed more newly introduced macro usage from root
- Link to v1: https://patch.msgid.link/[email protected]
---
Gary Guo (4):
rust: macros: add #[macro_export_scoped]
rust: build_assert: remove macros from crate root
rust: list: convert to use #[macro_export_scoped]
rust: io: convert to use #[macro_export_scoped]
rust/kernel/build_assert.rs | 24 +++++---------- rust/kernel/configfs.rs | 4 +-- rust/kernel/firmware.rs | 4 +-- rust/kernel/io.rs | 31 ++++++++----------- rust/kernel/list/arc.rs | 4 +-- rust/kernel/list/arc_field.rs | 4 +-- rust/kernel/list/impl_list_item_mod.rs | 14 +++------ rust/kernel/num/casts.rs | 6 ++-- rust/kernel/pci/cap.rs | 4 +-- rust/kernel/ptr.rs | 8 ++--- rust/kernel/sync/atomic.rs | 2 +- rust/kernel/time.rs | 4 ++- rust/macros/helpers.rs | 16 ++++++++++ rust/macros/lib.rs | 28 +++++++++++++++++ rust/macros/macro_export_scoped.rs | 56 ++++++++++++++++++++++++++++++++++ scripts/Kconfig.toolchain | 3 ++ scripts/generate_rust_analyzer.py | 1 + 17 files changed, 145 insertions(+), 68 deletions(-)
---
base-commit: 82d8023ec40420ed61d7a96a173ef862741f1753
change-id: 20260811-macro_export_scoped-5ce38b5db968
Best regards,
Signature · 1 line
Gary Guo <[email protected]>
Gary Guo
maintainerPATCH v2 1/4 rust: macros: add `#[macro_export_scoped]`
Due to Rust macro scoping rules, macros that are exported with #[macro_export] gets added to the crate root, and this causes the crate root to get crowded with various macros.
We used a trick of #[doc(hidden)] + #[doc(inline)] pub use to make these macros appear to be only defined in the documentation, but this does not actually prevent them from being referenced from crate root.
Create a macro #[macro_export_scoped], that automates these definition and re-export and also give these macros unique and non-guessable names by hashing the file name and macro name (in theory this can collide if two macros are defined with the same name in the same file, but this is very unlikely; this could be fixed by including line number or macro definition in the hash, but doing so is less reproducible because the hash could change due to reformatting or macro-internal refactoring).
--- rust/macros/helpers.rs | 16 +++++++++++ rust/macros/lib.rs | 28 +++++++++++++++++++ rust/macros/macro_export_scoped.rs | 56 ++++++++++++++++++++++++++++++++++++++ scripts/Kconfig.toolchain | 3 ++ scripts/generate_rust_analyzer.py | 1 + 5 files changed, 104 insertions(+)
rust/macros/helpers.rs +16 -0
@@ -38,6 +38,22 @@ pub(crate) fn value(&self) -> String { } } +pub (crate )fn file () ->String { +#[cfg(not( CONFIG_RUSTC_HAS_SPAN_FILE ))] + { + proc_macro::Span ::call_site () + .source_file () + .path () + .to_string_lossy () + .into_owned () + } + +#[cfg( CONFIG_RUSTC_HAS_SPAN_FILE )] + { + proc_macro::Span ::call_site ().file () + } +} +/// Obtain all `#[cfg]` attributes. pub (crate )fn gather_cfg_attrs (attr: &[Attribute ]) ->impl Iterator <Item = &Attribute > + '_ { attr.iter ().filter (|a| a.path ().is_ident ("cfg" ))
rust/macros/lib.rs +28 -0
@@ -8,6 +8,11 @@// Stable since Rust 1.87.0. #![feature(extract_if)] +// +// Stable since Rust 1.88.0 under a different name, `proc_macro_span_file`, +// which was added in Rust 1.88.0. This is why `cfg_attr` is used here, i.e. +// to avoid depending on the full `proc_macro_span` on Rust >= 1.88.0. +#![cfg_attr(not( CONFIG_RUSTC_HAS_SPAN_FILE ), feature(proc_macro_span))] mod concat_idents;mod export;
@@ -16,6 +21,7 @@mod helpers;mod io;mod kunit; +mod macro_export_scoped;mod module;mod paste;mod vtable;
@@ -319,6 +325,28 @@ pub fn concat_idents(input: TokenStream) -> TokenStream { concat_idents::concat_idents (parse_macro_input! (input)).into () } +/// Export a macro publicly, but from the current module instead of crate root. +/// +/// # Examples +/// +/// ``` +/// mod foo { +/// #[kernel::macros::macro_export_scoped] +/// macro_rules! my_macro { +/// () => {} +/// } +/// } +/// +/// foo::my_macro!(); +/// ``` +#[proc_macro_attribute] +pub fn macro_export_scoped (attr:TokenStream , input:TokenStream ) ->TokenStream { +parse_macro_input! (attras syn::parse::Nothing ); + macro_export_scoped::macro_export_scoped (parse_macro_input! (input)) + .unwrap_or_else (|e| e.into_compile_error ()) + .into () +} +/// Paste identifiers together. /// /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
rust/macros/macro_export_scoped.rs new file +56 -0
56 lines not on this page · raw message
scripts/Kconfig.toolchain +3 -0
@@ -275,6 +275,9 @@ config LD_CAN_USE_KEEP_IN_OVERLAY # https://github.com/llvm/llvm-project/pull/130661 def_bool LD_IS_BFD || LLD_VERSION >= 210000 +config RUSTC_HAS_SPAN_FILE + def_bool RUSTC_VERSION >= 108800 + config RUSTC_HAS_UNNECESSARY_TRANSMUTES def_bool RUSTC_VERSION >= 108800
scripts/generate_rust_analyzer.py +1 -0
@@ -250,6 +250,7 @@ def generate_crates( "macros", srctree / "rust" / "macros" / "lib.rs", [std, proc_macro, proc_macro2, quote, syn], + cfg=generated_cfg, ) zerocopy_derive = append_proc_macro_crate(
Signature · 1 line
2.56.1
Gary Guo
maintainerPATCH v2 2/4 rust: build_assert: remove macros from crate root
In reply to Gary GuoConvert build_assert to use #[macro_export_scoped]. This removes the macros from crate root of kernel. A few remaining mentions of the macros from crate root are removed.
--- rust/kernel/build_assert.rs | 24 +++++++----------------- rust/kernel/configfs.rs | 4 ++-- rust/kernel/firmware.rs | 4 ++-- rust/kernel/num/casts.rs | 6 +++--- rust/kernel/ptr.rs | 8 ++------ rust/kernel/sync/atomic.rs | 2 +- rust/kernel/time.rs | 4 +++- 7 files changed, 20 insertions(+), 32 deletions(-)
rust/kernel/build_assert.rs +7 -17
@@ -61,17 +61,11 @@//! undefined symbols and linker errors, it is not developer friendly to debug, so it is recommended //! to avoid it and prefer other two assertions where possible. -#[doc(inline)] -pub use crate ::{ - build_assert_macroas build_assert, - build_error, - const_assert, - static_assert,// -}; -#[doc(hidden)] pub use build_error::build_erroras build_error_fn; +use macros::macro_export_scoped; +/// Static assert (i.e. compile-time assert). /// /// Similar to C11 [`_Static_assert`] and C++11 [`static_assert`].
@@ -105,8 +99,7 @@/// static_assert!(f(40) == 42); /// static_assert!(f(40) == 42, "f(x) must add 2 to the given input."); /// ``` -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! static_assert { ($condition:expr $(,$arg:literal)?) => {const _: () = ::core::assert!($condition $(,$arg)?);
@@ -134,8 +127,7 @@ macro_rules! static_assert {/// const_assert!(size_of::<T>() > 0, "T cannot be ZST"); /// } /// ``` -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! const_assert { ($condition:expr $(,$arg:literal)?) => {const { ::core::assert!($condition $(,$arg)?) };
@@ -159,8 +151,7 @@ macro_rules! const_assert {/// assert_eq!(foo(usize::MAX - 1), usize::MAX); // OK. /// // foo(usize::MAX); // Fails to compile. /// ``` -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! build_error { () => {{ $crate::build_assert::build_error_fn ("" )
@@ -203,9 +194,8 @@ macro_rules! build_error {/// /// const _: () = const_bar(2); /// ``` -#[macro_export] -#[doc(hidden)] -macro_rules! build_assert_macro { +#[macro_export_scoped] +macro_rules! build_assert { ($cond:expr $(,)?) => {{if !$cond { $crate::build_assert::build_error_fn (concat! ("assertion failed: " ,stringify! ($cond)));
rust/kernel/configfs.rs +2 -2
@@ -541,7 +541,7 @@ pub trait GroupOperations: Sync {/// NOTE: "drop" in the name of this function is not related to the Rust drop term. Rather, the /// name is inherited from the callback name in the underlying C code. fn drop_item (&self, _child:ArcBorrow <'_,Group <Self ::Child >>) { - kernel::build_error!(kernel::error::VTABLE_DEFAULT_ERROR ) +build_error! (kernel::error::VTABLE_DEFAULT_ERROR ) } }
@@ -694,7 +694,7 @@ pub trait AttributeOperations<const ID: u64 = 0> {/// Implementations should parse the value from `page` and update internal /// state to reflect the parsed value. fn store (_data: &Self ::Data , _page: &[u8 ]) ->Result { - kernel::build_error!(kernel::error::VTABLE_DEFAULT_ERROR ) +build_error! (kernel::error::VTABLE_DEFAULT_ERROR ) } }
rust/kernel/firmware.rs +2 -2
@@ -325,7 +325,7 @@ const fn push_internal(mut self, bytes: &[u8]) -> Self {pub const fn push (self, s: &str ) ->Self {// Check whether there has been an initial call to `next_entry()`. if N !=0 && self.n ==0 { -crate ::build_error!("Must call next_entry() before push()." ); +build_error! ("Must call next_entry() before push()." ); } self.push_internal (s.as_bytes ())
@@ -369,7 +369,7 @@ pub const fn new_entry(self) -> Self {if this.n ==N { this.buf }else { -crate ::build_error!("Length mismatch." ); +build_error! ("Length mismatch." ); } } }
rust/kernel/num/casts.rs +3 -3
@@ -81,7 +81,7 @@ macro_rules! impl_safe_as {/// ``` #[inline] pub const fn [<$from _as_ $into>](value: $from) -> $into { - $crate::static_assert!(size_of ::<$into>() >=size_of ::<$from>()); +static_assert! (size_of ::<$into>() >=size_of ::<$from>()); valueas $into }
@@ -217,10 +217,10 @@ macro_rules! impl_const_into {#[inline] pub const fn [<$from _into_ $into>]<const N: $from>() -> $into {// Make sure that the target type is smaller than the source one. - $crate::static_assert!($from::BITS >= $into::BITS ); +static_assert! ($from::BITS >= $into::BITS );// CAST: we statically enforced above that `$from` is larger than `$into`, so the // `as` conversion will be lossless. - $crate::const_assert!(N >= $into::MIN as $from &&N <= $into::MAX as $from); +const_assert! (N >= $into::MIN as $from &&N <= $into::MAX as $from);N as $into }
rust/kernel/ptr.rs +2 -6
@@ -5,15 +5,11 @@pub mod projection;pub use crate ::project_pointeras project; -use core::mem::{ - align_of, - size_of,// -};use core::num::NonZero ;use crate ::{ - const_assert, - num::FromConst ,// + num::FromConst , + prelude::*,// };/// Type representing an alignment, which is always a power of two.
rust/kernel/sync/atomic.rs +1 -1
@@ -25,7 +25,7 @@pub (crate )use internal::{AtomicArithmeticOps ,AtomicBasicOps ,AtomicExchangeOps }; -use crate ::build_error; +use crate ::build_assert::build_error;use internal::AtomicRepr ;use ordering::OrderingType ;
rust/kernel/time.rs +3 -1
@@ -27,6 +27,8 @@use core::marker::PhantomData ;use core::ops; +use crate ::prelude::*; +pub mod delay;pub mod hrtimer;
@@ -619,7 +621,7 @@ pub fn to_jiffies_timeout(self) -> Delta<Jiffy> {// The quotient `(nsecs * HZ + NSEC_PER_SEC - 1) / NSEC_PER_SEC` has to fit in // `u64`; `nsecs * HZ` does not. With `HZ <= NSEC_PER_SEC` the numerator is at // most `(nsecs + 1) * NSEC_PER_SEC - 1`, so the quotient is at most `nsecs`. -crate ::static_assert!(HZ <=NSEC_PER_SEC as u64 ); +static_assert! (HZ <=NSEC_PER_SEC as u64 );// CAST: `i64::max()` makes the value non-negative, so the cast keeps it. let nsecs = i64::max (self.as_nanos (),0 )as u64 ;
Signature · 1 line
2.56.1
Gary Guo
maintainerPATCH v2 3/4 rust: list: convert to use `#[macro_export_scoped]`
In reply to Gary GuoConvert list macros that use #[macro_export] + #[doc(hidden)] trick to use the #[macro_export_scoped] macro.
--- rust/kernel/list/arc.rs | 4 +--- rust/kernel/list/arc_field.rs | 4 +--- rust/kernel/list/impl_list_item_mod.rs | 14 +++++--------- 3 files changed, 7 insertions(+), 15 deletions(-)
rust/kernel/list/arc.rs +1 -3
@@ -81,8 +81,7 @@ pub unsafe trait TryNewListArc<const ID: u64 = 0>: ListArcSafe<ID> {/// The `tracked_by` strategy is usually used by deferring to a field of type /// [`AtomicTracker`]. However, it is also possible to defer the tracking to another struct /// using also using this macro. -#[macro_export] -#[doc(hidden)] +#[macros::macro_export_scoped] macro_rules! impl_list_arc_safe { (impl $({$($generics:tt)*})?ListArcSafe <$num:tt>for $t:ty { untracked; } $($rest:tt)*) => {impl $(<$($generics)*>)? $crate::list::ListArcSafe <$num>for $t {
@@ -127,7 +126,6 @@ fn try_new_list_arc(&self) -> bool { () => {}; } -pub use impl_list_arc_safe;/// A wrapper around [`Arc`] that's guaranteed unique for the given id. ///
rust/kernel/list/arc_field.rs +1 -3
@@ -65,8 +65,7 @@ pub unsafe fn assert_mut(&self) -> &mut T { }/// Defines getters for a [`ListArcField`]. -#[macro_export] -#[doc(hidden)] +#[macros::macro_export_scoped] macro_rules! define_list_arc_field_getter { ($pub:vis fn $name:ident(&self $(<$id:tt>)?) -> &$typ:ty { $field:ident } $($rest:tt)*
@@ -94,4 +93,3 @@ macro_rules! define_list_arc_field_getter { () => {}; } -pub use define_list_arc_field_getter;
rust/kernel/list/impl_list_item_mod.rs +5 -9
@@ -4,6 +4,8 @@//! Helpers for implementing list traits safely. +use macros::macro_export_scoped; +/// Declares that this type has a [`ListLinks<ID>`] field. /// /// This trait is only used to help implement [`ListItem`] safely. If [`ListItem`] is implemented
@@ -28,8 +30,7 @@ pub unsafe trait HasListLinks<const ID: u64 = 0> { }/// Implements the [`HasListLinks`] trait for the given type. -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! impl_has_list_links { ($(impl$({$($generics:tt)*})? HasListLinks$(<$id:tt>)?
@@ -55,7 +56,6 @@ unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut $crate::list::ListLinks$(<$ } )*}; } -pub use impl_has_list_links;/// Declares that the [`ListLinks<ID>`] field in this struct is inside a /// [`ListLinksSelfPtr<T, ID>`].
@@ -74,8 +74,7 @@ pub unsafe trait HasSelfPtr<T: ?Sized, const ID: u64 = 0> }/// Implements the [`HasListLinks`] and [`HasSelfPtr`] traits for the given type. -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! impl_has_list_links_self_ptr { ($(impl$({$($generics:tt)*})? HasSelfPtr<$item_type:ty $(, $id:tt)?>
@@ -98,7 +97,6 @@ unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut $crate::list::ListLinks$(<$ } )*}; } -pub use impl_has_list_links_self_ptr;/// Implements the [`ListItem`] trait for the given type. ///
@@ -182,8 +180,7 @@ unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut $crate::list::ListLinks$(<$/// } /// } /// ``` -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! impl_list_item { ( $(impl$({$($generics:tt)*})? ListItem<$num:tt> for $self:ty {
@@ -358,4 +355,3 @@ unsafe fn post_remove(me: *mut $crate::list::ListLinks<$num>) -> *const Self { } )*}; } -pub use impl_list_item;
Signature · 1 line
2.56.1
Gary Guo
maintainerPATCH v2 4/4 rust: io: convert to use `#[macro_export_scoped]`
In reply to Gary GuoConvert I/O macros that use #[macro_export] + #[doc(hidden)] trick to use the #[macro_export_scoped] macro.
--- rust/kernel/io.rs | 31 ++++++++++++------------------- rust/kernel/pci/cap.rs | 4 ++-- 2 files changed, 14 insertions(+), 21 deletions(-)
rust/kernel/io.rs +12 -19
@@ -10,6 +10,8 @@ num::TryFromIntError, // }; +use macros::macro_export_scoped; +use crate ::{ bindings, fmt,
@@ -1818,8 +1820,7 @@ pub fn project_loc<U, L>(self, location: L) -> <T::Backend as IoBackend>::View<'/// let reg: Mmio<'_, FIELD> = io_project!(whole, build: FIELD); /// # Ok::<(), Error>(()) } /// ``` -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! io_project {// Register projection ($io:expr, try: $ioloc:expr) => {{
@@ -1848,8 +1849,6 @@ macro_rules! io_project {unsafe { view.project_view (ptr) } }}; } -#[doc(inline)] -pub use crate ::io_project;/// Read from I/O memory. ///
@@ -1867,15 +1866,12 @@ macro_rules! io_project {/// let field: u32 = kernel::io::io_read!(mmio, [try: 2].field); /// # Ok::<(), Error>(()) } /// ``` -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! io_read { ($io:expr, $($proj:tt)*) => { - $crate::io::Io ::read_val ($crate::io_project!($io, $($proj)*)) + $crate::io::Io ::read_val ($crate::io::io_project!($io, $($proj)*)) }; } -#[doc(inline)] -pub use crate ::io_read;/// Writes to I/O memory. ///
@@ -1894,27 +1890,24 @@ macro_rules! io_read {/// kernel::io::io_write!(mmio, [try: 2].field, 10); /// # Ok::<(), Error>(()) } /// ``` -#[macro_export] -#[doc(hidden)] +#[macro_export_scoped] macro_rules! io_write { (@parse [$io:expr] [$($proj:tt)*] [, $val:expr]) => { - $crate::io::Io ::write_val ($crate::io_project!($io, $($proj)*), $val) + $crate::io::Io ::write_val ($crate::io::io_project!($io, $($proj)*), $val) }; (@parse [$io:expr] [$($proj:tt)*] [.$field:tt $($rest:tt)*]) => { - $crate::io_write!(@parse [$io] [$($proj)* .$field] [$($rest)*]) + $crate::io::io_write!(@parse [$io] [$($proj)* .$field] [$($rest)*]) }; (@parse [$io:expr] [$($proj:tt)*] [[$flavor:ident: $index:expr] $($rest:tt)*]) => { - $crate::io_write!(@parse [$io] [$($proj)* [$flavor: $index]] [$($rest)*]) + $crate::io::io_write!(@parse [$io] [$($proj)* [$flavor: $index]] [$($rest)*]) }; (@parse [$io:expr] [] [try: $ioloc:expr, $($rest:tt)*]) => { - $crate::io_write!(@parse [$io] [try: $ioloc] [, $($rest)*]) + $crate::io::io_write!(@parse [$io] [try: $ioloc] [, $($rest)*]) }; (@parse [$io:expr] [] [build: $ioloc:expr, $($rest:tt)*]) => { - $crate::io_write!(@parse [$io] [build: $ioloc] [, $($rest)*]) + $crate::io::io_write!(@parse [$io] [build: $ioloc] [, $($rest)*]) }; ($io:expr, $($rest:tt)*) => { - $crate::io_write!(@parse [$io] [] [$($rest)*]) + $crate::io::io_write!(@parse [$io] [] [$($rest)*]) }; } -#[doc(inline)] -pub use crate ::io_write;
rust/kernel/pci/cap.rs +2 -2
@@ -237,7 +237,7 @@ impl ExtSriovCapability<'_> {/// VF Offset itself. #[inline] pub fn first_vf_offset (&self) ->u16 { -crate ::io_read!(*self, .vf_offset) +crate ::io::io_read!(*self, .vf_offset) }/// Returns an iterator over decoded VF BAR register encodings.
@@ -252,7 +252,7 @@ pub fn first_vf_offset(&self) -> u16 {/// memory BAR, or if a 64-bit encoding has no upper DWORD. pub fn vf_bars (&self) ->Result <impl Iterator <Item =ExtSriovVfBar >> {let slots: [u32 ;NUM_VF_BARS ] = - core::array::from_fn (|slot|crate ::io_read!(*self, .vf_bar[panic: slot])); + core::array::from_fn (|slot|crate ::io::io_read!(*self, .vf_bar[panic: slot]));let mut slots = slots.into_iter ();let mut bars = [None ;NUM_VF_BARS ];let mut count =0 ;
Signature · 1 line
2.56.1