Skip to content

Commit 2cf5c4f

Browse files
committed
[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.
1 parent 548bf3a commit 2cf5c4f

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

naga/src/common/diagnostic_debug.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,43 @@ impl fmt::Debug for DiagnosticDebug<Scalar> {
8484
Ok(())
8585
}
8686
}
87+
88+
pub trait ForDebug: Sized {
89+
/// Format this type using [`core::fmt::Debug`].
90+
///
91+
/// Return a value that implements the [`core::fmt::Debug`] trait
92+
/// by displaying `self` in a language-appropriate way. For
93+
/// example:
94+
///
95+
/// # use naga::common::ForDebug;
96+
/// # let scalar: naga::Scalar = naga::Scalar::F32;
97+
/// log::debug!("My scalar: {:?}", scalar.for_debug());
98+
fn for_debug(self) -> DiagnosticDebug<Self> {
99+
DiagnosticDebug(self)
100+
}
101+
}
102+
103+
impl ForDebug for Scalar {}
104+
105+
pub trait ForDebugWithTypes: Sized {
106+
/// Format this type using [`core::fmt::Debug`].
107+
///
108+
/// Given an arena to look up type handles in, return a value that
109+
/// implements the [`core::fmt::Debug`] trait by displaying `self`
110+
/// in a language-appropriate way. For example:
111+
///
112+
/// # use naga::{Span, Type, TypeInner, Scalar, UniqueArena};
113+
/// # use naga::common::ForDebugWithTypes;
114+
/// # let mut types = UniqueArena::<Type>::default();
115+
/// # let inner = TypeInner::Scalar(Scalar::F32);
116+
/// # let span = Span::UNDEFINED;
117+
/// # let handle = types.insert(Type { name: None, inner }, span);
118+
/// log::debug!("My type: {:?}", handle.for_debug(&types));
119+
fn for_debug(self, types: &UniqueArena<Type>) -> DiagnosticDebug<(Self, &UniqueArena<Type>)> {
120+
DiagnosticDebug((self, types))
121+
}
122+
}
123+
124+
impl ForDebugWithTypes for Handle<Type> {}
125+
impl ForDebugWithTypes for &TypeInner {}
126+
impl ForDebugWithTypes for &TypeResolution {}

naga/src/common/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ mod diagnostic_display;
55
pub mod predeclared;
66
pub mod wgsl;
77

8-
pub use diagnostic_debug::DiagnosticDebug;
8+
pub use diagnostic_debug::{DiagnosticDebug, ForDebug, ForDebugWithTypes};
99
pub use diagnostic_display::DiagnosticDisplay;
1010

1111
/// Helper function that returns the string corresponding to the [`VectorSize`](crate::VectorSize)

0 commit comments

Comments
 (0)