rust: introduce sfile macro for succinct code tracing
PATCH v5 1/1 rust: introduce sfile macro for succinct code tracing
Introduce the sfile (short file) macro that returns the stem of the current source file filename.
Rust provides a file!() macro that is similar to C's __FILE__ predefined macro. Unlike __FILE__, however, file!() returns a full path, which is klunky when used for debug traces such as
pr_info!("{}:{}\n", file!(), line!());sfile!() can be used in situations instead, to provide a more compact print. For example, if file!() returns "rust/kernel/print.rs", sfile!() returns just "print".
The macro avoids str::rfind() because currently, that function is not const. The compiler emits a call to memrchr, even when called on string literals. Instead, the macro implements its own versions of rfind(), allowing the compiler to generate the slice at compile time.
The macro also uses some unsafe functions in order to avoid indexing into a str, which is necessary to fully support const contexts.
--- rust/kernel/print.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/str.rs | 28 ++++++++++++++++++++ 2 files changed, 91 insertions(+)
rust/kernel/print.rs +63 -0
@@ -423,3 +423,66 @@ macro_rules! pr_cont ( $crate::print_macro!($crate ::print::format_strings::CONT ,true , $($arg)*) ) ); + +/// Returns just the base filename of the current file. +/// +/// This differs from the built-in [`file!()`] macro, which returns the full +/// path of the current file. +/// +/// # Examples +/// +/// Useful for succinct logging purposes. +/// +/// ``` +/// # use kernel::sfile; +/// // Output: `example:42`. +/// pr_err!("{}:{}\n", sfile!(), line!()); +/// ``` +/// +/// The value is a constant expression, so it can be used in const +/// contexts, e.g.: +/// +/// ``` +/// # use kernel::sfile; +/// // Contains: `example`. +/// const SFILE: &'static str = sfile!(); +/// ``` +#[macro_export] +macro_rules! sfile { + () => {{ +const fn shortname () ->Option <&'static str > { +const FILE : &str = core::file!(); + +let start = ::kernel::str ::rfind_const (FILE ,'/' ).unwrap () +1 ; +let end = ::kernel::str ::rfind_const (FILE ,'.' ).unwrap (); + +// Make sure that there actually is something to return. This also +// covers a lot of corner cases, such as eliminating filenames that +// end in a slash (not possible) or don't have an extension, +// and making sure that `start` < `FILE.len()` and `end` - `start` > 0. +if end <= start { +return None ; + } + +// The following code is the equivalent of &FILE[start..start+len], +// except that it is allowed in const contexts. + +let base_ptr: *const u8 =FILE .as_ptr (); + +// SAFETY: The above assertion ensures that `start` points to inside +// the string. +let p =unsafe { <*const ::core::primitive::u8 >::add (base_ptr, start) }; +// SAFETY: Based on all constraints on `start` and `end`, this slice +// will never extend beyond the string. +let p =unsafe { core::slice::from_raw_parts (p, end - start) }; +// SAFETY: We know that the slice is valid UTF-8, because we checked +// that `FILE` is ASCII (via `is_ascii()` above). +match core::str ::from_utf8 (p) { +Ok (slice) =>Some (slice), +Err (_) =>None , + } + } + +shortname ().unwrap () + }}; +}
rust/kernel/str.rs +28 -0
@@ -936,3 +936,31 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {macro_rules! fmt { ($($f:tt)*) => ( ::core::format_args!($($f)*) ) } + +/// Returns the index of the last occurrence of `needle` in `haystack`, or [`None`]. +/// +/// Similar to [`str::rfind()`], except this one is const. It also only supports +/// ASCII strings. +/// +/// # Examples +/// +/// ``` +/// # use ::kernel::str::rfind_const; +/// let l = rfind_const("when will then be now?", 'l'); +/// assert!(l == Some(8)); +/// +/// let q = rfind_const("when will then be now?", 'q'); +/// assert!(q == None); +/// ``` +#[inline] +pub const fn rfind_const (haystack: &str , needle:char ) ->Option <usize > { +let haystack = haystack.as_bytes (); +let mut i = haystack.len (); +while i >0 { + i -=1 ; +if haystack[i] == needleas u8 { +return Some (i); + } + } +None +}
base-commit: c4dce0c094a89b1bc8fde1163342bd6fe29c0370
Signature · 1 line
2.48.1
kernel test robot
build botkernel test robot noticed the following build errors:
Hi Timur,
kernel test robot noticed the following build errors:
[auto build test ERROR on c4dce0c094a89b1bc8fde1163342bd6fe29c0370]
url: https://github.com/intel-lab-lkp/linux/commits/Timur-Tabi/rust-introduce-sfile-macro-for-succinct-code-tracing/20250627-043731 base: c4dce0c094a89b1bc8fde1163342bd6fe29c0370 patch link: https://lore.kernel.org/r/20250626203535.331219-1-ttabi%40nvidia.com patch subject: [PATCH v5] rust: introduce sfile macro for succinct code tracing config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20250629/[email protected]/config) compiler: clang version 18.1.8 (https://github.com/llvm/llvm-project 3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff) rustc: rustc 1.78.0 (9b00956e5 2024-04-29) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250629/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> error: `Option::<T>::unwrap` is not yet stable as a const fn
--> rust/doctests_kernel_generated.rs:5969:29
|
5969 | const SFILE: &'static str = sfile!();
| ^^^^^^^^
|
= help: add #![feature(const_option)] to the crate attributes to enable
= note: this error originates in the macro sfile (in Nightly builds, run with -Z macro-backtrace for more info)
--
>> error: `Option::<T>::unwrap` is not yet stable as a const fn
--> rust/doctests_kernel_generated.rs:5915:20
|
5915 | pr_err!("{}:{}n", sfile!(), line!());
| ^^^^^^^^
|
= help: add #![feature(const_option)] to the crate attributes to enable
= note: this error originates in the macro sfile (in Nightly builds, run with -Z macro-backtrace for more info)
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki