[naga] Introduce ForDebug and ForDebugWithTypes traits

Introduce traits to add `for_debug` methods to Naga IR types that can
be formatted with `core::fmt::Debug`, given adequate context.
This commit is contained in:
Jim Blandy 2025-04-01 10:14:31 -07:00 committed by Connor Fitzgerald
parent d19e3b2b3e
commit 8292949478
2 changed files with 41 additions and 1 deletions

View File

@ -84,3 +84,43 @@ impl fmt::Debug for DiagnosticDebug<Scalar> {
Ok(())
}
}
pub trait ForDebug: Sized {
/// Format this type using [`core::fmt::Debug`].
///
/// Return a value that implements the [`core::fmt::Debug`] trait
/// by displaying `self` in a language-appropriate way. For
/// example:
///
/// # use naga::common::ForDebug;
/// # let scalar: naga::Scalar = naga::Scalar::F32;
/// log::debug!("My scalar: {:?}", scalar.for_debug());
fn for_debug(self) -> DiagnosticDebug<Self> {
DiagnosticDebug(self)
}
}
impl ForDebug for Scalar {}
pub trait ForDebugWithTypes: Sized {
/// Format this type using [`core::fmt::Debug`].
///
/// Given an arena to look up type handles in, return a value that
/// implements the [`core::fmt::Debug`] trait by displaying `self`
/// in a language-appropriate way. For example:
///
/// # use naga::{Span, Type, TypeInner, Scalar, UniqueArena};
/// # use naga::common::ForDebugWithTypes;
/// # let mut types = UniqueArena::<Type>::default();
/// # let inner = TypeInner::Scalar(Scalar::F32);
/// # let span = Span::UNDEFINED;
/// # let handle = types.insert(Type { name: None, inner }, span);
/// log::debug!("My type: {:?}", handle.for_debug(&types));
fn for_debug(self, types: &UniqueArena<Type>) -> DiagnosticDebug<(Self, &UniqueArena<Type>)> {
DiagnosticDebug((self, types))
}
}
impl ForDebugWithTypes for Handle<Type> {}
impl ForDebugWithTypes for &TypeInner {}
impl ForDebugWithTypes for &TypeResolution {}

View File

@ -5,7 +5,7 @@ mod diagnostic_display;
pub mod predeclared;
pub mod wgsl;
pub use diagnostic_debug::DiagnosticDebug;
pub use diagnostic_debug::{DiagnosticDebug, ForDebug, ForDebugWithTypes};
pub use diagnostic_display::DiagnosticDisplay;
/// Helper function that returns the string corresponding to the [`VectorSize`](crate::VectorSize)