From: Gary Guo <gary@garyguo.net>
To: "Eliot Courtney" <ecourtney@nvidia.com>,
"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>
Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org,
Gary Guo <gary@garyguo.net>
Subject: [PATCH v3 2/2] rust: const_eval: add `#[const_only]` attribute
Date: Thu, 03 Dec 2026 18:24:43 +0000 [thread overview]
Message-ID: <20261203-cv-v3-2-bf8bfa2593cf@garyguo.net> (raw)
In-Reply-To: <20261203-cv-v3-0-bf8bfa2593cf@garyguo.net>
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
prev parent reply other threads:[~2026-12-03 18:25 UTC|newest]
Thread overview: 3+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-03 18:24 [PATCH v3 0/2] " 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 [this message]
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=20261203-cv-v3-2-bf8bfa2593cf@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=ecourtney@nvidia.com \
--cc=linux-kernel@vger.kernel.org \
--cc=lossin@kernel.org \
--cc=ojeda@kernel.org \
--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
all inboxes | Powered by JetHome®