Skip to contentSkip to conversation

rust: const_eval: add a mechanism to do const trait calls

PATCH In review Gary Guo 3 participants 11 messages Sep 3 – Sep 17

Subsystems (10)
lore
Share & tools
lore

Gary Guo

author reviewer
#0 lore raw

v2 cover rust: const_eval: add a mechanism to do const trait calls

Add a mechanism to perform const trait method calls, with the same type inference capabilities. This would only work for concrete types (not inside generic functions).

As an example, convert as_char_ptr_in_const_context, so instead of

kernel::str::as_char_ptr_in_const_context(c_str)

one may write

    const_call!(c_str.as_char_ptr())

instead.

---
Changes in v2:
- Split from cv!() alt series, and become a general infra instead.
- Link to v1: https://patch.msgid.link/[email protected]

---
Gary Guo (3):
rust: const_eval: add #[const_eval_only] attribute
rust: const_eval: allow const trait method invocation in some contexts
rust: str: convert as_char_ptr to work with const_call!

 rust/build_error.rs       |   7 +++
 rust/kernel/configfs.rs   |   2 +-
 rust/kernel/const_eval.rs | 115 ++++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/device_id.rs  |   4 ++
 rust/kernel/drm/device.rs |   4 +-
 rust/kernel/drm/ioctl.rs  |   4 +-
 rust/kernel/kunit.rs      |   6 +--
 rust/kernel/lib.rs        |   1 +
 rust/kernel/miscdevice.rs |   2 +-
 rust/kernel/net/phy.rs    |   2 +-
 rust/kernel/prelude.rs    |   1 +
 rust/kernel/str.rs        |  15 +++---
 rust/macros/const_eval.rs |  51 ++++++++++++++++++++
 rust/macros/lib.rs        |  39 ++++++++++++++++
 rust/macros/module.rs     |   4 +-
 15 files changed, 237 insertions(+), 20 deletions(-)

---
base-commit: 89c07d98716a13454ec3fd9f97689e812cc71bd4
change-id: 20260828-cv-acaf3400d16c

Best regards,

Signature · 1 line
Gary Guo <[email protected]>
author reviewer
#1 lore raw

PATCH v2 1/3 rust: const_eval: add `#[const_eval_only]` attribute

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.

Convert device_id.rs as an example.

---
 rust/build_error.rs       |  7 +++++++
 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        | 21 +++++++++++++++++++++
 6 files changed, 66 insertions(+)
rust/build_error.rs +7 -0
index fa24eeef9929..b7ef80596f1f 100644
@@ -29,3 +29,10 @@
 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.
+#[inline(never)]
+#[export_name = "rust_const_eval_called_at_runtime"]
+pub const fn assert_in_const_eval() {}
rust/kernel/const_eval.rs new file +9 -0
new file mode 100644
index 000000000000..f1b79d82549d
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Utilities for const evaluation.
+
+#[doc(inline)]
+pub use build_error::assert_in_const_eval;
+
+#[doc(inline)]
+pub use macros::const_eval_only;
rust/kernel/device_id.rs +4 -0
index c81fca5b4986..dad9cadaeb1b 100644
@@ -10,6 +10,8 @@
     mem::MaybeUninit, //
 };
 
+use crate::const_eval::const_eval_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_eval_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_eval_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 { core::mem::transmute_copy(&ids) };
rust/kernel/lib.rs +1 -0
index 4d5c96ddc49c..d9ed25e96ff3 100644
@@ -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;
rust/macros/const_eval.rs new file +24 -0
new file mode 100644
index 000000000000..0664888d3b38
@@ -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_eval_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()
+}
rust/macros/lib.rs +21 -0
index 24f96feaeb34..e47a8c35ccff 100644
@@ -15,6 +15,7 @@
 #![cfg_attr(not(CONFIG_RUSTC_HAS_SPAN_FILE), feature(proc_macro_span))]
 
 mod concat_idents;
+mod const_eval;
 mod export;
 mod fmt;
 mod for_lt;
@@ -338,6 +339,26 @@ 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 for runtime code.
+///
+/// # Examples
+///
+/// ```
+/// #[const_eval_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_eval_only(attr: TokenStream, input: TokenStream) -> TokenStream {
+    parse_macro_input!(attr as syn::parse::Nothing);
+    const_eval::const_eval_only(parse_macro_input!(input)).into()
+}
+
 /// Paste identifiers together.
 ///
 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
Signature · 1 line
2.54.0
#2 lore raw

Re: [PATCH v2 1/3] rust: const_eval: add `#[const_eval_only]` attribute

Quoted 22 lines · 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.

Convert device_id.rs as an example.

---
 rust/build_error.rs       |  7 +++++++
 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        | 21 +++++++++++++++++++++
 6 files changed, 66 insertions(+)
rust/build_error.rs +0 -0
index fa24eeef9929..b7ef80596f1f 100644

rust/build_error.rs line 38

Quoted 10 lines
rust/build_error.rs +7 -0
@@ -29,3 +29,10 @@
 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.
+#[inline(never)]
+#[export_name = "rust_const_eval_called_at_runtime"]
+pub const fn assert_in_const_eval() {}

IIUC if RUST_BUILD_ASSERT_ALLOW=y then this will not cause a build error anything built-in. I don't expect the call will ever fail to be eliminated by link time here, so isn't it better to not use the same mechanism affected by RUST_BUILD_ASSERT_ALLOW=y here? Guess you would need to make a new file for this.

Quoted 20 lines
rust/kernel/const_eval.rs new file +9 -0
new file mode 100644
index 000000000000..f1b79d82549d
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Utilities for const evaluation.
+
+#[doc(inline)]
+pub use build_error::assert_in_const_eval;
+
+#[doc(inline)]
+pub use macros::const_eval_only;
rust/kernel/device_id.rs +0 -0
index c81fca5b4986..dad9cadaeb1b 100644

rust/kernel/device_id.rs line 13

Quoted 4 lines
rust/kernel/device_id.rs +1 -0
@@ -10,6 +10,8 @@
     mem::MaybeUninit, //
 };
 
+use crate::const_eval::const_eval_only;

I am used to C++ so #[consteval] looks nicer to me (same with Miguel) but no idea if that means it's better. Just another datapoint.

Quoted 82 lines
rust/kernel/device_id.rs +3 -0
+
 /// 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_eval_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_eval_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 { core::mem::transmute_copy(&ids) };
rust/kernel/lib.rs +1 -0
index 4d5c96ddc49c..d9ed25e96ff3 100644
@@ -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;
rust/macros/const_eval.rs new file +24 -0
new file mode 100644
index 000000000000..0664888d3b38
@@ -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_eval_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()
+}
rust/macros/lib.rs +5 -0
index 24f96feaeb34..e47a8c35ccff 100644
@@ -15,6 +15,7 @@
 #![cfg_attr(not(CONFIG_RUSTC_HAS_SPAN_FILE), feature(proc_macro_span))]
 
 mod concat_idents;
+mod const_eval;
 mod export;
 mod fmt;
 mod for_lt;
@@ -338,6 +339,26 @@ 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 for runtime code.
+///

