[PATCH v2 1/4] rust: macros: add `#[macro_export_scoped]`
From: Gary Guo
Date: Thu Dec 03 2026 - 10:58:26 EST
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).
Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
---
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(+)
diff --git a/rust/macros/helpers.rs b/rust/macros/helpers.rs
index 8cc9a20f470e..d18fbf4daa0a 100644
--- a/rust/macros/helpers.rs
+++ b/rust/macros/helpers.rs
@@ -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"))
diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs
index f448e7f21c83..41bc11abb5cd 100644
--- a/rust/macros/lib.rs
+++ b/rust/macros/lib.rs
@@ -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!(attr as 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
diff --git a/rust/macros/macro_export_scoped.rs b/rust/macros/macro_export_scoped.rs
new file mode 100644
index 000000000000..3bbd7dbc1c28
--- /dev/null
+++ b/rust/macros/macro_export_scoped.rs
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: GPL-2.0
+
+use std::hash::{
+ DefaultHasher,
+ Hash,
+ Hasher, //
+};
+
+use proc_macro2::TokenStream;
+use quote::{
+ format_ident,
+ quote, //
+};
+use syn::{
+ Error,
+ ItemMacro,
+ Result, //
+};
+
+pub(crate) fn macro_export_scoped(mut input: ItemMacro) -> Result<TokenStream> {
+ if !input.mac.path.is_ident("macro_rules") {
+ return Err(Error::new_spanned(
+ input,
+ "#[macro_export_scoped] can only be used on `macro_rules!`",
+ ));
+ }
+
+ let Some(name) = input.ident else {
+ Err(Error::new_spanned(
+ input,
+ "`macro_rules!` definition missing an identifier",
+ ))?
+ };
+
+ // Hash together file name and macro name to create a hash that is likely to be unique. Use
+ // `DefaultHasher::new` which is free from RNG so the build is still reproducible.
+ let mut hasher = DefaultHasher::new();
+ crate::helpers::file().hash(&mut hasher);
+ name.hash(&mut hasher);
+ let hash = hasher.finish();
+
+ let unique_name = format_ident!("{name}_{hash:x}");
+ input.ident = Some(unique_name.clone());
+
+ let cfg_attrs = crate::helpers::gather_cfg_attrs(&input.attrs);
+
+ Ok(quote!(
+ #[doc(hidden)]
+ #[macro_export]
+ #input
+
+ #[doc(inline)]
+ #(#cfg_attrs)*
+ pub use #unique_name as #name;
+ ))
+}
diff --git a/scripts/Kconfig.toolchain b/scripts/Kconfig.toolchain
index 1d68075f0469..c25767b34e06 100644
--- a/scripts/Kconfig.toolchain
+++ b/scripts/Kconfig.toolchain
@@ -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
diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py
index dc1219736f77..621895bae128 100755
--- a/scripts/generate_rust_analyzer.py
+++ b/scripts/generate_rust_analyzer.py
@@ -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(
--
2.56.1