[PATCH v2 0/4] rust: add `#[macro_export_scoped]` for scoped declarative macro
From: Gary Guo
Date: Thu Dec 03 2026 - 10:58:12 EST
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.
Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
---
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/20260811-macro_export_scoped-v1-0-e7782b102819@xxxxxxxxxxx
---
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,
--
Gary Guo <gary@xxxxxxxxxxx>