rust/macros/lib.rs pub fn concat_idents(input: TokenStream) -> TokenStream { · line 355

Quoted 10 lines
rust/macros/lib.rs +10 -0
+/// # Examples
+///
+/// ```
+/// #[const_eval_only]
+/// const fn call_for_const_eval_only() {
+///     // This code will be executed only during const eval!
+/// }
+///
+/// const _: () = call_for_const_eval_only();
+/// ```

Looks like make rusttest fails here?

rust/macros/lib.rs pub fn concat_idents(input: TokenStream) -> TokenStream { · line 364

Quoted 9 lines
rust/macros/lib.rs +6 -0
+#[proc_macro_attribute]
+pub fn const_eval_only(attr: TokenStream, input: TokenStream) -> TokenStream {
+    parse_macro_input!(attr as syn::parse::Nothing);
+    const_eval::const_eval_only(parse_macro_input!(input)).into()
+}
+
 /// Paste identifiers together.
 ///
 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a

I think this is a useful thing to add! Thanks~

author reviewer
#3 lore raw

Re: [PATCH v2 1/3] rust: const_eval: add `#[const_eval_only]` attribute

Quoted 31 lines · Eliot Courtney
Quoted 30 lines · 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.

Convert device_id.rs as an example.

---
 rust/build_error.rs       |  7 +++++++
 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        | 21 +++++++++++++++++++++
 6 files changed, 66 insertions(+)
rust/build_error.rs +5 -0
index fa24eeef9929..b7ef80596f1f 100644
@@ -29,3 +29,10 @@
 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.
+#[inline(never)]
Quoted 8 lines

rust/build_error.rs line 38

Quoted 2 lines
rust/build_error.rs +2 -0
+#[export_name = "rust_const_eval_called_at_runtime"]
+pub const fn assert_in_const_eval() {}

IIUC if RUST_BUILD_ASSERT_ALLOW=y then this will not cause a build error anything built-in. I don't expect the call will ever fail to be eliminated by link time here, so isn't it better to not use the same mechanism affected by RUST_BUILD_ASSERT_ALLOW=y here? Guess you would need to make a new file for this.

I could do that, but I also think it's not a big deal to also allow for RUST_BUILD_ASSERT_ALLOW=y builds just to simplify the build system.

As long as we have people building code with RUST_BUILD_ASSERT_ALLOW=n then the problematic use will be caught.

Best,
Gary

author reviewer
#4 lore raw

PATCH v2 2/3 rust: const_eval: allow const trait method invocation in some contexts

In reply to Gary Guo

Rust does not yet (as of 1.98) have stable const trait impl support; on 1.85 it does not have unstable support either. This leaves us having many free functions that do the exact same as trait methods.

Create a Const wrapper type as the central place to put const trait methods on as inherent methods, and a const_call! macro that dispatches to these inherent methods as opposed to trait methods.

const_call! would check that the signature actually matches, and provides some additional inference help. Once const trait impl is available, we can also easily just convert the macro without having to touching all users at once. Implement it as a proc macro, so it can accept the normal method call syntax.

---
 rust/kernel/const_eval.rs | 108 +++++++++++++++++++++++++++++++++++++++++++++-
 rust/kernel/prelude.rs    |   1 +
 rust/macros/const_eval.rs |  31 ++++++++++++-
 rust/macros/lib.rs        |   9 ++++
 4 files changed, 146 insertions(+), 3 deletions(-)
rust/kernel/const_eval.rs +107 -1
index f1b79d82549d..2a6ea3f7b693 100644
@@ -2,8 +2,114 @@
 
 //! Utilities for const evaluation.
 
+use core::{
+    ops::Deref, //
+};
+
 #[doc(inline)]
 pub use build_error::assert_in_const_eval;
 
 #[doc(inline)]
-pub use macros::const_eval_only;
+pub use macros::{
+    const_call,
+    const_eval_only, //
+};
+
+/// Constant wrapper type.
+///
+/// Rust does not yet (as of 1.98) have stable const trait impl support; on 1.85 it does not have
+/// unstable support either. Only inherent functions can be marked as const. There are a few const
+/// methods that we want to add on core types; and this mean that we cannot use extension trait on
+/// them.
+///
+/// This type serves as a middle layer. This type is local to the `kernel` crate, and thus we can
+/// define inherent methods on it. For core types, we will define it for `Const<Type>`. Other kernel
+/// crate types or even downstream types can also utilize it by defining inherent methods that
+/// *receive* `Const<Self>`.
+///
+/// Caller should use the `const_call!()` macro so it also checks that the type signature matches
+/// the trait.
+///
+/// # Examples
+///
+/// Say we want to define a extension method on u32. We can do
+/// ```no_run
+/// trait MyTrait {
+///     fn trait_method(self);
+/// }
+///
+/// impl MyTrait for u32 {
+///     fn trait_method(self) {
+///         /* impl */
+///     }
+/// }
+/// ```
+/// but we cannot mark it const.
+///
+/// Instead, we can do this
+/// ```ignore (doctest is outside kernel crate)
+/// trait MyTrait {
+///     fn trait_method(self);
+/// }
+///
+/// impl MyTrait for u32 {
+///     #[inline]
+///     fn trait_method(self) {
+///         // Forwarding impl
+///         Const(self).trait_method()
+///     }
+/// }
+///
+/// impl Const<u32> {
+///     pub const fn trait_method(self) {
+///         let Const(this) = self;
+///         /* impl */
+///     }
+/// }
+/// ```
+///
+/// For local or downstream types, implement it directly on the type with a different receiver:
+/// ```no_run
+/// # use kernel::const_eval::Const;
+/// trait MyTrait {
+///     fn trait_method(self);
+/// }
+///
+/// struct Foo;
+///
+/// impl MyTrait for Foo {
+///     #[inline]
+///     fn trait_method(self) {
+///         // Forwarding impl
+///         Const(self).trait_method()
+///     }
+/// }
+///
+/// impl Foo {
+///     pub const fn trait_method(self: Const<Self>) {
+///         let Const(this) = self;
+///         /* impl */
+///     }
+/// }
+/// ```
+///
+/// For caller of the method, one would simply replace `expr.method()` with `Const(expr).method()`;
+/// although the auto-ref coercion will be lost, so it a method expects `&self`, the caller would
+/// need to explicitly use the `Const(&expr).method()` syntax to call it.
+pub struct Const<T>(pub T);
+
+impl<T> Deref for Const<T> {
+    type Target = T;
+
+    #[inline]
+    fn deref(&self) -> &T {
+        &self.0
+    }
+}
+
+// Provide inference help only. Should never be code-generated.
+#[doc(hidden)]
+#[const_eval_only]
+pub const fn would_call<T, U, F: FnOnce(T) -> U>(_: T, _: F) -> U {
+    todo!()
+}
rust/kernel/prelude.rs +1 -0
index ca396f1f78a6..8f4c8cd2d8a2 100644
@@ -91,6 +91,7 @@
         const_assert,
         static_assert, //
     },
+    const_eval::const_call,
     current,
     dev_alert,
     dev_crit,
rust/macros/const_eval.rs +29 -2
index 0664888d3b38..10a4a93f905a 100644
@@ -1,9 +1,17 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use proc_macro2::TokenStream;
-use quote::ToTokens;
+use proc_macro2::{
+    Span,
+    TokenStream, //
+};
+use quote::{
+    format_ident,
+    quote,
+    ToTokens, //
+};
 use syn::{
     parse_quote,
+    ExprMethodCall,
     ItemFn, //
 };
 
@@ -22,3 +30,22 @@ pub(crate) fn const_eval_only(mut input: ItemFn) -> TokenStream {
 
     input.into_token_stream()
 }
+
+pub(crate) fn const_call(mut input: ExprMethodCall) -> TokenStream {
+    let expr = input.receiver;
+
+    let expr_ident = format_ident!("expr", span = Span::mixed_site());
+    input.receiver = parse_quote!(#expr_ident);
+
+    let would_call = quote!(#input);
+    input.receiver = parse_quote!(::kernel::const_eval::Const(#expr_ident));
+
+    quote!({
+        let #expr_ident = #expr;
+        if false {
+            ::kernel::const_eval::would_call(#expr_ident, |#expr_ident| #would_call)
+        } else {
+            #input
+        }
+    })
+}
rust/macros/lib.rs +9 -0
index e47a8c35ccff..262539cccf38 100644
@@ -339,6 +339,15 @@ pub fn concat_idents(input: TokenStream) -> TokenStream {
     concat_idents::concat_idents(parse_macro_input!(input)).into()
 }
 
+/// Call a trait method in const context.
+///
+/// This is a polyfill for Rust's const trait impl feature. Only work for specific methods that have
+/// dedicated const implementation.
+#[proc_macro]
+pub fn const_call(input: TokenStream) -> TokenStream {
+    const_eval::const_call(parse_macro_input!(input)).into()
+}
+
 /// Mark a function as usable from const evaluation only.
 ///
 /// Build will fail if the function is used for runtime code.
Signature · 1 line
2.54.0
author reviewer
#5 lore raw

PATCH v2 3/3 rust: str: convert `as_char_ptr` to work with `const_call!`

In reply to Gary Guo

This allows const_call!(foo.as_char_ptr()) to be used instead of kernel::str::as_char_ptr_in_const_context.

Const(foo).as_char_ptr() is used directly in macros to avoid having to import CStrExt.

---
 rust/kernel/configfs.rs   |  2 +-
 rust/kernel/drm/device.rs |  4 ++--
 rust/kernel/drm/ioctl.rs  |  4 ++--
 rust/kernel/kunit.rs      |  6 +++---
 rust/kernel/miscdevice.rs |  2 +-
 rust/kernel/net/phy.rs    |  2 +-
 rust/kernel/str.rs        | 15 +++++++--------
 rust/macros/lib.rs        |  9 +++++++++
 rust/macros/module.rs     |  4 ++--
 9 files changed, 28 insertions(+), 20 deletions(-)
rust/kernel/configfs.rs +1 -1
index cd082b83e9e7..ece6cb31609f 100644
@@ -612,7 +612,7 @@ impl<const ID: u64, O, Data> Attribute<ID, O, Data>
     pub const fn new(name: &'static CStr) -> Self {
         Self {
             attribute: Opaque::new(bindings::configfs_attribute {
-                ca_name: crate::str::as_char_ptr_in_const_context(name),
+                ca_name: const_call!(name.as_char_ptr()),
                 ca_owner: core::ptr::null_mut(),
                 ca_mode: 0o660,
                 show: Some(Self::show),
rust/kernel/drm/device.rs +2 -2
index 6b88ade28e24..536a0e958c8b 100644
@@ -186,8 +186,8 @@ const fn compute_features() -> u32 {
         major: T::INFO.major,
         minor: T::INFO.minor,
         patchlevel: T::INFO.patchlevel,
-        name: crate::str::as_char_ptr_in_const_context(T::INFO.name).cast_mut(),
-        desc: crate::str::as_char_ptr_in_const_context(T::INFO.desc).cast_mut(),
+        name: const_call!(T::INFO.name.as_char_ptr()).cast_mut(),
+        desc: const_call!(T::INFO.desc.as_char_ptr()).cast_mut(),
 
         driver_features: Self::compute_features(),
         ioctls: T::IOCTLS.as_ptr(),
rust/kernel/drm/ioctl.rs +2 -2
index 64af9eacc306..5bba960504d6 100644
@@ -206,9 +206,9 @@ macro_rules! declare_drm_ioctls {
                         Some($cmd)
                     },
                     flags: $flags,
-                    name: $crate::str::as_char_ptr_in_const_context(
+                    name: $crate::const_eval::Const(
                         $crate::c_str!(::core::stringify!($cmd)),
-                    ),
+                    ).as_char_ptr(),
                 }
             ),*];
             ioctls
rust/kernel/kunit.rs +3 -3
index 91eaff8c186a..034df521b195 100644
@@ -107,12 +107,12 @@ unsafe impl Sync for Location {}
             unsafe impl Sync for UnaryAssert {}
 
             static LOCATION: Location = Location($crate::bindings::kunit_loc {
-                file: $crate::str::as_char_ptr_in_const_context(FILE),
+                file: $crate::const_eval::Const(FILE).as_char_ptr(),
                 line: LINE,
             });
             static ASSERTION: UnaryAssert = UnaryAssert($crate::bindings::kunit_unary_assert {
                 assert: $crate::bindings::kunit_assert {},
-                condition: $crate::str::as_char_ptr_in_const_context(CONDITION),
+                condition: $crate::const_eval::Const(CONDITION).as_char_ptr(),
                 expected_true: true,
             });
 
@@ -204,7 +204,7 @@ pub const fn kunit_case(
 ) -> kernel::bindings::kunit_case {
     kernel::bindings::kunit_case {
         run_case: Some(run_case),
-        name: kernel::str::as_char_ptr_in_const_context(name),
+        name: const_call!(name.as_char_ptr()),
         attr: kernel::bindings::kunit_attributes {
             speed: kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL,
         },
rust/kernel/miscdevice.rs +1 -1
index 8d4b719bd83f..02e115ec045d 100644
@@ -46,7 +46,7 @@ impl MiscDeviceOptions {
     pub const fn into_raw<T: MiscDevice>(self) -> bindings::miscdevice {
         let mut result: bindings::miscdevice = pin_init::zeroed();
         result.minor = bindings::MISC_DYNAMIC_MINOR as ffi::c_int;
-        result.name = crate::str::as_char_ptr_in_const_context(self.name);
+        result.name = const_call!(self.name.as_char_ptr());
         result.fops = MiscdeviceVTable::<T>::build();
         result
     }
rust/kernel/net/phy.rs +1 -1
index 956cda573ddb..28047fc3a876 100644
@@ -494,7 +494,7 @@ unsafe impl Sync for DriverVTable {}
 pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
     // INVARIANT: All the fields of `struct phy_driver` are initialized properly.
     DriverVTable(Opaque::new(bindings::phy_driver {
-        name: crate::str::as_char_ptr_in_const_context(T::NAME).cast_mut(),
+        name: const_call!(T::NAME.as_char_ptr()).cast_mut(),
         flags: T::FLAGS,
         phy_id: T::PHY_DEVICE_ID.id(),
         phy_id_mask: T::PHY_DEVICE_ID.mask_as_int(),
rust/kernel/str.rs +7 -8
index b3caa9a1c898..93ae32b42e18 100644
@@ -197,14 +197,13 @@ macro_rules! b_str {
     }};
 }
 
-/// Returns a C pointer to the string.
-// It is a free function rather than a method on an extension trait because:
-//
-// - error[E0379]: functions in trait impls cannot be declared const
-#[inline]
-#[expect(clippy::disallowed_methods, reason = "internal implementation")]
-pub const fn as_char_ptr_in_const_context(c_str: &CStr) -> *const c_char {
-    c_str.as_ptr().cast()
+impl crate::const_eval::Const<&CStr> {
+    /// Returns a C pointer to the string.
+    #[inline]
+    #[expect(clippy::disallowed_methods, reason = "internal implementation")]
+    pub const fn as_char_ptr(self) -> *const c_char {
+        self.0.as_ptr().cast()
+    }
 }
 
 mod private {
rust/macros/lib.rs +9 -0
index 262539cccf38..f5d8d0706e46 100644
@@ -343,6 +343,15 @@ pub fn concat_idents(input: TokenStream) -> TokenStream {
 ///
 /// This is a polyfill for Rust's const trait impl feature. Only work for specific methods that have
 /// dedicated const implementation.
+///
+/// # Examples
+///
+/// ```
+/// const fn use_cstr(c: &CStr) {
+///     // This is an extension trait method that is not otherwise callable in const context.
+///     let char_ptr = const_call!((c).as_char_ptr());
+/// }
+/// ```
 #[proc_macro]
 pub fn const_call(input: TokenStream) -> TokenStream {
     const_eval::const_call(parse_macro_input!(input)).into()
rust/macros/module.rs +2 -2
index bc7027f8dbb2..b2c1f118c7e1 100644
@@ -149,13 +149,13 @@ fn emit_params(&mut self, info: &ModuleInfo) {
                         ::kernel::module_param::KernelParam =
                         ::kernel::module_param::KernelParam::new(
                             ::kernel::bindings::kernel_param {
-                                name: kernel::str::as_char_ptr_in_const_context(
+                                name: ::kernel::const_eval::Const(
                                     if ::core::cfg!(MODULE) {
                                         #param_name_cstr
                                     } else {
                                         #param_name_cstr_with_module
                                     }
-                                ),
+                                ).as_char_ptr(),
                                 // SAFETY: `__this_module` is constructed by the kernel at load
                                 // time and will not be freed until the module is unloaded.
                                 #[cfg(MODULE)]
Signature · 1 line
2.54.0
#6 lore raw
In reply to Gary Guo
Quoted 9 lines · Gary Guo

Add a mechanism to perform const trait method calls, with the same type inference capabilities. This would only work for concrete types (not inside generic functions).

As an example, convert as_char_ptr_in_const_context, so instead of

kernel::str::as_char_ptr_in_const_context(c_str)

Quoted 7 lines

one may write

    const_call!(c_str.as_char_ptr())

instead.

Thanks for resending this!

So I definitely like having #[const_eval_only], because we do want to limit those calls sometimes and it is nice to have C++'s equivalent to consteval (perhaps this could be called just #[consteval] to match?); i.e. what we talked about in the call.

On Const and const_call!, i.e. the other two patches: I am not sure if we care that much to introduce a macro for it, but it doesn't look bad either. I guess perhaps it helps to have a consistent way to do it and to easily remove it later when the actual feature lands in Rust. I would like to hear some thoughts on it from others.

Cheers,
Miguel

author reviewer
#7 lore raw
Quoted 25 lines · Miguel Ojeda
Quoted 9 lines · Gary Guo

Add a mechanism to perform const trait method calls, with the same type inference capabilities. This would only work for concrete types (not inside generic functions).

As an example, convert as_char_ptr_in_const_context, so instead of

kernel::str::as_char_ptr_in_const_context(c_str)

Quoted 7 lines

one may write

    const_call!(c_str.as_char_ptr())

instead.

Thanks for resending this!

So I definitely like having #[const_eval_only], because we do want to limit those calls sometimes and it is nice to have C++'s equivalent to consteval (perhaps this could be called just #[consteval] to match?); i.e. what we talked about in the call.

Quoted 5 lines

On Const and const_call!, i.e. the other two patches: I am not sure if we care that much to introduce a macro for it, but it doesn't look bad either. I guess perhaps it helps to have a consistent way to do it and to easily remove it later when the actual feature lands in Rust. I would like to hear some thoughts on it from others.

I think it's good to have such macro compared to our current approach; it can be made into a identity macro once we have const trait impl.

FWIW, I even considered an extra macro that allow you to write

#[const_trait_impl] // #[const_trait_impl(foreign)] for core types impl MyTrait for MyType {}

and generate the impl Const part too (and also add a line to the documentation that the method is const-callable with const_call!()).

Best,
Gary

#8 lore raw
Quoted 37 lines · Gary Guo
Quoted 25 lines · Miguel Ojeda
Quoted 9 lines · Gary Guo

Add a mechanism to perform const trait method calls, with the same type inference capabilities. This would only work for concrete types (not inside generic functions).

As an example, convert as_char_ptr_in_const_context, so instead of

kernel::str::as_char_ptr_in_const_context(c_str)

Quoted 7 lines

one may write

    const_call!(c_str.as_char_ptr())

instead.

Thanks for resending this!

So I definitely like having #[const_eval_only], because we do want to limit those calls sometimes and it is nice to have C++'s equivalent to consteval (perhaps this could be called just #[consteval] to match?); i.e. what we talked about in the call.

Quoted 5 lines

On Const and const_call!, i.e. the other two patches: I am not sure if we care that much to introduce a macro for it, but it doesn't look bad either. I guess perhaps it helps to have a consistent way to do it and to easily remove it later when the actual feature lands in Rust. I would like to hear some thoughts on it from others.

I think it's good to have such macro compared to our current approach; it can be made into a identity macro once we have const trait impl.

FWIW, I even considered an extra macro that allow you to write

Quoted 8 lines

#[const_trait_impl] // #[const_trait_impl(foreign)] for core types impl MyTrait for MyType {}

and generate the impl Const part too (and also add a line to the documentation that the method is const-callable with const_call!()).

Best,
Gary

I agree with the consteval macro, that sounds very nice.

On the const_call! I have similar thoughts to Miguel. I reckon if we have a bunch of prospective users of this right now, and some thoughts on what would use this in the future then it's good. If it's just one use case right now, then not so sure.

author reviewer
#9 lore raw
Quoted 18 lines · Eliot Courtney
Quoted 17 lines · Gary Guo
Quoted 16 lines · Miguel Ojeda
Quoted 15 lines · Gary Guo

Add a mechanism to perform const trait method calls, with the same type inference capabilities. This would only work for concrete types (not inside generic functions).

As an example, convert as_char_ptr_in_const_context, so instead of

kernel::str::as_char_ptr_in_const_context(c_str)

one may write

    const_call!(c_str.as_char_ptr())

instead.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 1 line

Thanks for resending this!

So I definitely like having #[const_eval_only], because we do want to limit those calls sometimes and it is nice to have C++'s equivalent to consteval (perhaps this could be called just #[consteval] to match?); i.e. what we talked about in the call.

I'm okay with either. I put in _only because I think it makes it very clear that this is not just const-evalutable (that's provided by const) and is *always* const evaled.

Quoted 22 lines
Quoted 13 lines
Quoted 6 lines

On Const and const_call!, i.e. the other two patches: I am not sure if we care that much to introduce a macro for it, but it doesn't look bad either. I guess perhaps it helps to have a consistent way to do it and to easily remove it later when the actual feature lands in Rust. I would like to hear some thoughts on it from others.

I think it's good to have such macro compared to our current approach; it can be made into a identity macro once we have const trait impl.

FWIW, I even considered an extra macro that allow you to write

Quoted 8 lines

#[const_trait_impl] // #[const_trait_impl(foreign)] for core types impl MyTrait for MyType {}

and generate the impl Const part too (and also add a line to the documentation that the method is const-callable with const_call!()).

Best,
Gary

Quoted 6 lines

I agree with the consteval macro, that sounds very nice.

On the const_call! I have similar thoughts to Miguel. I reckon if we have a bunch of prospective users of this right now, and some thoughts on what would use this in the future then it's good. If it's just one use case right now, then not so sure.

Some other candidates include Alignable (we currently have a "const_align_up") and maybe IntoSafeCast.

Best,
Gary

#10 lore raw
Quoted 61 lines · Gary Guo
Quoted 18 lines · Eliot Courtney
Quoted 17 lines · Gary Guo
Quoted 16 lines · Miguel Ojeda
Quoted 15 lines · Gary Guo

Add a mechanism to perform const trait method calls, with the same type inference capabilities. This would only work for concrete types (not inside generic functions).

As an example, convert as_char_ptr_in_const_context, so instead of

kernel::str::as_char_ptr_in_const_context(c_str)

one may write

    const_call!(c_str.as_char_ptr())

instead.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 1 line

Thanks for resending this!

So I definitely like having #[const_eval_only], because we do want to limit those calls sometimes and it is nice to have C++'s equivalent to consteval (perhaps this could be called just #[consteval] to match?); i.e. what we talked about in the call.

I'm okay with either. I put in _only because I think it makes it very clear that this is not just const-evalutable (that's provided by const) and is *always* const evaled.

Quoted 22 lines
Quoted 13 lines
Quoted 6 lines

On Const and const_call!, i.e. the other two patches: I am not sure if we care that much to introduce a macro for it, but it doesn't look bad either. I guess perhaps it helps to have a consistent way to do it and to easily remove it later when the actual feature lands in Rust. I would like to hear some thoughts on it from others.

I think it's good to have such macro compared to our current approach; it can be made into a identity macro once we have const trait impl.

FWIW, I even considered an extra macro that allow you to write

Quoted 8 lines

#[const_trait_impl] // #[const_trait_impl(foreign)] for core types impl MyTrait for MyType {}

and generate the impl Const part too (and also add a line to the documentation that the method is const-callable with const_call!()).

Best,
Gary

Quoted 6 lines

I agree with the consteval macro, that sounds very nice.

On the const_call! I have similar thoughts to Miguel. I reckon if we have a bunch of prospective users of this right now, and some thoughts on what would use this in the future then it's good. If it's just one use case right now, then not so sure.

Quoted 5 lines

Some other candidates include Alignable (we currently have a "const_align_up") and maybe IntoSafeCast.

Best,
Gary

I'm definitely not opposed to a const trait polyfill, it's pretty cool actually IMO. I also do think there is a bit of survivorship bias on the argument (which I made) that there are not many users. And it can be removed once const traits become available in MSRV. I am keen to hear from others on this.