Rust for Linux List
 help / color / mirror / Atom feed
From: Gary Guo <gary@garyguo.net>
To: "Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun@kernel.org>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	"Breno Leitao" <leitao@debian.org>,
	"Luis Chamberlain" <mcgrof@kernel.org>,
	"Russ Weight" <russ.weight@linux.dev>,
	"Lyude Paul" <lyude@redhat.com>
Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org,
	 driver-core@lists.linux.dev, Gary Guo <gary@garyguo.net>
Subject: [PATCH 1/4] rust: macros: add `#[macro_export_scoped]`
Date: Tue, 11 Aug 2026 13:25:53 +0100	[thread overview]
Message-ID: <20260811-macro_export_scoped-v1-1-e7782b102819@garyguo.net> (raw)
In-Reply-To: <20260811-macro_export_scoped-v1-0-e7782b102819@garyguo.net>

Due to Rust macro scoping rules, macros that are exported with
`#[macro_export_scoped]` 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 to 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 macro unique and non-guessable names.

Signed-off-by: Gary Guo <gary@garyguo.net>
---
 rust/macros/lib.rs                 | 25 ++++++++++++++++++
 rust/macros/macro_export_scoped.rs | 53 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 78 insertions(+)

diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs
index 0514fc7c0a55..6f8ef9043255 100644
--- a/rust/macros/lib.rs
+++ b/rust/macros/lib.rs
@@ -20,6 +20,7 @@
 mod for_lt;
 mod helpers;
 mod kunit;
+mod macro_export_scoped;
 mod module;
 mod paste;
 mod vtable;
@@ -320,6 +321,30 @@ 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!();
+/// ```
+#[doc(hidden)]
+#[proc_macro_attribute]
+#[allow(non_snake_case)]
+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..a14ee51d2d93
--- /dev/null
+++ b/rust/macros/macro_export_scoped.rs
@@ -0,0 +1,53 @@
+// 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!("macro_{name}_{hash:x}");
+    input.ident = Some(unique_name.clone());
+
+    Ok(quote!(
+        #[doc(hidden)]
+        #[macro_export]
+        #input
+
+        #[doc(inline)]
+        pub use #unique_name as #name;
+    ))
+}

-- 
2.54.0


  reply	other threads:[~2026-08-11 12:26 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-08-11 12:25 [PATCH 0/4] rust: add `#[macro_export_scoped]` for scoped declarative macro Gary Guo
2026-08-11 12:25 ` Gary Guo [this message]
2026-08-11 12:25 ` [PATCH 2/4] rust: build_assert: remove macro from crate root Gary Guo
2026-08-12 10:33   ` Andreas Hindborg
2026-08-11 12:25 ` [PATCH 3/4] rust: list: convert to use `#[macro_export_scoped]` Gary Guo
2026-08-11 12:25 ` [PATCH 4/4] rust: io: " Gary Guo

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260811-macro_export_scoped-v1-1-e7782b102819@garyguo.net \
    --to=gary@garyguo.net \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=driver-core@lists.linux.dev \
    --cc=leitao@debian.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=lyude@redhat.com \
    --cc=mcgrof@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=russ.weight@linux.dev \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=work@onurozkan.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox