mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH v3 0/2] rust: const_eval: add `#[const_only]` attribute
@ 2026-12-03 18:24 Gary Guo
  2026-12-03 18:24 ` [PATCH v3 1/2] rust: generalize `build_error` to `const_eval_select` Gary Guo
  2026-12-03 18:24 ` [PATCH v3 2/2] rust: const_eval: add `#[const_only]` attribute Gary Guo
  0 siblings, 2 replies; 3+ messages in thread
From: Gary Guo @ 2026-12-03 18:24 UTC (permalink / raw)
  To: Eliot Courtney, Miguel Ojeda, Boqun Feng, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan
  Cc: linux-kernel, rust-for-linux, Gary Guo

We have a lot of helper const functions which are intended to be used
during const evaluation only and runtime calls should not be generated. Add
a macro to denote this explicitly.

This is similar to C++'s consteval keyword; however, I did not use
`consteval` as the name of the attribute as it fails to capture that
annotated functions *must only* be used in const evaluation. My preferred
name for this attribute is actually `#[const_eval_only]` but after sampling
people's opinion on the attribute, it was settled that `#[const_only]` is
the name that most people are okay with.

I refactored build_error.rs to const_eval_select.rs to make it generic
enough for any functions that we prefer different behaviour between const
eval and runtime. The rust/Makefile changes are generated by Gemini 4 Neon
and I have validated it.

Signed-off-by: Gary Guo <gary@garyguo.net>
---
Changes in v3:
- Renamed the attribute.
- Dropped `const_call!`, keep `#[const_only]` only.
- Refactored build_error so CONFIG_RUST_BUILD_ASSERT_ALLOW has reasonable
  behaviour for `assert_in_const_eval`.
- Link to v2: https://patch.msgid.link/20260903-cv-v2-0-e93b1613e40c@garyguo.net

Changes in v2:
- Split from `cv!()` alt series, and become a general infra instead.
- Link to v1: https://patch.msgid.link/20260828-cv-v1-0-694a695ff17f@garyguo.net

---
Gary Guo (2):
      rust: generalize `build_error` to `const_eval_select`
      rust: const_eval: add `#[const_only]` attribute

 rust/Makefile                     | 64 ++++++++++++++++++++++++++-------------
 rust/build_error.rs               | 31 -------------------
 rust/const_eval_select.rs         | 44 +++++++++++++++++++++++++++
 rust/exports.c                    |  6 +---
 rust/kernel/build_assert.rs       |  2 +-
 rust/kernel/const_eval.rs         |  9 ++++++
 rust/kernel/device_id.rs          |  4 +++
 rust/kernel/lib.rs                |  1 +
 rust/macros/const_eval.rs         | 24 +++++++++++++++
 rust/macros/lib.rs                | 23 ++++++++++++++
 scripts/generate_rust_analyzer.py |  8 ++---
 11 files changed, 154 insertions(+), 62 deletions(-)
---
base-commit: 82d8023ec40420ed61d7a96a173ef862741f1753
change-id: 20260828-cv-acaf3400d16c

Best regards,
--  
Gary Guo <gary@garyguo.net>


^ permalink raw reply	[flat|nested] 3+ messages in thread

* [PATCH v3 1/2] rust: generalize `build_error` to `const_eval_select`
  2026-12-03 18:24 [PATCH v3 0/2] rust: const_eval: add `#[const_only]` attribute Gary Guo
@ 2026-12-03 18:24 ` Gary Guo
  2026-12-03 18:24 ` [PATCH v3 2/2] rust: const_eval: add `#[const_only]` attribute Gary Guo
  1 sibling, 0 replies; 3+ messages in thread
From: Gary Guo @ 2026-12-03 18:24 UTC (permalink / raw)
  To: Eliot Courtney, Miguel Ojeda, Boqun Feng, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan
  Cc: linux-kernel, rust-for-linux, Gary Guo

Generalize the `build_error` crate to be a general-purpose
`const_eval_select` instead, which will be the home for everything that we
want to behave differently depending on whether it's in const-eval or
runtime.

For this to work, the build is reworked so rmeta/obj generation are split
with different cfgs. The object file generated is always linked; in the
absence of CONFIG_RUST_BUILD_ASSERT_ALLOW, `rust_build_error` will simply
be absent from the object file.

Signed-off-by: Gary Guo <gary@garyguo.net>
---
 rust/Makefile                     | 64 ++++++++++++++++++++++++++-------------
 rust/build_error.rs               | 31 -------------------
 rust/const_eval_select.rs         | 32 ++++++++++++++++++++
 rust/exports.c                    |  6 +---
 rust/kernel/build_assert.rs       |  2 +-
 scripts/generate_rust_analyzer.py |  8 ++---
 6 files changed, 81 insertions(+), 62 deletions(-)

diff --git a/rust/Makefile b/rust/Makefile
index 80028738e51d..d938b9e9e0ad 100644
--- a/rust/Makefile
+++ b/rust/Makefile
@@ -28,11 +28,9 @@ always-$(CONFIG_RUST) += exports_bindings_generated.h exports_kernel_generated.h
 always-$(CONFIG_RUST) += uapi/uapi_generated.rs
 obj-$(CONFIG_RUST) += uapi.o
 
-ifdef CONFIG_RUST_BUILD_ASSERT_ALLOW
-obj-$(CONFIG_RUST) += build_error.o
-else
-always-$(CONFIG_RUST) += build_error.o
-endif
+obj-$(CONFIG_RUST) += const_eval_select.o
+always-$(CONFIG_RUST) += libconst_eval_select.rmeta
+always-$(CONFIG_RUST) += exports_const_eval_select_generated.h
 
 obj-$(CONFIG_RUST) += exports.o
 
@@ -280,7 +278,7 @@ rustdoc-pin_init: $(src)/pin-init/src/lib.rs rustdoc-pin_init_internal \
 
 rustdoc-kernel: private is-kernel-object := y
 rustdoc-kernel: private rustc_target_flags = --extern ffi --extern pin_init \
-    --extern build_error --extern macros \
+    --extern const_eval_select --extern macros \
     --extern bindings --extern uapi \
     --extern zerocopy --extern zerocopy_derive
 rustdoc-kernel: $(src)/kernel/lib.rs rustdoc-core rustdoc-ffi rustdoc-macros \
@@ -307,7 +305,8 @@ rusttestlib-zerocopy: private rustc_target_flags = $(zerocopy-flags)
 rusttestlib-zerocopy: $(src)/zerocopy/src/lib.rs FORCE
 	+$(call if_changed,rustc_test_library)
 
-rusttestlib-build_error: $(src)/build_error.rs FORCE
+rusttestlib-const_eval_select: private rustc_target_flags = --cfg const_eval
+rusttestlib-const_eval_select: $(src)/const_eval_select.rs FORCE
 	+$(call if_changed,rustc_test_library)
 
 rusttestlib-ffi: $(src)/ffi.rs FORCE
@@ -352,12 +351,12 @@ rusttestlib-pin_init: $(src)/pin-init/src/lib.rs rusttestlib-macros \
 	+$(call if_changed,rustc_test_library)
 
 rusttestlib-kernel: private rustc_target_flags = --extern ffi \
-    --extern build_error --extern macros --extern pin_init \
+    --extern const_eval_select --extern macros --extern pin_init \
     --extern bindings --extern uapi \
     --extern zerocopy=$(objtree)/$(obj)/test/libzerocopy.rlib \
     --extern zerocopy_derive=$(objtree)/$(obj)/test/$(libzerocopy_derive_name)
 rusttestlib-kernel: $(src)/kernel/lib.rs rusttestlib-bindings rusttestlib-uapi \
-    rusttestlib-build_error rusttestlib-pin_init $(obj)/$(libmacros_name) \
+    rusttestlib-const_eval_select rusttestlib-pin_init $(obj)/$(libmacros_name) \
     $(obj)/bindings.o rusttestlib-zerocopy rusttestlib-zerocopy_derive FORCE
 	+$(call if_changed,rustc_test_library)
 
