[PATCH v2 1/2] rust: make unsafe_precondition_assert! const compatible
From: JX
Date: Tue Sep 08 2026 - 06:15:50 EST
The no-message form of unsafe_precondition_assert! routes the
condition through the formatting machinery. This prevents the macro from
being used in const unsafe functions.
Use a fixed diagnostic literal instead. This allows the no-message form
in const contexts without interpreting tokens from the condition as
format string syntax. Keep the custom-message form unchanged since it
intentionally supports runtime formatting.
Suggested-by: Miguel Ojeda <ojeda@xxxxxxxxxx>
Link: https://github.com/Rust-for-Linux/linux/issues/1232
Signed-off-by: JX <1239989762@xxxxxx>
---
rust/kernel/safety.rs | 11 ++++++++++-
1 file changed, 10 insertions(+), 1 deletion(-)
diff --git a/rust/kernel/safety.rs b/rust/kernel/safety.rs
index c1c6bd0fa2..f3c498c242 100644
--- a/rust/kernel/safety.rs
+++ b/rust/kernel/safety.rs
@@ -7,6 +7,15 @@
/// The check is enabled at runtime if debug assertions (`CONFIG_RUST_DEBUG_ASSERTIONS`)
/// are enabled. Otherwise, this macro is a no-op.
///
+/// The form without a custom message can be used in const contexts.
+///
+/// ```
+/// # use kernel::unsafe_precondition_assert;
+/// const fn check(value: usize) {
+/// unsafe_precondition_assert!({ value < 4 });
+/// }
+/// ```
+///
/// # Examples
///
/// ```no_run
@@ -40,7 +49,7 @@
#[macro_export]
macro_rules! unsafe_precondition_assert {
($cond:expr $(,)?) => {
- $crate::unsafe_precondition_assert!(@inner $cond, ::core::stringify!($cond))
+ ::core::debug_assert!($cond, "unsafe precondition violated")
};
($cond:expr, $($arg:tt)+) => {
--
2.54.0