* [PATCH v5] rust: introduce sfile macro for succinct code tracing
@ 2025-06-26 20:35 Timur Tabi
2025-06-29 13:41 ` kernel test robot
0 siblings, 1 reply; 2+ messages in thread
From: Timur Tabi @ 2025-06-26 20:35 UTC (permalink / raw)
To: Miguel Ojeda, Benno Lossin, Alice Ryhl, Danilo Krummrich,
rust-for-linux
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.
Signed-off-by: Timur Tabi <ttabi@nvidia.com>
---
rust/kernel/print.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++
rust/kernel/str.rs | 28 ++++++++++++++++++++
2 files changed, 91 insertions(+)
diff --git a/rust/kernel/print.rs b/rust/kernel/print.rs
index 9783d960a97a..40f1ff0342af 100644
--- a/rust/kernel/print.rs
+++ b/rust/kernel/print.rs
@@ -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()
+ }};
+}
diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index a927db8e079c..d74b94a406c4 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -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] == needle as u8 {
+ return Some(i);
+ }
+ }
+ None
+}
base-commit: c4dce0c094a89b1bc8fde1163342bd6fe29c0370
--
2.48.1
^ permalink raw reply related [flat|nested] 2+ messages in thread
* Re: [PATCH v5] rust: introduce sfile macro for succinct code tracing
2025-06-26 20:35 [PATCH v5] rust: introduce sfile macro for succinct code tracing Timur Tabi
@ 2025-06-29 13:41 ` kernel test robot
0 siblings, 0 replies; 2+ messages in thread
From: kernel test robot @ 2025-06-29 13:41 UTC (permalink / raw)
To: Timur Tabi, Miguel Ojeda, Benno Lossin, Alice Ryhl,
Danilo Krummrich, rust-for-linux
Cc: llvm, oe-kbuild-all
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/202506292116.f6SHoUIX-lkp@intel.com/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/202506292116.f6SHoUIX-lkp@intel.com/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 <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202506292116.f6SHoUIX-lkp@intel.com/
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)
--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
^ permalink raw reply [flat|nested] 2+ messages in thread
end of thread, other threads:[~2025-06-29 13:41 UTC | newest]
Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-06-26 20:35 [PATCH v5] rust: introduce sfile macro for succinct code tracing Timur Tabi
2025-06-29 13:41 ` kernel test robot
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).