rust: const_eval: add `#[const_only]` attribute
Subsystems (3)
Gary Guo
reviewerv3 cover rust: const_eval: add `#[const_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; 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.
---
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/[email protected]
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 (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,
Signature · 1 line
Gary Guo <[email protected]>
Gary Guo
reviewerPATCH v3 1/2 rust: generalize `build_error` to `const_eval_select`
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.
--- 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(-)
rust/Makefile +43 -21
@@ -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)
rust/build_error.rs deleted +0 -31
@@ -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: &'staticstr ) -> ! { -panic! ("{}" , msg); -}
rust/const_eval_select.rs new file +32 -0
@@ -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: &'staticstr ) -> ! { +panic! ("{}" , msg); +}
rust/exports.c +1 -5
@@ -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
rust/kernel/build_assert.rs +1 -1
@@ -70,7 +70,7 @@ };#[doc(hidden)] -pub use build_error::build_erroras build_error_fn; +pub use const_eval_select::build_erroras build_error_fn;/// Static assert (i.e. compile-time assert). ///
scripts/generate_rust_analyzer.py +4 -4
@@ -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"
Signature · 1 line
2.56.1
Gary Guo
reviewerPATCH v3 2/2 rust: const_eval: add `#[const_only]` attribute
In reply to Gary GuoWe 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.
--- 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(+)
rust/const_eval_select.rs +12 -0
@@ -30,3 +30,15 @@pub const fn build_error (msg: &'staticstr ) -> ! {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" ); +}
rust/kernel/const_eval.rs new file +9 -0
@@ -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;
rust/kernel/device_id.rs +4 -0
@@ -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 , &'staticU );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) };
rust/kernel/lib.rs +1 -0
@@ -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
@@ -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 () +}
rust/macros/lib.rs +23 -0
@@ -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! (attras 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
Signature · 1 line
2.56.1