@@ -390,7 +389,7 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $<
 	OBJTREE=$(abspath $(objtree)) \
 	$(RUSTDOC) --test $(filter-out --remap-path-scope=%,$(rust_flags)) \
 		-L$(objtree)/$(obj) --extern ffi --extern pin_init \
-		--extern kernel --extern build_error --extern macros \
+		--extern kernel --extern const_eval_select --extern macros \
 		--extern bindings --extern uapi \
 		--extern zerocopy --extern zerocopy_derive \
 		--no-run --crate-name kernel -Zunstable-options \
@@ -577,6 +576,9 @@ $(obj)/exports_helpers_generated.h: $(obj)/helpers/helpers.o FORCE
 $(obj)/exports_bindings_generated.h: $(obj)/bindings.o FORCE
 	$(call if_changed,exports)
 
+$(obj)/exports_const_eval_select_generated.h: $(obj)/const_eval_select.o FORCE
+	$(call if_changed,exports)
+
 $(obj)/exports_kernel_generated.h: $(obj)/kernel.o FORCE
 	$(call if_changed,exports)
 
@@ -636,18 +638,22 @@ $(obj)/$(libpin_init_internal_name): $(src)/pin-init/internal/src/lib.rs \
 
 # `rustc` requires `-Zunstable-options` to use custom target specifications
 # since Rust 1.95.0 (https://github.com/rust-lang/rust/pull/151534).
-quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L $@
-      cmd_rustc_library = \
+rustc_library_common = \
 	$(rustc_target_envs) \
 	OBJTREE=$(abspath $(objtree)) \
 	$(if $(skip_clippy),$(RUSTC),$(RUSTC_OR_CLIPPY)) \
 		$(filter-out $(skip_flags),$(rust_flags)) $(rustc_target_flags) \
-		--emit=dep-info=$(depfile) --emit=$(if $(link_helper),llvm-bc=$(patsubst %.o,%.bc,$@),obj=$@) \
-		--emit=metadata=$(dir $@)$(patsubst %.o,lib%.rmeta,$(notdir $@)) \
+		--emit=dep-info=$(depfile) \
 		--crate-type rlib -L$(objtree)/$(obj) \
-		--crate-name $(patsubst %.o,%,$(notdir $@)) $< \
 		--sysroot=/dev/null \
-		-Zunstable-options \
+		-Zunstable-options
+
+quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L $@
+      cmd_rustc_library = \
+	$(rustc_library_common) \
+	--emit=$(if $(link_helper),llvm-bc=$(patsubst %.o,%.bc,$@),obj=$@) \
+	$(if $(skip_rmeta),,--emit=metadata=$(dir $@)$(patsubst %.o,lib%.rmeta,$(notdir $@))) \
+	--crate-name $(patsubst %.o,%,$(notdir $@)) $< \
 	$(if $(link_helper),;$(LLVM_LINK) --internalize --suppress-warnings $(patsubst %.o,%.bc,$@) \
 		$(obj)/helpers/helpers$(if $(part-of-module),_module).bc -o $(patsubst %.o,%.m.bc,$@); \
 		$(CC) $(CLANG_FLAGS) $(filter-out $(CC_FLAGS_LTO),$(KBUILD_CFLAGS) $(modkern_cflags)) \
@@ -656,6 +662,15 @@ quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L
 	$(if $(rustc_objcopy),;$(OBJCOPY) $(rustc_objcopy) $@) \
 	$(cmd_objtool)
 
+# `--emit=obj=/dev/null` is needed to avoid rustc complaining about
+# "missing optimized MIR for an item" on dependent crates.
+quiet_cmd_rustc_rmeta = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) M $@
+      cmd_rustc_rmeta = \
+	$(rustc_library_common) \
+	--emit=obj=/dev/null \
+	--emit=metadata=$@ \
+	--crate-name $(patsubst lib%.rmeta,%,$(notdir $@)) $<
+
 rust-analyzer:
 	$(Q)MAKEFLAGS= $(srctree)/scripts/generate_rust_analyzer.py \
 		--cfgs='core=$(core-cfgs)' $(core-edition) \
@@ -666,6 +681,7 @@ rust-analyzer:
 		--cfgs='zerocopy_derive=$(zerocopy_derive-cfgs)' \
 		--cfgs='pin_init_internal=$(pin_init_internal-cfgs)' \
 		--cfgs='pin_init=$(pin_init-cfgs)' \
+		--cfgs='const_eval_select=const_eval' \
 		--envs='zerocopy=$(zerocopy-envs)' \
 		$(realpath $(srctree)) $(realpath $(objtree)) \
 		$(rustc_sysroot) $(RUST_LIB_SRC) $(if $(KBUILD_EXTMOD),$(srcroot)) \
@@ -755,11 +771,17 @@ $(obj)/pin_init.o: $(src)/pin-init/src/lib.rs $(obj)/compiler_builtins.o \
     $(obj)/$(libpin_init_internal_name) $(obj)/$(libmacros_name) FORCE
 	+$(call if_changed_rule,rustc_library)
 
-# Even if normally `build_error` is not a kernel object, it should still be
+# Even though `libconst_eval_select.rmeta` is not a kernel object, it should still be
 # treated as such so that we pass the same flags. Otherwise, for instance,
 # `rustc` will complain about missing sanitizer flags causing an ABI mismatch.
-$(obj)/build_error.o: private is-kernel-object := y
-$(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FORCE
+$(obj)/libconst_eval_select.rmeta: private is-kernel-object := y
+$(obj)/libconst_eval_select.rmeta: private rustc_target_flags = --cfg=const_eval
+$(obj)/libconst_eval_select.rmeta: $(src)/const_eval_select.rs $(obj)/compiler_builtins.o FORCE
+	+$(call if_changed_dep,rustc_rmeta)
+
+$(obj)/const_eval_select.o: private skip_rmeta = 1
+$(obj)/const_eval_select.o: $(src)/const_eval_select.rs $(obj)/compiler_builtins.o \
+    $(obj)/libconst_eval_select.rmeta FORCE
 	+$(call if_changed_rule,rustc_library)
 
 $(obj)/ffi.o: private skip_gendwarfksyms = 1
@@ -783,9 +805,9 @@ $(obj)/uapi.o: $(src)/uapi/lib.rs \
 	+$(call if_changed_rule,rustc_library)
 
 $(obj)/kernel.o: private rustc_target_flags = --extern ffi --extern pin_init \
-    --extern build_error --extern macros --extern bindings --extern uapi \
+    --extern const_eval_select --extern macros --extern bindings --extern uapi \
     --extern zerocopy --extern zerocopy_derive
-$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/build_error.o $(obj)/pin_init.o \
+$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/const_eval_select.o $(obj)/pin_init.o \
     $(obj)/$(libmacros_name) $(obj)/bindings.o $(obj)/uapi.o \
     $(obj)/zerocopy.o $(obj)/$(libzerocopy_derive_name) FORCE
 	+$(call if_changed_rule,rustc_library)
diff --git a/rust/build_error.rs b/rust/build_error.rs
deleted file mode 100644
index fa24eeef9929..000000000000
--- a/rust/build_error.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0
-
-//! Build-time error.
-//!
-//! This crate provides a [const function][const-functions] `build_error`, which will panic in
-//! compile-time if executed in [const context][const-context], and will cause a build error
-//! if not executed at compile time and the optimizer does not optimise away the call.
-//!
-//! It is used by `build_assert!` in the kernel crate, allowing checking of
-//! conditions that could be checked statically, but could not be enforced in
-//! Rust yet (e.g. perform some checks in [const functions][const-functions], but those
-//! functions could still be called in the runtime).
-//!
-//! For details on constant evaluation in Rust, please see the [Reference][const-eval].
-//!
-//! [const-eval]: https://doc.rust-lang.org/reference/const_eval.html
-//! [const-functions]: https://doc.rust-lang.org/reference/const_eval.html#const-functions
-//! [const-context]: https://doc.rust-lang.org/reference/const_eval.html#const-context
-
-#![no_std]
-
-/// Panics if executed in [const context][const-context], or triggers a build error if not.
-///
-/// [const-context]: https://doc.rust-lang.org/reference/const_eval.html#const-context
-#[inline(never)]
-#[cold]
-#[export_name = "rust_build_error"]
-#[track_caller]
-pub const fn build_error(msg: &'static str) -> ! {
-    panic!("{}", msg);
-}
diff --git a/rust/const_eval_select.rs b/rust/const_eval_select.rs
new file mode 100644
index 000000000000..fb0670a8d925
--- /dev/null
+++ b/rust/const_eval_select.rs
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Functions that behave differently between const evaluation and runtime.
+//!
+//! This crate serves the same purpose as the `const_eval_select` Rust compiler intrinsic, but
+//! implemented using linking tricks.
+//!
+//! For details on constant evaluation in Rust, please see the [Reference][const-eval].
+//!
+//! [const-eval]: https://doc.rust-lang.org/reference/const_eval.html
+
+#![no_std]
+
+/// Panics if executed in [const context][const-context], or triggers a build error if not.
+///
+/// This will trigger a build error if the optimizer does not optimise away the call.
+///
+/// It is used by `build_assert!` in the kernel crate, allowing checking of
+/// conditions that could be checked statically, but could not be enforced in
+/// Rust yet (e.g. perform some checks in [const functions][const-functions], but those
+/// functions could still be called in the runtime).
+///
+/// [const-context]: https://doc.rust-lang.org/reference/const_eval.html#const-context
+/// [const-functions]: https://doc.rust-lang.org/reference/const_eval.html#const-functions
+#[cfg(any(const_eval, CONFIG_RUST_BUILD_ASSERT_ALLOW))]
+#[inline(never)]
+#[cold]
+#[export_name = "rust_build_error"]
+#[track_caller]
+pub const fn build_error(msg: &'static str) -> ! {
+    panic!("{}", msg);
+}
diff --git a/rust/exports.c b/rust/exports.c
index 1b52460b0f4e..47aacc1f817b 100644
--- a/rust/exports.c
+++ b/rust/exports.c
@@ -17,13 +17,9 @@
 
 #include "exports_core_generated.h"
 #include "exports_bindings_generated.h"
+#include "exports_const_eval_select_generated.h"
 #include "exports_kernel_generated.h"
 
 #ifndef CONFIG_RUST_INLINE_HELPERS
 #include "exports_helpers_generated.h"
 #endif
-
-// For modules using `rust/build_error.rs`.
-#ifdef CONFIG_RUST_BUILD_ASSERT_ALLOW
-EXPORT_SYMBOL_RUST_GPL(rust_build_error);
-#endif
diff --git a/rust/kernel/build_assert.rs b/rust/kernel/build_assert.rs
index c3acb9b68a65..f7f44e381cd8 100644
--- a/rust/kernel/build_assert.rs
+++ b/rust/kernel/build_assert.rs
@@ -70,7 +70,7 @@
 };
 
 #[doc(hidden)]
-pub use build_error::build_error as build_error_fn;
+pub use const_eval_select::build_error as build_error_fn;
 
 /// Static assert (i.e. compile-time assert).
 ///
diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py
index dc1219736f77..ef7180a797ec 100755
--- a/scripts/generate_rust_analyzer.py
+++ b/scripts/generate_rust_analyzer.py
@@ -258,9 +258,9 @@ def generate_crates(
         [std, proc_macro, proc_macro2, quote, syn],
     )
 
-    build_error = append_crate(
-        "build_error",
-        srctree / "rust" / "build_error.rs",
+    const_eval_select = append_crate(
+        "const_eval_select",
+        srctree / "rust" / "const_eval_select.rs",
         [core, compiler_builtins],
     )
 
@@ -316,7 +316,7 @@ def generate_crates(
     bindings = append_crate_with_generated("bindings", [core, ffi, pin_init])
     uapi = append_crate_with_generated("uapi", [core, ffi, pin_init])
     kernel = append_crate_with_generated(
-        "kernel", [core, macros, build_error, pin_init, ffi, bindings, uapi, zerocopy, zerocopy_derive]
+        "kernel", [core, macros, const_eval_select, pin_init, ffi, bindings, uapi, zerocopy, zerocopy_derive]
     )
 
     scripts = srctree / "scripts"

-- 
2.56.1


^ permalink raw reply	[flat|nested] 3+ messages in thread

* [PATCH v3 2/2] rust: const_eval: add `#[const_only]` attribute
  2026-12-03 18:24 [PATCH v3 0/2] rust: const_eval: add `#[const_only]` attribute Gary Guo
  2026-12-03 18:24 ` [PATCH v3 1/2] rust: generalize `build_error` to `const_eval_select` Gary Guo
@ 2026-12-03 18:24 ` Gary Guo
  1 sibling, 0 replies; 3+ messages in thread
From: Gary Guo @ 2026-12-03 18:24 UTC (permalink / raw)
  To: Eliot Courtney, Miguel Ojeda, Boqun Feng, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan
  Cc: linux-kernel, rust-for-linux, Gary Guo

We have a lot of helper const functions which are intended to be used
during const evaluation only and runtime calls should not be generated. Add
a macro to denote this explicitly.

This is similar to C++'s consteval keyword; however, I did not use
`consteval` as the name of the attribute as it fails to capture that
annotated functions *must only* be used in const evaluation.

Convert device_id.rs as an example.

Signed-off-by: Gary Guo <gary@garyguo.net>
---
 rust/const_eval_select.rs | 12 ++++++++++++
 rust/kernel/const_eval.rs |  9 +++++++++
 rust/kernel/device_id.rs  |  4 ++++
 rust/kernel/lib.rs        |  1 +
 rust/macros/const_eval.rs | 24 ++++++++++++++++++++++++
 rust/macros/lib.rs        | 23 +++++++++++++++++++++++
 6 files changed, 73 insertions(+)

diff --git a/rust/const_eval_select.rs b/rust/const_eval_select.rs
index fb0670a8d925..b80221347d66 100644
--- a/rust/const_eval_select.rs
+++ b/rust/const_eval_select.rs
@@ -30,3 +30,15 @@
 pub const fn build_error(msg: &'static str) -> ! {
     panic!("{}", msg);
 }
+
+/// Assert that the code is in const evaluation.
+///
+/// Triggers a build error if called at runtime.
+#[cfg(any(const_eval, CONFIG_RUST_BUILD_ASSERT_ALLOW))]
+#[inline(never)]
+#[export_name = "rust_const_eval_called_at_runtime"]
+#[track_caller]
+pub const fn assert_in_const_eval() {
+    #[cfg(not(const_eval))]
+    panic!("#[const_only] function called at runtime");
+}
diff --git a/rust/kernel/const_eval.rs b/rust/kernel/const_eval.rs
new file mode 100644
index 000000000000..78ac1c6480fa
--- /dev/null
+++ b/rust/kernel/const_eval.rs
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Utilities for const evaluation.
+
+#[doc(inline)]
+pub use const_eval_select::assert_in_const_eval;
+
+#[doc(inline)]
+pub use macros::const_only;
diff --git a/rust/kernel/device_id.rs b/rust/kernel/device_id.rs
index f0b9cb84e58e..126be49d9ecb 100644
--- a/rust/kernel/device_id.rs
+++ b/rust/kernel/device_id.rs
@@ -10,6 +10,8 @@
     mem::MaybeUninit, //
 };
 
+use crate::const_eval::const_only;
+
 /// Marker trait to indicate a Rust device ID type represents a corresponding C device ID type.
 ///
 /// This is meant to be implemented by buses/subsystems so that they can use [`IdTable`] to
@@ -108,6 +110,7 @@ impl<T: RawDeviceId + RawDeviceIdIndex, U: 'static, const N: usize> IdArray<T, U
     /// Creates a new instance of the array.
     ///
     /// The contents are derived from the given identifiers and context information.
+    #[const_only]
     pub const fn new(ids: [(T, &'static U); N]) -> Self {
         let mut raw_ids = [const { MaybeUninit::<T::RawType>::uninit() }; N];
 
@@ -144,6 +147,7 @@ impl<T: RawDeviceId, const N: usize> IdArray<T, (), N> {
     ///
     /// The contents are derived from the given identifiers and context information.
     /// If the device implements [`RawDeviceIdIndex`], consider using [`IdArray::new`] instead.
+    #[const_only]
     pub const fn new_without_index(ids: [T; N]) -> Self {
         // SAFETY: `T` is layout-wise compatible with `T::RawType`, so is the array of them.
         let raw_ids: [MaybeUninit<T::RawType>; N] = unsafe { crate::mem::transmute(ids) };
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 482fef8be2e8..d0bc584948e8 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -57,6 +57,7 @@
 pub mod clk;
 #[cfg(CONFIG_CONFIGFS_FS)]
 pub mod configfs;
+pub mod const_eval;
 pub mod cpu;
 #[cfg(CONFIG_CPU_FREQ)]
 pub mod cpufreq;
diff --git a/rust/macros/const_eval.rs b/rust/macros/const_eval.rs
new file mode 100644
index 000000000000..b65d23c9e420
--- /dev/null
+++ b/rust/macros/const_eval.rs
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0
+
+use proc_macro2::TokenStream;
+use quote::ToTokens;
+use syn::{
+    parse_quote,
+    ItemFn, //
+};
+
+pub(crate) fn const_only(mut input: ItemFn) -> TokenStream {
+    // Prevent code generation as the function is for const evaluation only.
+    input.attrs.push(parse_quote!(
+        #[inline(always)]
+    ));
+
+    input.block.stmts.insert(
+        0,
+        parse_quote!(
+            ::kernel::const_eval::assert_in_const_eval();
+        ),
+    );
+
+    input.into_token_stream()
+}
diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs
index f448e7f21c83..6550ffc5d0a9 100644
--- a/rust/macros/lib.rs
+++ b/rust/macros/lib.rs
@@ -10,6 +10,7 @@
 #![feature(extract_if)]
 
 mod concat_idents;
+mod const_eval;
 mod export;
 mod fmt;
 mod for_lt;
@@ -319,6 +320,28 @@ pub fn concat_idents(input: TokenStream) -> TokenStream {
     concat_idents::concat_idents(parse_macro_input!(input)).into()
 }
 
+/// Mark a function as usable from const evaluation only.
+///
+/// Build will fail if the function is used in runtime code.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::const_eval::const_only;
+///
+/// #[const_only]
+/// const fn call_for_const_eval_only() {
+///     // This code will be executed only during const eval!
+/// }
+///
+/// const _: () = call_for_const_eval_only();
+/// ```
+#[proc_macro_attribute]
+pub fn const_only(attr: TokenStream, input: TokenStream) -> TokenStream {
+    parse_macro_input!(attr as syn::parse::Nothing);
+    const_eval::const_only(parse_macro_input!(input)).into()
+}
+
 /// Paste identifiers together.
 ///
 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a

-- 
2.56.1


^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2026-12-03 18:25 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-12-03 18:24 [PATCH v3 0/2] rust: const_eval: add `#[const_only]` attribute Gary Guo
2026-12-03 18:24 ` [PATCH v3 1/2] rust: generalize `build_error` to `const_eval_select` Gary Guo
2026-12-03 18:24 ` [PATCH v3 2/2] rust: const_eval: add `#[const_only]` attribute Gary Guo

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®