Skip to contentSkip to conversation

rust: static_assert: add optional message

PATCH Benno Lossin 2 participants 2 messages Mar 24, 2025 Rust

lore
Share & tools
lore
#0 lore raw
Quoted 29 lines · Altan Ozlu

Add optional panic message for static_assert! macro.

It doesn't support argument formatting, due to const_format_args being experimental. It will fail to compile if a message with argument is given.

---
 rust/kernel/static_assert.rs | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
rust/kernel/static_assert.rs +3 -0
index 3115ee0ba8e9..27771dc2988a 100644
@@ -6,6 +6,9 @@
 ///
 /// Similar to C11 [`_Static_assert`] and C++11 [`static_assert`].
 ///
+/// It has optional argument for custom panic messages.
+/// Panic message doesn't support formatting.
+///
 /// The feature may be added to Rust in the future: see [RFC 2790].
 ///
 /// [`_Static_assert`]: https://en.cppreference.com/w/c/language/_Static_assert
@@ -24,11 +27,11 @@
 /// const fn f(x: i32) -> i32 {

rust/kernel/static_assert.rs line 34

Quoted 10 lines
rust/kernel/static_assert.rs +2 -3
 ///     x + 2
 /// }
-/// static_assert!(f(40) == 42);
+/// static_assert!(f(40) == 42, "f(x) must add 2 to the given input.");
 /// ```
 #[macro_export]
 macro_rules! static_assert {
-    ($condition:expr) => {
-        const _: () = core::assert!($condition);
+    ($condition:expr $(,$arg:tt)?) => {

Shouldn't $arg be a literal fragment?

---
Cheers,
Benno

Quoted 5 lines
rust/kernel/static_assert.rs +1 -0
+        const _: () = core::assert!($condition $(,$arg)?);
     };
 }

base-commit: a0b539ad369fe434fe488faf92d4ae770a27a90f

#1 lore raw
Quoted 7 lines

Review

Quoted 5 lines

#[macro_export]
macro_rules! static_assert {

(quoted diff) +1 -2
-    ($condition:expr) => {
-        const _: () = core::assert!($condition);
+    ($condition:expr $(,$arg:tt)?) => {

Shouldn't $arg be a literal fragment?

You are right it's better to keep it as literal, changed it in v2.

Signature · 2 lines
Kind regards,
Altan