Add enter_trace_span! that checks #[cfg("tracing")]

Includes a custom syntax shortand to enter_trace_span! with NAME::SUBNAME.

MaybeEnteredTraceSpan is `pub use`d in lib.rs to make it available also in bin/, just in case.
This commit is contained in:
Stypox
2025-07-07 11:10:51 +02:00
parent a96e73f39e
commit 6b51eee9df
2 changed files with 44 additions and 1 deletions

View File

@@ -1431,3 +1431,44 @@ impl ToU64 for usize {
self.try_into().unwrap()
}
}
/// This struct is needed to enforce `#[must_use]` on values produced by [enter_trace_span] even
/// when the "tracing" feature is not enabled.
#[must_use]
pub struct MaybeEnteredTraceSpan {
#[cfg(feature = "tracing")]
pub _entered_span: tracing::span::EnteredSpan,
}
/// Enters a [tracing::info_span] only if the "tracing" feature is enabled, otherwise does nothing.
/// This is like [rustc_const_eval::enter_trace_span] except that it does not depend on the
/// [Machine] trait to check if tracing is enabled, because from the Miri codebase we can directly
/// check whether the "tracing" feature is enabled, unlike from the rustc_const_eval codebase.
///
/// In addition to the syntax accepted by [tracing::span!], this macro optionally allows passing
/// the span name (i.e. the first macro argument) in the form `NAME::SUBNAME` (without quotes) to
/// indicate that the span has name "NAME" (usually the name of the component) and has an additional
/// more specific name "SUBNAME" (usually the function name). The latter is passed to the [tracing]
/// infrastructure as a span field with the name "NAME". This allows not being distracted by
/// subnames when looking at the trace in <https://ui.perfetto.dev>, but when deeper introspection
/// is needed within a component, it's still possible to view the subnames directly in the UI by
/// selecting a span, clicking on the "NAME" argument on the right, and clicking on "Visualize
/// argument values".
/// ```rust
/// // for example, the first will expand to the second
/// enter_trace_span!(borrow_tracker::on_stack_pop, /* ... */)
/// enter_trace_span!("borrow_tracker", borrow_tracker = "on_stack_pop", /* ... */)
/// ```
#[macro_export]
macro_rules! enter_trace_span {
($name:ident :: $subname:ident $($tt:tt)*) => {{
enter_trace_span!(stringify!($name), $name = %stringify!(subname) $($tt)*)
}};
($($tt:tt)*) => {
$crate::MaybeEnteredTraceSpan {
#[cfg(feature = "tracing")]
_entered_span: tracing::info_span!($($tt)*).entered()
}
};
}

View File

@@ -139,7 +139,9 @@ pub use crate::eval::{
AlignmentCheck, BacktraceStyle, IsolatedOp, MiriConfig, MiriEntryFnType, RejectOpWith,
ValidationMode, create_ecx, eval_entry,
};
pub use crate::helpers::{AccessKind, EvalContextExt as _, ToU64 as _, ToUsize as _};
pub use crate::helpers::{
AccessKind, EvalContextExt as _, MaybeEnteredTraceSpan, ToU64 as _, ToUsize as _,
};
pub use crate::intrinsics::EvalContextExt as _;
pub use crate::machine::{
AllocExtra, DynMachineCallback, FrameExtra, MachineCallback, MemoryKind, MiriInterpCx,