naga/common/wgsl/
to_wgsl.rs

1//! Generating WGSL source code for Naga IR types.
2
3use alloc::format;
4use alloc::string::{String, ToString};
5
6/// Types that can return the WGSL source representation of their
7/// values as a `'static` string.
8///
9/// This trait is specifically for types whose WGSL forms are simple
10/// enough that they can always be returned as a static string.
11///
12/// - If only some values have a WGSL representation, consider
13///   implementing [`TryToWgsl`] instead.
14///
15/// - If a type's WGSL form requires dynamic formatting, so that
16///   returning a `&'static str` isn't feasible, consider implementing
17///   [`std::fmt::Display`] on some wrapper type instead.
18pub trait ToWgsl: Sized {
19    /// Return WGSL source code representation of `self`.
20    fn to_wgsl(self) -> &'static str;
21}
22
23/// Types that may be able to return the WGSL source representation
24/// for their values as a `'static` string.
25///
26/// This trait is specifically for types whose values are either
27/// simple enough that their WGSL form can be represented a static
28/// string, or aren't representable in WGSL at all.
29///
30/// - If all values in the type have `&'static str` representations in
31///   WGSL, consider implementing [`ToWgsl`] instead.
32///
33/// - If a type's WGSL form requires dynamic formatting, so that
34///   returning a `&'static str` isn't feasible, consider implementing
35///   [`std::fmt::Display`] on some wrapper type instead.
36pub trait TryToWgsl: Sized {
37    /// Return the WGSL form of `self` as a `'static` string.
38    ///
39    /// If `self` doesn't have a representation in WGSL (standard or
40    /// as extended by Naga), then return `None`.
41    fn try_to_wgsl(self) -> Option<&'static str>;
42
43    /// What kind of WGSL thing `Self` represents.
44    const DESCRIPTION: &'static str;
45
46    /// Return the WGSL form of `self` as appropriate for diagnostics.
47    ///
48    /// If `self` can be expressed in WGSL, return that form as a
49    /// [`String`]. Otherwise, return some representation of `self`
50    /// that is appropriate for use in diagnostic messages.
51    ///
52    /// The default implementation of this function falls back to
53    /// `self`'s [`Debug`] form.
54    ///
55    /// [`Debug`]: core::fmt::Debug
56    fn to_wgsl_for_diagnostics(self) -> String
57    where
58        Self: core::fmt::Debug + Copy,
59    {
60        match self.try_to_wgsl() {
61            Some(static_string) => static_string.to_string(),
62            None => format!("{{non-WGSL {} {self:?}}}", Self::DESCRIPTION),
63        }
64    }
65}
66
67impl TryToWgsl for crate::MathFunction {
68    const DESCRIPTION: &'static str = "math function";
69
70    fn try_to_wgsl(self) -> Option<&'static str> {
71        use crate::MathFunction as Mf;
72
73        Some(match self {
74            Mf::Abs => "abs",
75            Mf::Min => "min",
76            Mf::Max => "max",
77            Mf::Clamp => "clamp",
78            Mf::Saturate => "saturate",
79            Mf::Cos => "cos",
80            Mf::Cosh => "cosh",
81            Mf::Sin => "sin",
82            Mf::Sinh => "sinh",
83            Mf::Tan => "tan",
84            Mf::Tanh => "tanh",
85            Mf::Acos => "acos",
86            Mf::Asin => "asin",
87            Mf::Atan => "atan",
88            Mf::Atan2 => "atan2",
89            Mf::Asinh => "asinh",
90            Mf::Acosh => "acosh",
91            Mf::Atanh => "atanh",
92            Mf::Radians => "radians",
93            Mf::Degrees => "degrees",
94            Mf::Ceil => "ceil",
95            Mf::Floor => "floor",
96            Mf::Round => "round",
97            Mf::Fract => "fract",
98            Mf::Trunc => "trunc",
99            Mf::Modf => "modf",
100            Mf::Frexp => "frexp",
101            Mf::Ldexp => "ldexp",
102            Mf::Exp => "exp",
103            Mf::Exp2 => "exp2",
104            Mf::Log => "log",
105            Mf::Log2 => "log2",
106            Mf::Pow => "pow",
107            Mf::Dot => "dot",
108            Mf::Cross => "cross",
109            Mf::Distance => "distance",
110            Mf::Length => "length",
111            Mf::Normalize => "normalize",
112            Mf::FaceForward => "faceForward",
113            Mf::Reflect => "reflect",
114            Mf::Refract => "refract",
115            Mf::Sign => "sign",
116            Mf::Fma => "fma",
117            Mf::Mix => "mix",
118            Mf::Step => "step",
119            Mf::SmoothStep => "smoothstep",
120            Mf::Sqrt => "sqrt",
121            Mf::InverseSqrt => "inverseSqrt",
122            Mf::Transpose => "transpose",
123            Mf::Determinant => "determinant",
124            Mf::QuantizeToF16 => "quantizeToF16",
125            Mf::CountTrailingZeros => "countTrailingZeros",
126            Mf::CountLeadingZeros => "countLeadingZeros",
127            Mf::CountOneBits => "countOneBits",
128            Mf::ReverseBits => "reverseBits",
129            Mf::ExtractBits => "extractBits",
130            Mf::InsertBits => "insertBits",
131            Mf::FirstTrailingBit => "firstTrailingBit",
132            Mf::FirstLeadingBit => "firstLeadingBit",
133            Mf::Pack4x8snorm => "pack4x8snorm",
134            Mf::Pack4x8unorm => "pack4x8unorm",
135            Mf::Pack2x16snorm => "pack2x16snorm",
136            Mf::Pack2x16unorm => "pack2x16unorm",
137            Mf::Pack2x16float => "pack2x16float",
138            Mf::Pack4xI8 => "pack4xI8",
139            Mf::Pack4xU8 => "pack4xU8",
140            Mf::Unpack4x8snorm => "unpack4x8snorm",
141            Mf::Unpack4x8unorm => "unpack4x8unorm",
142            Mf::Unpack2x16snorm => "unpack2x16snorm",
143            Mf::Unpack2x16unorm => "unpack2x16unorm",
144            Mf::Unpack2x16float => "unpack2x16float",
145            Mf::Unpack4xI8 => "unpack4xI8",
146            Mf::Unpack4xU8 => "unpack4xU8",
147
148            // Non-standard math functions.
149            Mf::Inverse | Mf::Outer => return None,
150        })
151    }
152}
153
154impl TryToWgsl for crate::BuiltIn {
155    const DESCRIPTION: &'static str = "builtin value";
156
157    fn try_to_wgsl(self) -> Option<&'static str> {
158        use crate::BuiltIn as Bi;
159        Some(match self {
160            Bi::Position { .. } => "position",
161            Bi::ViewIndex => "view_index",
162            Bi::InstanceIndex => "instance_index",
163            Bi::VertexIndex => "vertex_index",
164            Bi::FragDepth => "frag_depth",
165            Bi::FrontFacing => "front_facing",
166            Bi::PrimitiveIndex => "primitive_index",
167            Bi::SampleIndex => "sample_index",
168            Bi::SampleMask => "sample_mask",
169            Bi::GlobalInvocationId => "global_invocation_id",
170            Bi::LocalInvocationId => "local_invocation_id",
171            Bi::LocalInvocationIndex => "local_invocation_index",
172            Bi::WorkGroupId => "workgroup_id",
173            Bi::NumWorkGroups => "num_workgroups",
174            Bi::NumSubgroups => "num_subgroups",
175            Bi::SubgroupId => "subgroup_id",
176            Bi::SubgroupSize => "subgroup_size",
177            Bi::SubgroupInvocationId => "subgroup_invocation_id",
178
179            // Non-standard built-ins.
180            Bi::BaseInstance
181            | Bi::BaseVertex
182            | Bi::ClipDistance
183            | Bi::CullDistance
184            | Bi::PointSize
185            | Bi::DrawID
186            | Bi::PointCoord
187            | Bi::WorkGroupSize => return None,
188        })
189    }
190}
191
192impl ToWgsl for crate::Interpolation {
193    fn to_wgsl(self) -> &'static str {
194        match self {
195            crate::Interpolation::Perspective => "perspective",
196            crate::Interpolation::Linear => "linear",
197            crate::Interpolation::Flat => "flat",
198        }
199    }
200}
201
202impl ToWgsl for crate::Sampling {
203    fn to_wgsl(self) -> &'static str {
204        match self {
205            crate::Sampling::Center => "center",
206            crate::Sampling::Centroid => "centroid",
207            crate::Sampling::Sample => "sample",
208            crate::Sampling::First => "first",
209            crate::Sampling::Either => "either",
210        }
211    }
212}
213
214impl ToWgsl for crate::StorageFormat {
215    fn to_wgsl(self) -> &'static str {
216        use crate::StorageFormat as Sf;
217
218        match self {
219            Sf::R8Unorm => "r8unorm",
220            Sf::R8Snorm => "r8snorm",
221            Sf::R8Uint => "r8uint",
222            Sf::R8Sint => "r8sint",
223            Sf::R16Uint => "r16uint",
224            Sf::R16Sint => "r16sint",
225            Sf::R16Float => "r16float",
226            Sf::Rg8Unorm => "rg8unorm",
227            Sf::Rg8Snorm => "rg8snorm",
228            Sf::Rg8Uint => "rg8uint",
229            Sf::Rg8Sint => "rg8sint",
230            Sf::R32Uint => "r32uint",
231            Sf::R32Sint => "r32sint",
232            Sf::R32Float => "r32float",
233            Sf::Rg16Uint => "rg16uint",
234            Sf::Rg16Sint => "rg16sint",
235            Sf::Rg16Float => "rg16float",
236            Sf::Rgba8Unorm => "rgba8unorm",
237            Sf::Rgba8Snorm => "rgba8snorm",
238            Sf::Rgba8Uint => "rgba8uint",
239            Sf::Rgba8Sint => "rgba8sint",
240            Sf::Bgra8Unorm => "bgra8unorm",
241            Sf::Rgb10a2Uint => "rgb10a2uint",
242            Sf::Rgb10a2Unorm => "rgb10a2unorm",
243            Sf::Rg11b10Ufloat => "rg11b10float",
244            Sf::R64Uint => "r64uint",
245            Sf::Rg32Uint => "rg32uint",
246            Sf::Rg32Sint => "rg32sint",
247            Sf::Rg32Float => "rg32float",
248            Sf::Rgba16Uint => "rgba16uint",
249            Sf::Rgba16Sint => "rgba16sint",
250            Sf::Rgba16Float => "rgba16float",
251            Sf::Rgba32Uint => "rgba32uint",
252            Sf::Rgba32Sint => "rgba32sint",
253            Sf::Rgba32Float => "rgba32float",
254            Sf::R16Unorm => "r16unorm",
255            Sf::R16Snorm => "r16snorm",
256            Sf::Rg16Unorm => "rg16unorm",
257            Sf::Rg16Snorm => "rg16snorm",
258            Sf::Rgba16Unorm => "rgba16unorm",
259            Sf::Rgba16Snorm => "rgba16snorm",
260        }
261    }
262}
263
264impl TryToWgsl for crate::Scalar {
265    const DESCRIPTION: &'static str = "scalar type";
266
267    fn try_to_wgsl(self) -> Option<&'static str> {
268        use crate::Scalar;
269
270        Some(match self {
271            Scalar::F16 => "f16",
272            Scalar::F32 => "f32",
273            Scalar::F64 => "f64",
274            Scalar::I32 => "i32",
275            Scalar::U32 => "u32",
276            Scalar::I64 => "i64",
277            Scalar::U64 => "u64",
278            Scalar::BOOL => "bool",
279            _ => return None,
280        })
281    }
282
283    fn to_wgsl_for_diagnostics(self) -> String {
284        match self.try_to_wgsl() {
285            Some(static_string) => static_string.to_string(),
286            None => match self.kind {
287                crate::ScalarKind::Sint
288                | crate::ScalarKind::Uint
289                | crate::ScalarKind::Float
290                | crate::ScalarKind::Bool => format!("{{non-WGSL scalar {self:?}}}"),
291                crate::ScalarKind::AbstractInt => "{AbstractInt}".to_string(),
292                crate::ScalarKind::AbstractFloat => "{AbstractFloat}".to_string(),
293            },
294        }
295    }
296}
297
298impl ToWgsl for crate::ImageDimension {
299    fn to_wgsl(self) -> &'static str {
300        use crate::ImageDimension as IDim;
301
302        match self {
303            IDim::D1 => "1d",
304            IDim::D2 => "2d",
305            IDim::D3 => "3d",
306            IDim::Cube => "cube",
307        }
308    }
309}
310
311/// Return the WGSL address space and access mode strings for `space`.
312///
313/// Why don't we implement [`ToWgsl`] for [`AddressSpace`]?
314///
315/// In WGSL, the full form of a pointer type is `ptr<AS, T, AM>`, where:
316/// - `AS` is the address space,
317/// - `T` is the store type, and
318/// - `AM` is the access mode.
319///
320/// Since the type `T` intervenes between the address space and the
321/// access mode, there isn't really any individual WGSL grammar
322/// production that corresponds to an [`AddressSpace`], so [`ToWgsl`]
323/// is too simple-minded for this case.
324///
325/// Furthermore, we want to write `var<AS[, AM]>` for most address
326/// spaces, but we want to just write `var foo: T` for handle types.
327///
328/// [`AddressSpace`]: crate::AddressSpace
329pub const fn address_space_str(
330    space: crate::AddressSpace,
331) -> (Option<&'static str>, Option<&'static str>) {
332    use crate::AddressSpace as As;
333
334    (
335        Some(match space {
336            As::Private => "private",
337            As::Uniform => "uniform",
338            As::Storage { access } => {
339                if access.contains(crate::StorageAccess::ATOMIC) {
340                    return (Some("storage"), Some("atomic"));
341                } else if access.contains(crate::StorageAccess::STORE) {
342                    return (Some("storage"), Some("read_write"));
343                } else {
344                    "storage"
345                }
346            }
347            As::PushConstant => "push_constant",
348            As::WorkGroup => "workgroup",
349            As::Handle => return (None, None),
350            As::Function => "function",
351        }),
352        None,
353    )
354}