Skip to contentSkip to conversation

rust: doctest: unify with other kunit tests

PATCH Applied Gary Guo 3 participants 6 messages Sep 2 – Oct 3

Subsystems (4)
lore
Share & tools
lore

Gary Guo

author reviewer
#0 lore raw

v2 cover rust: doctest: unify with other kunit tests

Currently in Rust, kunit tests are handled with kunit_tests, while the doctests generate a lot extern "C" functions and invoke them through a generated C wrapper.

This is currently needed because of the special treatment of file name and line numbers from doctests. Convert them to override file!() and line!() macro instead, and use them inside kunit_assert!.

With this it is possible to just generate #[kunit_tests] and #[test] for doctests.

David mentioned in [1] that this should route via the Rust tree.

---
Changes in v2:
- Rebased on v7.3-rc1
- Picked up tags
- Link to v1: https://patch.msgid.link/[email protected]

---
Gary Guo (3):
rust: kunit: use file!() inside kunit_assert!
rust: kunit: use line!() inside kunit_assert!
rust: doctest: generate Rust kunit test suites

 Documentation/rust/general-information.rst |  4 +-
 init/Kconfig                               |  3 --
 rust/Makefile                              |  4 +-
 rust/kernel/kunit.rs                       | 11 +++--
 rust/kernel/str.rs                         |  2 +-
 rust/macros/helpers.rs                     | 16 -------
 rust/macros/kunit.rs                       |  5 +-
 rust/macros/lib.rs                         |  5 --
 scripts/rustdoc_test_gen.rs                | 73 ++++++++----------------------
 9 files changed, 30 insertions(+), 93 deletions(-)

---
base-commit: cee9395acd8043be0644b25c34bfa86623f2b935
change-id: 20260616-kunit-348f2c029b1e

Best regards,

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

PATCH v2 1/3 rust: kunit: use `file!()` inside `kunit_assert!`

This parameter is needed currently because doctests want to override the file. Simplify it by changing it to use file!(). Have doctests override file!() macro to achieve the current behavior.

This allows us to remove the file helper and associated Kconfig options.

---
 Documentation/rust/general-information.rst |  4 ++--
 init/Kconfig                               |  3 ---
 rust/kernel/kunit.rs                       |  9 +++++----
 rust/macros/helpers.rs                     | 16 ----------------
 rust/macros/kunit.rs                       |  5 ++---
 rust/macros/lib.rs                         |  5 -----
 scripts/rustdoc_test_gen.rs                | 10 ++++++++--
 7 files changed, 17 insertions(+), 35 deletions(-)
Documentation/rust/general-information.rst +2 -2
index 09234bed272c..20e3178ebfd4 100644
@@ -157,5 +157,5 @@ numerical comparisons, one may define a new Kconfig symbol:
 
 .. code-block:: kconfig
 
-	config RUSTC_HAS_SPAN_FILE
-		def_bool RUSTC_VERSION >= 108800
+	config RUSTC_HAS_FILE_AS_C_STR
+		def_bool RUSTC_VERSION >= 109100
init/Kconfig +0 -3
index 8583d9f06c52..24b019104d88 100644
@@ -178,9 +178,6 @@ config LD_CAN_USE_KEEP_IN_OVERLAY
 	# https://github.com/llvm/llvm-project/pull/130661
 	def_bool LD_IS_BFD || LLD_VERSION >= 210000
 
-config RUSTC_HAS_SPAN_FILE
-	def_bool RUSTC_VERSION >= 108800
-
 config RUSTC_HAS_UNNECESSARY_TRANSMUTES
 	def_bool RUSTC_VERSION >= 108800
 
rust/kernel/kunit.rs +5 -4
index 91eaff8c186a..12084873b51e 100644
@@ -58,14 +58,15 @@ pub fn info(args: fmt::Arguments<'_>) {
 #[doc(hidden)]
 #[macro_export]
 macro_rules! kunit_assert {
-    ($name:literal, $file:literal, $diff:expr, $condition:expr $(,)?) => {
+    ($name:literal, $diff:expr, $condition:expr $(,)?) => {
         'out: {
             // Do nothing if the condition is `true`.
             if $condition {
                 break 'out;
             }
 
-            static FILE: &'static $crate::str::CStr = $file;
+            // Use `file!()` instead of `::core::file!()` here so it can be overridden.
+            static FILE: &'static $crate::str::CStr = $crate::c_str!(file!());
             static LINE: i32 = ::core::line!() as i32 - $diff;
             static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition));
 
@@ -164,10 +165,10 @@ unsafe impl Sync for UnaryAssert {}
 #[doc(hidden)]
 #[macro_export]
 macro_rules! kunit_assert_eq {
-    ($name:literal, $file:literal, $diff:expr, $left:expr, $right:expr $(,)?) => {{
+    ($name:literal, $diff:expr, $left:expr, $right:expr $(,)?) => {{
         // For the moment, we just forward to the expression assert because, for binary asserts,
         // KUnit supports only a few types (e.g. integers).
-        $crate::kunit_assert!($name, $file, $diff, $left == $right);
+        $crate::kunit_assert!($name, $diff, $left == $right);
     }};
 }
 
rust/macros/helpers.rs +0 -16
index d18fbf4daa0a..8cc9a20f470e 100644
@@ -38,22 +38,6 @@ pub(crate) fn value(&self) -> String {
     }
 }
 
-pub(crate) fn file() -> String {
-    #[cfg(not(CONFIG_RUSTC_HAS_SPAN_FILE))]
-    {
-        proc_macro::Span::call_site()
-            .source_file()
-            .path()
-            .to_string_lossy()
-            .into_owned()
-    }
-
-    #[cfg(CONFIG_RUSTC_HAS_SPAN_FILE)]
-    {
-        proc_macro::Span::call_site().file()
-    }
-}
-
 /// Obtain all `#[cfg]` attributes.
 pub(crate) fn gather_cfg_attrs(attr: &[Attribute]) -> impl Iterator<Item = &Attribute> + '_ {
     attr.iter().filter(|a| a.path().is_ident("cfg"))
rust/macros/kunit.rs +2 -3
index ae20ed6768f1..936eff014870 100644
@@ -109,12 +109,11 @@ pub(crate) fn kunit_tests(test_suite: Ident, mut module: ItemMod) -> Result<Toke
         // Before the test, override usual `assert!` and `assert_eq!` macros with ones that call
         // KUnit instead.
         let test_str = test.to_string();
-        let path = CString::new(crate::helpers::file()).expect("file path cannot contain NUL");
         processed_items.push(parse_quote! {
             #[allow(unused)]
             macro_rules! assert {
                 ($cond:expr $(,)?) => {{
-                    kernel::kunit_assert!(#test_str, #path, 0, $cond);
+                    kernel::kunit_assert!(#test_str, 0, $cond);
                 }}
             }
         });
@@ -122,7 +121,7 @@ macro_rules! assert {
             #[allow(unused)]
             macro_rules! assert_eq {
                 ($left:expr, $right:expr $(,)?) => {{
-                    kernel::kunit_assert_eq!(#test_str, #path, 0, $left, $right);
+                    kernel::kunit_assert_eq!(#test_str, 0, $left, $right);
                 }}
             }
         });
rust/macros/lib.rs +0 -5
index 24f96feaeb34..6916195f0051 100644
@@ -8,11 +8,6 @@
 
 // Stable since Rust 1.87.0.
 #![feature(extract_if)]
-//
-// Stable since Rust 1.88.0 under a different name, `proc_macro_span_file`,
-// which was added in Rust 1.88.0. This is why `cfg_attr` is used here, i.e.
-// to avoid depending on the full `proc_macro_span` on Rust >= 1.88.0.
-#![cfg_attr(not(CONFIG_RUSTC_HAS_SPAN_FILE), feature(proc_macro_span))]
 
 mod concat_idents;
 mod export;
scripts/rustdoc_test_gen.rs +8 -2
index d087c0d9fcb3..bb57745ec339 100644
@@ -176,12 +176,18 @@ fn main() {
             r#"/// Generated `{name}` KUnit test case from a Rust documentation test.
 #[no_mangle]
 pub extern "C" fn {kunit_name}(__kunit_test: *mut ::kernel::bindings::kunit) {{
+    /// Overrides the usual [`file!`] macro with one that expands to the real path.
+    #[allow(unused)]
+    macro_rules! file {{
+        () => {{ "{real_path}" }}
+    }}
+
     /// Overrides the usual [`assert!`] macro with one that calls KUnit instead.
     #[allow(unused)]
     macro_rules! assert {{
         ($cond:expr $(,)?) => {{{{
             ::kernel::kunit_assert!(
-                "{kunit_name}", c"{real_path}", __DOCTEST_ANCHOR - {line}, $cond
+                "{kunit_name}", __DOCTEST_ANCHOR - {line}, $cond
             );
         }}}}
     }}
@@ -191,7 +197,7 @@ macro_rules! assert {{
     macro_rules! assert_eq {{
         ($left:expr, $right:expr $(,)?) => {{{{
             ::kernel::kunit_assert_eq!(
-                "{kunit_name}", c"{real_path}", __DOCTEST_ANCHOR - {line}, $left, $right
+                "{kunit_name}", __DOCTEST_ANCHOR - {line}, $left, $right
             );
         }}}}
     }}
Signature · 1 line
2.54.0
author reviewer
#2 lore raw

PATCH v2 2/3 rust: kunit: use `line!()` inside `kunit_assert!`

In reply to Gary Guo

The diff parameter is needed currently because doctests want to override the line number. Simplify it by changing it to use line!(). Have doctests override line!() macro to achieve the current behavior.

A few current doctests (or their invoked macros) require line!() to expand to literal; they're updated to use ::core::line!() instead.

---
 rust/kernel/kunit.rs        |  8 ++++----
 rust/kernel/str.rs          |  2 +-
 rust/macros/kunit.rs        |  4 ++--
 scripts/rustdoc_test_gen.rs | 16 ++++++++++++----
 4 files changed, 19 insertions(+), 11 deletions(-)
rust/kernel/kunit.rs +4 -4
index 12084873b51e..27b109923407 100644
@@ -58,7 +58,7 @@ pub fn info(args: fmt::Arguments<'_>) {
 #[doc(hidden)]
 #[macro_export]
 macro_rules! kunit_assert {
-    ($name:literal, $diff:expr, $condition:expr $(,)?) => {
+    ($name:literal, $condition:expr $(,)?) => {
         'out: {
             // Do nothing if the condition is `true`.
             if $condition {
@@ -67,7 +67,7 @@ macro_rules! kunit_assert {
 
             // Use `file!()` instead of `::core::file!()` here so it can be overridden.
             static FILE: &'static $crate::str::CStr = $crate::c_str!(file!());
-            static LINE: i32 = ::core::line!() as i32 - $diff;
+            static LINE: i32 = line!() as i32;
             static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition));
 
             // SAFETY: FFI call without safety requirements.
@@ -165,10 +165,10 @@ unsafe impl Sync for UnaryAssert {}
 #[doc(hidden)]
 #[macro_export]
 macro_rules! kunit_assert_eq {
-    ($name:literal, $diff:expr, $left:expr, $right:expr $(,)?) => {{
+    ($name:literal, $left:expr, $right:expr $(,)?) => {{
         // For the moment, we just forward to the expression assert because, for binary asserts,
         // KUnit supports only a few types (e.g. integers).
-        $crate::kunit_assert!($name, $diff, $left == $right);
+        $crate::kunit_assert!($name, $left == $right);
     }};
 }
 
rust/kernel/str.rs +1 -1
index b3caa9a1c898..644b4279a116 100644
@@ -411,7 +411,7 @@ fn as_ref(&self) -> &BStr {
 /// const BAD: &CStr = c_str!("literal");
 ///
 /// // `c_str!` is still needed for static non-literal C strings.
-/// const GOOD: &CStr = c_str!(concat!(file!(), ":", line!(), ": My CStr!"));
+/// const GOOD: &CStr = c_str!(concat!(file!(), ":", ::core::line!(), ": My CStr!"));
 /// ```
 #[macro_export]
 macro_rules! c_str {
rust/macros/kunit.rs +2 -2
index 936eff014870..e9152b9d51f9 100644
@@ -113,7 +113,7 @@ pub(crate) fn kunit_tests(test_suite: Ident, mut module: ItemMod) -> Result<Toke
             #[allow(unused)]
             macro_rules! assert {
                 ($cond:expr $(,)?) => {{
-                    kernel::kunit_assert!(#test_str, 0, $cond);
+                    kernel::kunit_assert!(#test_str, $cond);
                 }}
             }
         });
@@ -121,7 +121,7 @@ macro_rules! assert {
             #[allow(unused)]
             macro_rules! assert_eq {
                 ($left:expr, $right:expr $(,)?) => {{
-                    kernel::kunit_assert_eq!(#test_str, 0, $left, $right);
+                    kernel::kunit_assert_eq!(#test_str, $left, $right);
                 }}
             }
         });
scripts/rustdoc_test_gen.rs +12 -4
index bb57745ec339..bb870f83dde2 100644
@@ -176,18 +176,26 @@ fn main() {
             r#"/// Generated `{name}` KUnit test case from a Rust documentation test.
 #[no_mangle]
 pub extern "C" fn {kunit_name}(__kunit_test: *mut ::kernel::bindings::kunit) {{
-    /// Overrides the usual [`file!`] macro with one that expands to the real path.
+    // Overrides the usual [`file!`] macro with one that expands to the real path.
     #[allow(unused)]
     macro_rules! file {{
         () => {{ "{real_path}" }}
     }}
 
+    // Overrides the usual [`line!`] macro with one that expands to the real line number.
+    #[allow(unused)]
+    macro_rules! line {{
+        // NOTE: This does not expand to a literal, but a constant expression.
+        // Therefore code that depends on `line!()` being overrideable needs special adjustment.
+        () => {{ const {{ ::core::line!() - __DOCTEST_ANCHOR + {line} }} }}
+    }}
+
     /// Overrides the usual [`assert!`] macro with one that calls KUnit instead.
     #[allow(unused)]
     macro_rules! assert {{
         ($cond:expr $(,)?) => {{{{
             ::kernel::kunit_assert!(
-                "{kunit_name}", __DOCTEST_ANCHOR - {line}, $cond
+                "{kunit_name}", $cond
             );
         }}}}
     }}
@@ -197,7 +205,7 @@ macro_rules! assert {{
     macro_rules! assert_eq {{
         ($left:expr, $right:expr $(,)?) => {{{{
             ::kernel::kunit_assert_eq!(
-                "{kunit_name}", __DOCTEST_ANCHOR - {line}, $left, $right
+                "{kunit_name}", $left, $right
             );
         }}}}
     }}
@@ -219,7 +227,7 @@ macro_rules! assert_eq {{
 
     /// The anchor where the test code body starts.
     #[allow(unused)]
-    static __DOCTEST_ANCHOR: i32 = ::core::line!() as i32 + {body_offset} + 2;
+    static __DOCTEST_ANCHOR: u32 = ::core::line!() + {body_offset} + 2;
     {{
         #![allow(unreachable_pub, clippy::disallowed_names)]
         {body}
Signature · 1 line
2.54.0
author reviewer
#3 lore raw

PATCH v2 3/3 rust: doctest: generate Rust kunit test suites

In reply to Gary Guo

For doctest, instead of generating C FFI functions, generate a Rust test suite with #[kunit_tests] and #[test] attributes. This makes the C glue no longer needed.

---
 rust/Makefile               |  4 +--
 scripts/rustdoc_test_gen.rs | 69 ++++++---------------------------------------
 2 files changed, 10 insertions(+), 63 deletions(-)
rust/Makefile +1 -3
index da1a7409d984..ec8c08ee3263 100644
@@ -39,10 +39,8 @@ obj-$(CONFIG_RUST) += exports.o
 always-$(CONFIG_RUST) += host/libproc_macro2.rlib host/libquote.rlib host/libsyn.rlib
 
 always-$(CONFIG_RUST_KERNEL_DOCTESTS) += doctests_kernel_generated.rs
-always-$(CONFIG_RUST_KERNEL_DOCTESTS) += doctests_kernel_generated_kunit.c
 
 obj-$(CONFIG_RUST_KERNEL_DOCTESTS) += doctests_kernel_generated.o
-obj-$(CONFIG_RUST_KERNEL_DOCTESTS) += doctests_kernel_generated_kunit.o
 
 always-$(subst y,$(CONFIG_RUST),$(CONFIG_JUMP_LABEL)) += kernel/generated_arch_static_branch_asm.rs
 ifndef CONFIG_UML
@@ -400,7 +398,7 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $<
 		$< $(rustdoc_test_kernel_quiet); \
 	$(objtree)/scripts/rustdoc_test_gen
 
-%/doctests_kernel_generated.rs %/doctests_kernel_generated_kunit.c: \
+%/doctests_kernel_generated.rs: \
     $(src)/kernel/lib.rs $(obj)/kernel.o \
     $(objtree)/scripts/rustdoc_test_builder \
     $(objtree)/scripts/rustdoc_test_gen FORCE
scripts/rustdoc_test_gen.rs +9 -60

102 lines not on this page · raw message

Signature · 1 line
2.54.0
maintainer
#4 lore raw
In reply to Gary Guo

Le 03/09/2026 à 5:59 AM, Gary Guo a écrit :

Quoted 15 lines

Currently in Rust, kunit tests are handled with kunit_tests, while the doctests generate a lot extern "C" functions and invoke them through a generated C wrapper.

This is currently needed because of the special treatment of file name and line numbers from doctests. Convert them to override file!() and line!() macro instead, and use them inside kunit_assert!.

With this it is possible to just generate #[kunit_tests] and #[test] for doctests.

David mentioned in [1] that this should route via the Rust tree.

Quoted 8 lines

---
Changes in v2:
- Rebased on v7.3-rc1
- Picked up tags
- Link to v1: https://patch.msgid.link/[email protected]

---

Thanks again. This still looks good to me.

Cheers,
-- David

Quoted 23 lines

Gary Guo (3):
rust: kunit: use file!() inside kunit_assert!
rust: kunit: use line!() inside kunit_assert!
rust: doctest: generate Rust kunit test suites

 Documentation/rust/general-information.rst |  4 +-
 init/Kconfig                               |  3 --
 rust/Makefile                              |  4 +-
 rust/kernel/kunit.rs                       | 11 +++--
 rust/kernel/str.rs                         |  2 +-
 rust/macros/helpers.rs                     | 16 -------
 rust/macros/kunit.rs                       |  5 +-
 rust/macros/lib.rs                         |  5 --
 scripts/rustdoc_test_gen.rs                | 73 ++++++++----------------------
 9 files changed, 30 insertions(+), 93 deletions(-)

---
base-commit: cee9395acd8043be0644b25c34bfa86623f2b935
change-id: 20260616-kunit-348f2c029b1e

Best regards,

Signature · 1 line
Gary Guo <[email protected]>
Applied
#5 lore raw
In reply to Gary Guo
Quoted 9 lines · Gary Guo

Currently in Rust, kunit tests are handled with kunit_tests, while the doctests generate a lot extern "C" functions and invoke them through a generated C wrapper.

This is currently needed because of the special treatment of file name and line numbers from doctests. Convert them to override file!() and line!() macro instead, and use them inside kunit_assert!.

Quoted 8 lines

With this it is possible to just generate #[kunit_tests] and #[test] for doctests.

David mentioned in [1] that this should route via the Rust tree.

Applied to rust-next -- thanks everyone!

[ Removed spurious ///-to-// change and adjusted line! to match.
Added a comment to match file!'s. Made NOTE: more precise. Reworded to say it is only one doctest being updated. - Miguel ]

[ Removed generated file from rust/.gitignore and added it to
scripts/remove-stale-files. - Miguel ]

Cheers,
Miguel