Skip to main content

naga/back/wgsl/
writer.rs

1use alloc::{
2    format,
3    string::{String, ToString},
4    vec,
5    vec::Vec,
6};
7use core::fmt::Write;
8
9use super::Error;
10use super::ToWgslIfImplemented as _;
11use crate::{back::wgsl::polyfill::InversePolyfill, common::wgsl::TypeContext};
12use crate::{
13    back::{self, Baked},
14    common::{
15        self,
16        wgsl::{address_space_str, ToWgsl, TryToWgsl},
17    },
18    proc::{self, NameKey},
19    valid, Handle, Module, ShaderStage, TypeInner,
20};
21
22/// Shorthand result used internally by the backend
23type BackendResult = Result<(), Error>;
24
25/// WGSL [attribute](https://gpuweb.github.io/gpuweb/wgsl/#attributes)
26enum Attribute {
27    Binding(u32),
28    BuiltIn(crate::BuiltIn),
29    Group(u32),
30    Invariant,
31    Interpolate(Option<crate::Interpolation>, Option<crate::Sampling>),
32    Location(u32),
33    BlendSrc(u32),
34    Stage(ShaderStage),
35    WorkGroupSize([u32; 3]),
36    MeshStage(String),
37    TaskPayload(String),
38    PerPrimitive,
39    IncomingRayPayload(String),
40}
41
42/// The WGSL form that `write_expr_with_indirection` should use to render a Naga
43/// expression.
44///
45/// Sometimes a Naga `Expression` alone doesn't provide enough information to
46/// choose the right rendering for it in WGSL. For example, one natural WGSL
47/// rendering of a Naga `LocalVariable(x)` expression might be `&x`, since
48/// `LocalVariable` produces a pointer to the local variable's storage. But when
49/// rendering a `Store` statement, the `pointer` operand must be the left hand
50/// side of a WGSL assignment, so the proper rendering is `x`.
51///
52/// The caller of `write_expr_with_indirection` must provide an `Expected` value
53/// to indicate how ambiguous expressions should be rendered.
54#[derive(Clone, Copy, Debug)]
55enum Indirection {
56    /// Render pointer-construction expressions as WGSL `ptr`-typed expressions.
57    ///
58    /// This is the right choice for most cases. Whenever a Naga pointer
59    /// expression is not the `pointer` operand of a `Load` or `Store`, it
60    /// must be a WGSL pointer expression.
61    Ordinary,
62
63    /// Render pointer-construction expressions as WGSL reference-typed
64    /// expressions.
65    ///
66    /// For example, this is the right choice for the `pointer` operand when
67    /// rendering a `Store` statement as a WGSL assignment.
68    Reference,
69}
70
71bitflags::bitflags! {
72    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
73    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
74    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
75    pub struct WriterFlags: u32 {
76        /// Always annotate the type information instead of inferring.
77        const EXPLICIT_TYPES = 0x1;
78    }
79}
80
81#[expect(missing_debug_implementations, reason = "would be way too verbose?")]
82pub struct Writer<W> {
83    out: W,
84    flags: WriterFlags,
85    names: crate::FastHashMap<NameKey, String>,
86    namer: proc::Namer,
87    named_expressions: crate::NamedExpressions,
88    required_polyfills: crate::FastIndexSet<InversePolyfill>,
89}
90
91impl<W: Write> Writer<W> {
92    pub fn new(out: W, flags: WriterFlags) -> Self {
93        Writer {
94            out,
95            flags,
96            names: crate::FastHashMap::default(),
97            namer: proc::Namer::default(),
98            named_expressions: crate::NamedExpressions::default(),
99            required_polyfills: crate::FastIndexSet::default(),
100        }
101    }
102
103    fn reset(&mut self, module: &Module) {
104        self.names.clear();
105        self.namer.reset(
106            module,
107            &crate::keywords::wgsl::RESERVED_SET,
108            &crate::keywords::wgsl::BUILTIN_IDENTIFIER_SET,
109            // an identifier must not start with two underscore
110            proc::CaseInsensitiveKeywordSet::empty(),
111            &["__", "_naga"],
112            &mut self.names,
113        );
114        self.named_expressions.clear();
115        self.required_polyfills.clear();
116    }
117
118    /// Determine if `ty` is the Naga IR presentation of a WGSL builtin type.
119    ///
120    /// Return true if `ty` refers to the Naga IR form of a WGSL builtin type
121    /// like `__atomic_compare_exchange_result`.
122    ///
123    /// Even though the module may use the type, the WGSL backend should avoid
124    /// emitting a definition for it, since it is [predeclared] in WGSL.
125    ///
126    /// This also covers types like [`NagaExternalTextureParams`], which other
127    /// backends use to lower WGSL constructs like external textures to their
128    /// implementations. WGSL can express these directly, so the types need not
129    /// be emitted.
130    ///
131    /// [predeclared]: https://www.w3.org/TR/WGSL/#predeclared
132    /// [`NagaExternalTextureParams`]: crate::ir::SpecialTypes::external_texture_params
133    fn is_builtin_wgsl_struct(&self, module: &Module, ty: Handle<crate::Type>) -> bool {
134        module
135            .special_types
136            .predeclared_types
137            .values()
138            .any(|t| *t == ty)
139            || Some(ty) == module.special_types.external_texture_params
140            || Some(ty) == module.special_types.external_texture_transfer_function
141    }
142
143    pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult {
144        self.reset(module);
145
146        // Write all `enable` declarations
147        self.write_enable_declarations(module)?;
148
149        // Write all structs
150        for (handle, ty) in module.types.iter() {
151            if let TypeInner::Struct { ref members, .. } = ty.inner {
152                {
153                    if !self.is_builtin_wgsl_struct(module, handle) {
154                        self.write_struct(module, handle, members)?;
155                        writeln!(self.out)?;
156                    }
157                }
158            }
159        }
160
161        // Write all named constants
162        let mut constants = module
163            .constants
164            .iter()
165            .filter(|&(_, c)| c.name.is_some())
166            .peekable();
167        while let Some((handle, _)) = constants.next() {
168            self.write_global_constant(module, handle)?;
169            // Add extra newline for readability on last iteration
170            if constants.peek().is_none() {
171                writeln!(self.out)?;
172            }
173        }
174
175        // Write all overrides
176        let mut overrides = module.overrides.iter().peekable();
177        while let Some((handle, _)) = overrides.next() {
178            self.write_override(module, handle)?;
179            // Add extra newline for readability on last iteration
180            if overrides.peek().is_none() {
181                writeln!(self.out)?;
182            }
183        }
184
185        // Write all globals
186        for (ty, global) in module.global_variables.iter() {
187            self.write_global(module, global, ty)?;
188        }
189
190        if !module.global_variables.is_empty() {
191            // Add extra newline for readability
192            writeln!(self.out)?;
193        }
194
195        // Write all regular functions
196        for (handle, function) in module.functions.iter() {
197            let fun_info = &info[handle];
198
199            let func_ctx = back::FunctionCtx {
200                ty: back::FunctionType::Function(handle),
201                info: fun_info,
202                expressions: &function.expressions,
203                named_expressions: &function.named_expressions,
204            };
205
206            // Write the function
207            self.write_function(module, function, &func_ctx)?;
208
209            writeln!(self.out)?;
210        }
211
212        // Write all entry points
213        for (index, ep) in module.entry_points.iter().enumerate() {
214            let attributes = match ep.stage {
215                ShaderStage::Vertex | ShaderStage::Fragment => vec![Attribute::Stage(ep.stage)],
216                ShaderStage::Compute => vec![
217                    Attribute::Stage(ShaderStage::Compute),
218                    Attribute::WorkGroupSize(ep.workgroup_size),
219                ],
220                ShaderStage::Mesh => {
221                    let mesh_output_name = module.global_variables
222                        [ep.mesh_info.as_ref().unwrap().output_variable]
223                        .name
224                        .clone()
225                        .unwrap();
226                    let mut mesh_attrs = vec![
227                        Attribute::MeshStage(mesh_output_name),
228                        Attribute::WorkGroupSize(ep.workgroup_size),
229                    ];
230                    if let Some(task_payload) = ep.task_payload {
231                        let payload_name =
232                            module.global_variables[task_payload].name.clone().unwrap();
233                        mesh_attrs.push(Attribute::TaskPayload(payload_name));
234                    }
235                    mesh_attrs
236                }
237                ShaderStage::Task => {
238                    let payload_name = module.global_variables[ep.task_payload.unwrap()]
239                        .name
240                        .clone()
241                        .unwrap();
242                    vec![
243                        Attribute::Stage(ShaderStage::Task),
244                        Attribute::TaskPayload(payload_name),
245                        Attribute::WorkGroupSize(ep.workgroup_size),
246                    ]
247                }
248                ShaderStage::RayGeneration => vec![Attribute::Stage(ShaderStage::RayGeneration)],
249                ShaderStage::AnyHit | ShaderStage::ClosestHit | ShaderStage::Miss => {
250                    let payload_name = module.global_variables[ep.incoming_ray_payload.unwrap()]
251                        .name
252                        .clone()
253                        .unwrap();
254                    vec![
255                        Attribute::Stage(ep.stage),
256                        Attribute::IncomingRayPayload(payload_name),
257                    ]
258                }
259            };
260            self.write_attributes_line(&attributes)?;
261
262            let func_ctx = back::FunctionCtx {
263                ty: back::FunctionType::EntryPoint(index as u16),
264                info: info.get_entry_point(index),
265                expressions: &ep.function.expressions,
266                named_expressions: &ep.function.named_expressions,
267            };
268            self.write_function(module, &ep.function, &func_ctx)?;
269
270            if index < module.entry_points.len() - 1 {
271                writeln!(self.out)?;
272            }
273        }
274
275        // Write any polyfills that were required.
276        for polyfill in &self.required_polyfills {
277            writeln!(self.out)?;
278            write!(self.out, "{}", polyfill.source)?;
279            writeln!(self.out)?;
280        }
281
282        Ok(())
283    }
284
285    /// Helper method which writes all the `enable` declarations
286    /// needed for a module.
287    fn write_enable_declarations(&mut self, module: &Module) -> BackendResult {
288        #[derive(Default)]
289        struct RequiredEnabled {
290            f16: bool,
291            f64: bool,
292            int16: bool,
293            dual_source_blending: bool,
294            clip_distances: bool,
295            mesh_shaders: bool,
296            primitive_index: bool,
297            cooperative_matrix: bool,
298            draw_index: bool,
299            ray_tracing_pipeline: bool,
300            per_vertex: bool,
301            binding_array: bool,
302            debug_printf: bool,
303        }
304        let mut needed = RequiredEnabled {
305            mesh_shaders: module.uses_mesh_shaders(),
306            ..Default::default()
307        };
308
309        let check_binding = |binding: &crate::Binding, needed: &mut RequiredEnabled| match *binding
310        {
311            crate::Binding::Location {
312                blend_src: Some(_), ..
313            } => {
314                needed.dual_source_blending = true;
315            }
316            crate::Binding::BuiltIn(crate::BuiltIn::ClipDistances) => {
317                needed.clip_distances = true;
318            }
319            crate::Binding::BuiltIn(crate::BuiltIn::PrimitiveIndex) => {
320                needed.primitive_index = true;
321            }
322            crate::Binding::Location {
323                per_primitive: true,
324                ..
325            } => {
326                needed.mesh_shaders = true;
327            }
328            crate::Binding::Location {
329                interpolation: Some(crate::Interpolation::PerVertex),
330                ..
331            } => {
332                needed.per_vertex = true;
333            }
334            crate::Binding::BuiltIn(crate::BuiltIn::DrawIndex) => needed.draw_index = true,
335            crate::Binding::BuiltIn(
336                crate::BuiltIn::RayInvocationId
337                | crate::BuiltIn::NumRayInvocations
338                | crate::BuiltIn::InstanceCustomData
339                | crate::BuiltIn::GeometryIndex
340                | crate::BuiltIn::WorldRayOrigin
341                | crate::BuiltIn::WorldRayDirection
342                | crate::BuiltIn::ObjectRayOrigin
343                | crate::BuiltIn::ObjectRayDirection
344                | crate::BuiltIn::RayTmin
345                | crate::BuiltIn::RayTCurrentMax
346                | crate::BuiltIn::ObjectToWorld
347                | crate::BuiltIn::WorldToObject
348                | crate::BuiltIn::HitKind
349                | crate::BuiltIn::HitBarycentrics,
350            ) => {
351                needed.ray_tracing_pipeline = true;
352            }
353            _ => {}
354        };
355
356        // Determine which `enable` declarations are needed
357        for (_, ty) in module.types.iter() {
358            match ty.inner {
359                TypeInner::Scalar(scalar)
360                | TypeInner::Vector { scalar, .. }
361                | TypeInner::Matrix { scalar, .. } => {
362                    needed.f16 |= scalar == crate::Scalar::F16;
363                    needed.f64 |= scalar == crate::Scalar::F64;
364                    needed.int16 |= scalar == crate::Scalar::I16 || scalar == crate::Scalar::U16;
365                }
366                TypeInner::Struct { ref members, .. } => {
367                    for binding in members.iter().filter_map(|m| m.binding.as_ref()) {
368                        check_binding(binding, &mut needed);
369                    }
370                }
371                TypeInner::CooperativeMatrix { .. } => {
372                    needed.cooperative_matrix = true;
373                }
374                TypeInner::AccelerationStructure { .. } => {
375                    needed.ray_tracing_pipeline = true;
376                }
377                TypeInner::BindingArray { .. } => {
378                    needed.binding_array = true;
379                }
380                _ => {}
381            }
382        }
383
384        for ep in &module.entry_points {
385            if let Some(res) = ep.function.result.as_ref().and_then(|a| a.binding.as_ref()) {
386                check_binding(res, &mut needed);
387            }
388            for arg in ep
389                .function
390                .arguments
391                .iter()
392                .filter_map(|a| a.binding.as_ref())
393            {
394                check_binding(arg, &mut needed);
395            }
396        }
397
398        if module.global_variables.iter().any(|gv| {
399            gv.1.space == crate::AddressSpace::IncomingRayPayload
400                || gv.1.space == crate::AddressSpace::RayPayload
401        }) {
402            needed.ray_tracing_pipeline = true;
403        }
404
405        if module.entry_points.iter().any(|ep| {
406            matches!(
407                ep.stage,
408                ShaderStage::RayGeneration
409                    | ShaderStage::AnyHit
410                    | ShaderStage::ClosestHit
411                    | ShaderStage::Miss
412            )
413        }) {
414            needed.ray_tracing_pipeline = true;
415        }
416
417        if module.global_variables.iter().any(|gv| {
418            gv.1.space == crate::AddressSpace::IncomingRayPayload
419                || gv.1.space == crate::AddressSpace::RayPayload
420        }) {
421            needed.ray_tracing_pipeline = true;
422        }
423
424        if module.entry_points.iter().any(|ep| {
425            matches!(
426                ep.stage,
427                ShaderStage::RayGeneration
428                    | ShaderStage::AnyHit
429                    | ShaderStage::ClosestHit
430                    | ShaderStage::Miss
431            )
432        }) {
433            needed.ray_tracing_pipeline = true;
434        }
435
436        needed.debug_printf = module.uses_debug_printf();
437
438        // Write required declarations
439        let mut any_written = false;
440        if needed.f16 {
441            writeln!(self.out, "enable f16;")?;
442            any_written = true;
443        }
444        if needed.f64 {
445            writeln!(self.out, "enable wgpu_f64;")?;
446            any_written = true;
447        }
448        if needed.int16 {
449            writeln!(self.out, "enable wgpu_int16;")?;
450            any_written = true;
451        }
452        if needed.dual_source_blending {
453            writeln!(self.out, "enable dual_source_blending;")?;
454            any_written = true;
455        }
456        if needed.clip_distances {
457            writeln!(self.out, "enable clip_distances;")?;
458            any_written = true;
459        }
460        if module.uses_mesh_shaders() {
461            writeln!(self.out, "enable wgpu_mesh_shader;")?;
462            any_written = true;
463        }
464        if needed.binding_array {
465            writeln!(self.out, "enable wgpu_binding_array;")?;
466            any_written = true;
467        }
468        if needed.draw_index {
469            writeln!(self.out, "enable draw_index;")?;
470            any_written = true;
471        }
472        if needed.primitive_index {
473            writeln!(self.out, "enable primitive_index;")?;
474            any_written = true;
475        }
476        if needed.cooperative_matrix {
477            writeln!(self.out, "enable wgpu_cooperative_matrix;")?;
478            any_written = true;
479        }
480        if needed.ray_tracing_pipeline {
481            writeln!(self.out, "enable wgpu_ray_tracing_pipeline;")?;
482            any_written = true;
483        }
484        if module.uses_invocation_reorder() {
485            writeln!(self.out, "enable wgpu_ray_tracing_invocation_reorder;")?;
486            any_written = true;
487        }
488        if needed.per_vertex {
489            writeln!(self.out, "enable wgpu_per_vertex;")?;
490            any_written = true;
491        }
492        if needed.debug_printf {
493            writeln!(self.out, "enable wgpu_debug_printf;")?;
494            any_written = true;
495        }
496        if any_written {
497            // Empty line for readability
498            writeln!(self.out)?;
499        }
500
501        Ok(())
502    }
503
504    /// Helper method used to write
505    /// [functions](https://gpuweb.github.io/gpuweb/wgsl/#functions)
506    ///
507    /// # Notes
508    /// Ends in a newline
509    fn write_function(
510        &mut self,
511        module: &Module,
512        func: &crate::Function,
513        func_ctx: &back::FunctionCtx<'_>,
514    ) -> BackendResult {
515        let func_name = match func_ctx.ty {
516            back::FunctionType::EntryPoint(index) => &self.names[&NameKey::EntryPoint(index)],
517            back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)],
518        };
519
520        // Write function name
521        write!(self.out, "fn {func_name}(")?;
522
523        // Write function arguments
524        for (index, arg) in func.arguments.iter().enumerate() {
525            // Write argument attribute if a binding is present
526            if let Some(ref binding) = arg.binding {
527                self.write_attributes(&map_binding_to_attribute(binding))?;
528            }
529            // Write argument name
530            let argument_name = &self.names[&func_ctx.argument_key(index as u32)];
531
532            write!(self.out, "{argument_name}: ")?;
533            // Write argument type
534            self.write_type(module, arg.ty)?;
535            if index < func.arguments.len() - 1 {
536                // Add a separator between args
537                write!(self.out, ", ")?;
538            }
539        }
540
541        write!(self.out, ")")?;
542
543        // Write function return type
544        if let Some(ref result) = func.result {
545            write!(self.out, " -> ")?;
546            if let Some(ref binding) = result.binding {
547                self.write_attributes(&map_binding_to_attribute(binding))?;
548            }
549            self.write_type(module, result.ty)?;
550        }
551
552        write!(self.out, " {{")?;
553        writeln!(self.out)?;
554
555        // Write function local variables
556        for (handle, local) in func.local_variables.iter() {
557            // Write indentation (only for readability)
558            write!(self.out, "{}", back::INDENT)?;
559
560            // Write the local name
561            // The leading space is important
562            write!(self.out, "var {}: ", self.names[&func_ctx.name_key(handle)])?;
563
564            // Write the local type
565            self.write_type(module, local.ty)?;
566
567            // Write the local initializer if needed
568            if let Some(init) = local.init {
569                // Put the equal signal only if there's a initializer
570                // The leading and trailing spaces aren't needed but help with readability
571                write!(self.out, " = ")?;
572
573                // Write the constant
574                // `write_constant` adds no trailing or leading space/newline
575                self.write_expr(module, init, func_ctx)?;
576            }
577
578            // Finish the local with `;` and add a newline (only for readability)
579            writeln!(self.out, ";")?
580        }
581
582        if !func.local_variables.is_empty() {
583            writeln!(self.out)?;
584        }
585
586        // Write the function body (statement list)
587        for sta in func.body.iter() {
588            // The indentation should always be 1 when writing the function body
589            self.write_stmt(module, sta, func_ctx, back::Level(1))?;
590        }
591
592        writeln!(self.out, "}}")?;
593
594        self.named_expressions.clear();
595
596        Ok(())
597    }
598
599    /// Helper method to write an attribute.
600    ///
601    /// Write `attributes` to `out`, with each one followed by a trailing space.
602    fn write_attributes_to(out: &mut impl Write, attributes: &[Attribute]) -> BackendResult {
603        for attribute in attributes {
604            match *attribute {
605                Attribute::Location(id) => write!(out, "@location({id}) ")?,
606                Attribute::BlendSrc(blend_src) => write!(out, "@blend_src({blend_src}) ")?,
607                Attribute::BuiltIn(builtin_attrib) => {
608                    let builtin = builtin_attrib.to_wgsl_if_implemented()?;
609                    write!(out, "@builtin({builtin}) ")?;
610                }
611                Attribute::Stage(shader_stage) => {
612                    let stage_str = match shader_stage {
613                        ShaderStage::Vertex => "vertex",
614                        ShaderStage::Fragment => "fragment",
615                        ShaderStage::Compute => "compute",
616                        ShaderStage::Task => "task",
617                        //Handled by another variant in the Attribute enum, so this code should never be hit.
618                        ShaderStage::Mesh => unreachable!(),
619                        ShaderStage::RayGeneration => "ray_generation",
620                        ShaderStage::AnyHit => "any_hit",
621                        ShaderStage::ClosestHit => "closest_hit",
622                        ShaderStage::Miss => "miss",
623                    };
624
625                    write!(out, "@{stage_str} ")?;
626                }
627                Attribute::WorkGroupSize(size) => {
628                    write!(
629                        out,
630                        "@workgroup_size({}, {}, {}) ",
631                        size[0], size[1], size[2]
632                    )?;
633                }
634                Attribute::Binding(id) => write!(out, "@binding({id}) ")?,
635                Attribute::Group(id) => write!(out, "@group({id}) ")?,
636                Attribute::Invariant => write!(out, "@invariant ")?,
637                Attribute::Interpolate(interpolation, sampling) => {
638                    if sampling.is_some() && sampling != Some(crate::Sampling::Center) {
639                        let interpolation = interpolation
640                            .unwrap_or(crate::Interpolation::Perspective)
641                            .to_wgsl();
642                        let sampling = sampling.unwrap_or(crate::Sampling::Center).to_wgsl();
643                        write!(out, "@interpolate({interpolation}, {sampling}) ")?;
644                    } else if interpolation.is_some()
645                        && interpolation != Some(crate::Interpolation::Perspective)
646                    {
647                        let interpolation = interpolation
648                            .unwrap_or(crate::Interpolation::Perspective)
649                            .to_wgsl();
650                        write!(out, "@interpolate({interpolation}) ")?;
651                    }
652                }
653                Attribute::MeshStage(ref name) => {
654                    write!(out, "@mesh({name}) ")?;
655                }
656                Attribute::TaskPayload(ref payload_name) => {
657                    write!(out, "@payload({payload_name}) ")?;
658                }
659                Attribute::PerPrimitive => write!(out, "@per_primitive ")?,
660                Attribute::IncomingRayPayload(ref payload_name) => {
661                    write!(out, "@incoming_payload({payload_name}) ")?;
662                }
663            };
664        }
665        Ok(())
666    }
667
668    /// Write `attributes` followed by a single trailing space, for use where more
669    /// content follows on the same line (e.g. before a parameter name).
670    fn write_attributes(&mut self, attributes: &[Attribute]) -> BackendResult {
671        Self::write_attributes_to(&mut self.out, attributes)
672    }
673
674    /// Write `attributes` on their own line, followed by a newline. Attributes are
675    /// rendered into a buffer first so the trailing space `write_attributes_to`
676    /// puts after the last one can be trimmed before it reaches the line.
677    fn write_attributes_line(&mut self, attributes: &[Attribute]) -> BackendResult {
678        let mut buf = String::new();
679        Self::write_attributes_to(&mut buf, attributes)?;
680        writeln!(self.out, "{}", buf.trim_end())?;
681        Ok(())
682    }
683
684    /// Helper method used to write structs
685    /// Write the full declaration of a struct type.
686    ///
687    /// Write out a definition of the struct type referred to by
688    /// `handle` in `module`. The output will be an instance of the
689    /// `struct_decl` production in the WGSL grammar.
690    ///
691    /// Use `members` as the list of `handle`'s members. (This
692    /// function is usually called after matching a `TypeInner`, so
693    /// the callers already have the members at hand.)
694    fn write_struct(
695        &mut self,
696        module: &Module,
697        handle: Handle<crate::Type>,
698        members: &[crate::StructMember],
699    ) -> BackendResult {
700        write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?;
701        write!(self.out, " {{")?;
702        writeln!(self.out)?;
703        for (index, member) in members.iter().enumerate() {
704            // The indentation is only for readability
705            write!(self.out, "{}", back::INDENT)?;
706            if let Some(ref binding) = member.binding {
707                self.write_attributes(&map_binding_to_attribute(binding))?;
708            }
709            // Write struct member name and type
710            let member_name = &self.names[&NameKey::StructMember(handle, index as u32)];
711            write!(self.out, "{member_name}: ")?;
712            self.write_type(module, member.ty)?;
713            write!(self.out, ",")?;
714            writeln!(self.out)?;
715        }
716
717        writeln!(self.out, "}}")?;
718
719        Ok(())
720    }
721
722    fn write_type(&mut self, module: &Module, ty: Handle<crate::Type>) -> BackendResult {
723        // This actually can't be factored out into a nice constructor method,
724        // because the borrow checker needs to be able to see that the borrows
725        // of `self.names` and `self.out` are disjoint.
726        let type_context = WriterTypeContext {
727            module,
728            names: &self.names,
729        };
730        type_context.write_type(ty, &mut self.out)?;
731
732        Ok(())
733    }
734
735    fn write_type_resolution(
736        &mut self,
737        module: &Module,
738        resolution: &proc::TypeResolution,
739    ) -> BackendResult {
740        // This actually can't be factored out into a nice constructor method,
741        // because the borrow checker needs to be able to see that the borrows
742        // of `self.names` and `self.out` are disjoint.
743        let type_context = WriterTypeContext {
744            module,
745            names: &self.names,
746        };
747        type_context.write_type_resolution(resolution, &mut self.out)?;
748
749        Ok(())
750    }
751
752    /// Helper method used to write statements
753    ///
754    /// # Notes
755    /// Always adds a newline
756    fn write_stmt(
757        &mut self,
758        module: &Module,
759        stmt: &crate::Statement,
760        func_ctx: &back::FunctionCtx<'_>,
761        level: back::Level,
762    ) -> BackendResult {
763        use crate::{Expression, Statement};
764
765        match *stmt {
766            Statement::Emit(ref range) => {
767                for handle in range.clone() {
768                    let info = &func_ctx.info[handle];
769                    let expr_name = if let Some(name) = func_ctx.named_expressions.get(&handle) {
770                        // Front end provides names for all variables at the start of writing.
771                        // But we write them to step by step. We need to recache them
772                        // Otherwise, we could accidentally write variable name instead of full expression.
773                        // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords.
774                        Some(self.namer.call(name))
775                    } else {
776                        let expr = &func_ctx.expressions[handle];
777                        let min_ref_count = expr.bake_ref_count();
778                        // Forcefully creating baking expressions in some cases to help with readability
779                        let required_baking_expr = match *expr {
780                            Expression::ImageLoad { .. }
781                            | Expression::ImageQuery { .. }
782                            | Expression::ImageSample { .. } => true,
783                            _ => false,
784                        };
785                        if min_ref_count <= info.ref_count || required_baking_expr {
786                            Some(Baked(handle).to_string())
787                        } else {
788                            None
789                        }
790                    };
791
792                    if let Some(name) = expr_name {
793                        write!(self.out, "{level}")?;
794                        self.start_named_expr(module, handle, func_ctx, &name)?;
795                        self.write_expr(module, handle, func_ctx)?;
796                        self.named_expressions.insert(handle, name);
797                        writeln!(self.out, ";")?;
798                    }
799                }
800            }
801            // TODO: copy-paste from glsl-out
802            Statement::If {
803                condition,
804                ref accept,
805                ref reject,
806            } => {
807                write!(self.out, "{level}")?;
808                write!(self.out, "if ")?;
809                self.write_expr(module, condition, func_ctx)?;
810                writeln!(self.out, " {{")?;
811
812                let l2 = level.next();
813                for sta in accept {
814                    // Increase indentation to help with readability
815                    self.write_stmt(module, sta, func_ctx, l2)?;
816                }
817
818                // If there are no statements in the reject block we skip writing it
819                // This is only for readability
820                if !reject.is_empty() {
821                    writeln!(self.out, "{level}}} else {{")?;
822
823                    for sta in reject {
824                        // Increase indentation to help with readability
825                        self.write_stmt(module, sta, func_ctx, l2)?;
826                    }
827                }
828
829                writeln!(self.out, "{level}}}")?
830            }
831            Statement::Return { value } => {
832                write!(self.out, "{level}")?;
833                write!(self.out, "return")?;
834                if let Some(return_value) = value {
835                    // The leading space is important
836                    write!(self.out, " ")?;
837                    self.write_expr(module, return_value, func_ctx)?;
838                }
839                writeln!(self.out, ";")?;
840            }
841            // TODO: copy-paste from glsl-out
842            Statement::Kill => {
843                write!(self.out, "{level}")?;
844                writeln!(self.out, "discard;")?
845            }
846            Statement::Store { pointer, value } => {
847                write!(self.out, "{level}")?;
848
849                let is_atomic_pointer = func_ctx
850                    .resolve_type(pointer, &module.types)
851                    .is_atomic_pointer(&module.types);
852
853                if is_atomic_pointer {
854                    write!(self.out, "atomicStore(")?;
855                    self.write_expr(module, pointer, func_ctx)?;
856                    write!(self.out, ", ")?;
857                    self.write_expr(module, value, func_ctx)?;
858                    write!(self.out, ")")?;
859                } else {
860                    self.write_expr_with_indirection(
861                        module,
862                        pointer,
863                        func_ctx,
864                        Indirection::Reference,
865                    )?;
866                    write!(self.out, " = ")?;
867                    self.write_expr(module, value, func_ctx)?;
868                }
869                writeln!(self.out, ";")?
870            }
871            Statement::Call {
872                function,
873                ref arguments,
874                result,
875            } => {
876                write!(self.out, "{level}")?;
877                if let Some(expr) = result {
878                    let name = Baked(expr).to_string();
879                    self.start_named_expr(module, expr, func_ctx, &name)?;
880                    self.named_expressions.insert(expr, name);
881                }
882                let func_name = &self.names[&NameKey::Function(function)];
883                write!(self.out, "{func_name}(")?;
884                for (index, &argument) in arguments.iter().enumerate() {
885                    if index != 0 {
886                        write!(self.out, ", ")?;
887                    }
888                    self.write_expr(module, argument, func_ctx)?;
889                }
890                writeln!(self.out, ");")?
891            }
892            Statement::Atomic {
893                pointer,
894                ref fun,
895                value,
896                result,
897            } => {
898                write!(self.out, "{level}")?;
899                if let Some(result) = result {
900                    let res_name = Baked(result).to_string();
901                    self.start_named_expr(module, result, func_ctx, &res_name)?;
902                    self.named_expressions.insert(result, res_name);
903                }
904
905                let fun_str = fun.to_wgsl();
906                write!(self.out, "atomic{fun_str}(")?;
907                self.write_expr(module, pointer, func_ctx)?;
908                if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
909                    write!(self.out, ", ")?;
910                    self.write_expr(module, cmp, func_ctx)?;
911                }
912                write!(self.out, ", ")?;
913                self.write_expr(module, value, func_ctx)?;
914                writeln!(self.out, ");")?
915            }
916            Statement::ImageAtomic {
917                image,
918                coordinate,
919                array_index,
920                ref fun,
921                value,
922            } => {
923                write!(self.out, "{level}")?;
924                let fun_str = fun.to_wgsl();
925                write!(self.out, "textureAtomic{fun_str}(")?;
926                self.write_expr(module, image, func_ctx)?;
927                write!(self.out, ", ")?;
928                self.write_expr(module, coordinate, func_ctx)?;
929                if let Some(array_index_expr) = array_index {
930                    write!(self.out, ", ")?;
931                    self.write_expr(module, array_index_expr, func_ctx)?;
932                }
933                write!(self.out, ", ")?;
934                self.write_expr(module, value, func_ctx)?;
935                writeln!(self.out, ");")?;
936            }
937            Statement::WorkGroupUniformLoad { pointer, result } => {
938                write!(self.out, "{level}")?;
939                // TODO: Obey named expressions here.
940                let res_name = Baked(result).to_string();
941                self.start_named_expr(module, result, func_ctx, &res_name)?;
942                self.named_expressions.insert(result, res_name);
943                write!(self.out, "workgroupUniformLoad(")?;
944                self.write_expr(module, pointer, func_ctx)?;
945                writeln!(self.out, ");")?;
946            }
947            Statement::ImageStore {
948                image,
949                coordinate,
950                array_index,
951                value,
952            } => {
953                write!(self.out, "{level}")?;
954                write!(self.out, "textureStore(")?;
955                self.write_expr(module, image, func_ctx)?;
956                write!(self.out, ", ")?;
957                self.write_expr(module, coordinate, func_ctx)?;
958                if let Some(array_index_expr) = array_index {
959                    write!(self.out, ", ")?;
960                    self.write_expr(module, array_index_expr, func_ctx)?;
961                }
962                write!(self.out, ", ")?;
963                self.write_expr(module, value, func_ctx)?;
964                writeln!(self.out, ");")?;
965            }
966            // TODO: copy-paste from glsl-out
967            Statement::Block(ref block) => {
968                write!(self.out, "{level}")?;
969                writeln!(self.out, "{{")?;
970                for sta in block.iter() {
971                    // Increase the indentation to help with readability
972                    self.write_stmt(module, sta, func_ctx, level.next())?
973                }
974                writeln!(self.out, "{level}}}")?
975            }
976            Statement::Switch {
977                selector,
978                ref cases,
979            } => {
980                // Start the switch
981                write!(self.out, "{level}")?;
982                write!(self.out, "switch ")?;
983                self.write_expr(module, selector, func_ctx)?;
984                writeln!(self.out, " {{")?;
985
986                let l2 = level.next();
987                let mut new_case = true;
988                for case in cases {
989                    if case.fall_through && !case.body.is_empty() {
990                        // TODO: we could do the same workaround as we did for the HLSL backend
991                        return Err(Error::Unimplemented(
992                            "fall-through switch case block".into(),
993                        ));
994                    }
995
996                    match case.value {
997                        crate::SwitchValue::I32(value) => {
998                            if new_case {
999                                write!(self.out, "{l2}case ")?;
1000                            }
1001                            write!(self.out, "{value}")?;
1002                        }
1003                        crate::SwitchValue::U32(value) => {
1004                            if new_case {
1005                                write!(self.out, "{l2}case ")?;
1006                            }
1007                            write!(self.out, "{value}u")?;
1008                        }
1009                        crate::SwitchValue::Default => {
1010                            if new_case {
1011                                if case.fall_through {
1012                                    write!(self.out, "{l2}case ")?;
1013                                } else {
1014                                    write!(self.out, "{l2}")?;
1015                                }
1016                            }
1017                            write!(self.out, "default")?;
1018                        }
1019                    }
1020
1021                    new_case = !case.fall_through;
1022
1023                    if case.fall_through {
1024                        write!(self.out, ", ")?;
1025                    } else {
1026                        writeln!(self.out, ": {{")?;
1027                    }
1028
1029                    for sta in case.body.iter() {
1030                        self.write_stmt(module, sta, func_ctx, l2.next())?;
1031                    }
1032
1033                    if !case.fall_through {
1034                        writeln!(self.out, "{l2}}}")?;
1035                    }
1036                }
1037
1038                writeln!(self.out, "{level}}}")?
1039            }
1040            Statement::Loop {
1041                ref body,
1042                ref continuing,
1043                break_if,
1044            } => {
1045                write!(self.out, "{level}")?;
1046                writeln!(self.out, "loop {{")?;
1047
1048                let l2 = level.next();
1049                for sta in body.iter() {
1050                    self.write_stmt(module, sta, func_ctx, l2)?;
1051                }
1052
1053                // The continuing is optional so we don't need to write it if
1054                // it is empty, but the `break if` counts as a continuing statement
1055                // so even if `continuing` is empty we must generate it if a
1056                // `break if` exists
1057                if !continuing.is_empty() || break_if.is_some() {
1058                    writeln!(self.out, "{l2}continuing {{")?;
1059                    for sta in continuing.iter() {
1060                        self.write_stmt(module, sta, func_ctx, l2.next())?;
1061                    }
1062
1063                    // The `break if` is always the last
1064                    // statement of the `continuing` block
1065                    if let Some(condition) = break_if {
1066                        // The trailing space is important
1067                        write!(self.out, "{}break if ", l2.next())?;
1068                        self.write_expr(module, condition, func_ctx)?;
1069                        // Close the `break if` statement
1070                        writeln!(self.out, ";")?;
1071                    }
1072
1073                    writeln!(self.out, "{l2}}}")?;
1074                }
1075
1076                writeln!(self.out, "{level}}}")?
1077            }
1078            Statement::Break => {
1079                writeln!(self.out, "{level}break;")?;
1080            }
1081            Statement::Continue => {
1082                writeln!(self.out, "{level}continue;")?;
1083            }
1084            Statement::ControlBarrier(barrier) | Statement::MemoryBarrier(barrier) => {
1085                if barrier.contains(crate::Barrier::STORAGE) {
1086                    writeln!(self.out, "{level}storageBarrier();")?;
1087                }
1088
1089                if barrier.contains(crate::Barrier::WORK_GROUP) {
1090                    writeln!(self.out, "{level}workgroupBarrier();")?;
1091                }
1092
1093                if barrier.contains(crate::Barrier::SUB_GROUP) {
1094                    writeln!(self.out, "{level}subgroupBarrier();")?;
1095                }
1096
1097                if barrier.contains(crate::Barrier::TEXTURE) {
1098                    writeln!(self.out, "{level}textureBarrier();")?;
1099                }
1100            }
1101            Statement::RayQuery { .. } => unreachable!(),
1102            Statement::SubgroupBallot { result, predicate } => {
1103                write!(self.out, "{level}")?;
1104                let res_name = Baked(result).to_string();
1105                self.start_named_expr(module, result, func_ctx, &res_name)?;
1106                self.named_expressions.insert(result, res_name);
1107
1108                write!(self.out, "subgroupBallot(")?;
1109                if let Some(predicate) = predicate {
1110                    self.write_expr(module, predicate, func_ctx)?;
1111                }
1112                writeln!(self.out, ");")?;
1113            }
1114            Statement::SubgroupCollectiveOperation {
1115                op,
1116                collective_op,
1117                argument,
1118                result,
1119            } => {
1120                write!(self.out, "{level}")?;
1121                let res_name = Baked(result).to_string();
1122                self.start_named_expr(module, result, func_ctx, &res_name)?;
1123                self.named_expressions.insert(result, res_name);
1124
1125                match (collective_op, op) {
1126                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
1127                        write!(self.out, "subgroupAll(")?
1128                    }
1129                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
1130                        write!(self.out, "subgroupAny(")?
1131                    }
1132                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
1133                        write!(self.out, "subgroupAdd(")?
1134                    }
1135                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
1136                        write!(self.out, "subgroupMul(")?
1137                    }
1138                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
1139                        write!(self.out, "subgroupMax(")?
1140                    }
1141                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
1142                        write!(self.out, "subgroupMin(")?
1143                    }
1144                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
1145                        write!(self.out, "subgroupAnd(")?
1146                    }
1147                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
1148                        write!(self.out, "subgroupOr(")?
1149                    }
1150                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
1151                        write!(self.out, "subgroupXor(")?
1152                    }
1153                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Add) => {
1154                        write!(self.out, "subgroupExclusiveAdd(")?
1155                    }
1156                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Mul) => {
1157                        write!(self.out, "subgroupExclusiveMul(")?
1158                    }
1159                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Add) => {
1160                        write!(self.out, "subgroupInclusiveAdd(")?
1161                    }
1162                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Mul) => {
1163                        write!(self.out, "subgroupInclusiveMul(")?
1164                    }
1165                    _ => unimplemented!(),
1166                }
1167                self.write_expr(module, argument, func_ctx)?;
1168                writeln!(self.out, ");")?;
1169            }
1170            Statement::SubgroupGather {
1171                mode,
1172                argument,
1173                result,
1174            } => {
1175                write!(self.out, "{level}")?;
1176                let res_name = Baked(result).to_string();
1177                self.start_named_expr(module, result, func_ctx, &res_name)?;
1178                self.named_expressions.insert(result, res_name);
1179
1180                match mode {
1181                    crate::GatherMode::BroadcastFirst => {
1182                        write!(self.out, "subgroupBroadcastFirst(")?;
1183                    }
1184                    crate::GatherMode::Broadcast(_) => {
1185                        write!(self.out, "subgroupBroadcast(")?;
1186                    }
1187                    crate::GatherMode::Shuffle(_) => {
1188                        write!(self.out, "subgroupShuffle(")?;
1189                    }
1190                    crate::GatherMode::ShuffleDown(_) => {
1191                        write!(self.out, "subgroupShuffleDown(")?;
1192                    }
1193                    crate::GatherMode::ShuffleUp(_) => {
1194                        write!(self.out, "subgroupShuffleUp(")?;
1195                    }
1196                    crate::GatherMode::ShuffleXor(_) => {
1197                        write!(self.out, "subgroupShuffleXor(")?;
1198                    }
1199                    crate::GatherMode::QuadBroadcast(_) => {
1200                        write!(self.out, "quadBroadcast(")?;
1201                    }
1202                    crate::GatherMode::QuadSwap(direction) => match direction {
1203                        crate::Direction::X => {
1204                            write!(self.out, "quadSwapX(")?;
1205                        }
1206                        crate::Direction::Y => {
1207                            write!(self.out, "quadSwapY(")?;
1208                        }
1209                        crate::Direction::Diagonal => {
1210                            write!(self.out, "quadSwapDiagonal(")?;
1211                        }
1212                    },
1213                }
1214                self.write_expr(module, argument, func_ctx)?;
1215                match mode {
1216                    crate::GatherMode::BroadcastFirst => {}
1217                    crate::GatherMode::Broadcast(index)
1218                    | crate::GatherMode::Shuffle(index)
1219                    | crate::GatherMode::ShuffleDown(index)
1220                    | crate::GatherMode::ShuffleUp(index)
1221                    | crate::GatherMode::ShuffleXor(index)
1222                    | crate::GatherMode::QuadBroadcast(index) => {
1223                        write!(self.out, ", ")?;
1224                        self.write_expr(module, index, func_ctx)?;
1225                    }
1226                    crate::GatherMode::QuadSwap(_) => {}
1227                }
1228                writeln!(self.out, ");")?;
1229            }
1230            Statement::SubgroupBallotFindBit {
1231                order,
1232                argument,
1233                result,
1234            } => {
1235                // Evaluate each ballot word once into a local, rather than
1236                // repeatedly writing `argument.x`/`.y`/`.z`/`.w` in the select
1237                // chain below.
1238                const COMPONENTS: [char; 4] = ['x', 'y', 'z', 'w'];
1239                let mut words: [String; 4] = core::array::from_fn(|_| String::new());
1240                for (word, &component) in words.iter_mut().zip(&COMPONENTS) {
1241                    write!(self.out, "{level}")?;
1242                    let name = self.namer.call("");
1243                    write!(self.out, "let {name} = ")?;
1244                    self.write_expr(module, argument, func_ctx)?;
1245                    writeln!(self.out, ".{component};")?;
1246                    *word = name;
1247                }
1248
1249                write!(self.out, "{level}")?;
1250                let res_name = Baked(result).to_string();
1251                self.start_named_expr(module, result, func_ctx, &res_name)?;
1252                self.named_expressions.insert(result, res_name);
1253
1254                self.write_ballot_find_bit(&words, order, 3)?;
1255                writeln!(self.out, ";")?;
1256            }
1257            Statement::CooperativeStore { target, ref data } => {
1258                let suffix = if data.row_major { "T" } else { "" };
1259                write!(self.out, "{level}coopStore{suffix}(")?;
1260                self.write_expr(module, target, func_ctx)?;
1261                write!(self.out, ", ")?;
1262                self.write_expr(module, data.pointer, func_ctx)?;
1263                write!(self.out, ", ")?;
1264                self.write_expr(module, data.stride, func_ctx)?;
1265                writeln!(self.out, ");")?
1266            }
1267            Statement::RayPipelineFunction(fun) => match fun {
1268                crate::RayPipelineFunction::TraceRay {
1269                    acceleration_structure,
1270                    descriptor,
1271                    payload,
1272                } => {
1273                    write!(self.out, "{level}traceRay(")?;
1274                    self.write_expr(module, acceleration_structure, func_ctx)?;
1275                    write!(self.out, ", ")?;
1276                    self.write_expr(module, descriptor, func_ctx)?;
1277                    write!(self.out, ", ")?;
1278                    self.write_expr(module, payload, func_ctx)?;
1279                    writeln!(self.out, ");")?
1280                }
1281                crate::RayPipelineFunction::ReorderThread { hint, bits } => {
1282                    write!(self.out, "{level}reorderThread(")?;
1283                    self.write_expr(module, hint, func_ctx)?;
1284                    write!(self.out, ", ")?;
1285                    self.write_expr(module, bits, func_ctx)?;
1286                    writeln!(self.out, ");")?
1287                }
1288            },
1289            Statement::HitObject { hit_object, fun } => {
1290                let name = match fun {
1291                    crate::HitObjectFunction::TraceRay { .. } => "hitObjectTraceRay",
1292                    crate::HitObjectFunction::RecordMiss { .. } => "hitObjectRecordMiss",
1293                    crate::HitObjectFunction::RecordFromQuery { .. } => "hitObjectRecordFromQuery",
1294                    crate::HitObjectFunction::RecordEmpty => "hitObjectRecordEmpty",
1295                    crate::HitObjectFunction::ExecuteShader { .. } => "hitObjectExecuteShader",
1296                    crate::HitObjectFunction::Reorder { .. } => "reorderThread",
1297                };
1298                write!(self.out, "{level}{name}(")?;
1299                self.write_expr(module, hit_object, func_ctx)?;
1300                let hint = match fun {
1301                    crate::HitObjectFunction::TraceRay {
1302                        acceleration_structure,
1303                        descriptor,
1304                        payload,
1305                    } => {
1306                        write!(self.out, ", ")?;
1307                        self.write_expr(module, acceleration_structure, func_ctx)?;
1308                        write!(self.out, ", ")?;
1309                        self.write_expr(module, descriptor, func_ctx)?;
1310                        write!(self.out, ", ")?;
1311                        self.write_expr(module, payload, func_ctx)?;
1312                        None
1313                    }
1314                    crate::HitObjectFunction::RecordMiss { descriptor } => {
1315                        write!(self.out, ", ")?;
1316                        self.write_expr(module, descriptor, func_ctx)?;
1317                        None
1318                    }
1319                    crate::HitObjectFunction::RecordFromQuery { query } => {
1320                        write!(self.out, ", ")?;
1321                        self.write_expr(module, query, func_ctx)?;
1322                        None
1323                    }
1324                    crate::HitObjectFunction::RecordEmpty => None,
1325                    crate::HitObjectFunction::ExecuteShader { payload } => {
1326                        write!(self.out, ", ")?;
1327                        self.write_expr(module, payload, func_ctx)?;
1328                        None
1329                    }
1330                    crate::HitObjectFunction::Reorder { hint } => hint,
1331                };
1332                if let Some(crate::ReorderHint { hint, bits }) = hint {
1333                    write!(self.out, ", ")?;
1334                    self.write_expr(module, hint, func_ctx)?;
1335                    write!(self.out, ", ")?;
1336                    self.write_expr(module, bits, func_ctx)?;
1337                }
1338                writeln!(self.out, ");")?
1339            }
1340            Statement::DebugPrintf {
1341                ref format,
1342                ref arguments,
1343            } => {
1344                write!(self.out, "{level}debugPrintf(\"{}\"", format)?;
1345                for &arg in arguments {
1346                    write!(self.out, ", ")?;
1347                    self.write_expr(module, arg, func_ctx)?;
1348                }
1349                writeln!(self.out, ");")?;
1350            }
1351        }
1352
1353        Ok(())
1354    }
1355
1356    /// Return the sort of indirection that `expr`'s plain form evaluates to.
1357    ///
1358    /// An expression's 'plain form' is the most general rendition of that
1359    /// expression into WGSL, lacking `&` or `*` operators:
1360    ///
1361    /// - The plain form of `LocalVariable(x)` is simply `x`, which is a reference
1362    ///   to the local variable's storage.
1363    ///
1364    /// - The plain form of `GlobalVariable(g)` is simply `g`, which is usually a
1365    ///   reference to the global variable's storage. However, globals in the
1366    ///   `Handle` address space are immutable, and `GlobalVariable` expressions for
1367    ///   those produce the value directly, not a pointer to it. Such
1368    ///   `GlobalVariable` expressions are `Ordinary`.
1369    ///
1370    /// - `Access` and `AccessIndex` are `Reference` when their `base` operand is a
1371    ///   pointer. If they are applied directly to a composite value, they are
1372    ///   `Ordinary`.
1373    ///
1374    /// Note that `FunctionArgument` expressions are never `Reference`, even when
1375    /// the argument's type is `Pointer`. `FunctionArgument` always evaluates to the
1376    /// argument's value directly, so any pointer it produces is merely the value
1377    /// passed by the caller.
1378    fn plain_form_indirection(
1379        &self,
1380        expr: Handle<crate::Expression>,
1381        module: &Module,
1382        func_ctx: &back::FunctionCtx<'_>,
1383    ) -> Indirection {
1384        use crate::Expression as Ex;
1385
1386        // Named expressions are `let` expressions, which apply the Load Rule,
1387        // so if their type is a Naga pointer, then that must be a WGSL pointer
1388        // as well.
1389        if self.named_expressions.contains_key(&expr) {
1390            return Indirection::Ordinary;
1391        }
1392
1393        match func_ctx.expressions[expr] {
1394            Ex::LocalVariable(_) => Indirection::Reference,
1395            Ex::GlobalVariable(handle) => {
1396                let global = &module.global_variables[handle];
1397                match global.space {
1398                    crate::AddressSpace::Handle => Indirection::Ordinary,
1399                    _ => Indirection::Reference,
1400                }
1401            }
1402            Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => {
1403                let base_ty = func_ctx.resolve_type(base, &module.types);
1404                match *base_ty {
1405                    TypeInner::Pointer { .. } | TypeInner::ValuePointer { .. } => {
1406                        Indirection::Reference
1407                    }
1408                    _ => Indirection::Ordinary,
1409                }
1410            }
1411            _ => Indirection::Ordinary,
1412        }
1413    }
1414
1415    fn start_named_expr(
1416        &mut self,
1417        module: &Module,
1418        handle: Handle<crate::Expression>,
1419        func_ctx: &back::FunctionCtx,
1420        name: &str,
1421    ) -> BackendResult {
1422        // Write variable name
1423        write!(self.out, "let {name}")?;
1424        if self.flags.contains(WriterFlags::EXPLICIT_TYPES) {
1425            write!(self.out, ": ")?;
1426            // Write variable type
1427            self.write_type_resolution(module, &func_ctx.info[handle].ty)?;
1428        }
1429
1430        write!(self.out, " = ")?;
1431        Ok(())
1432    }
1433
1434    /// Write a polyfill for [`Statement::SubgroupBallotFindBit`], since WGSL has no
1435    /// built-in for it: a chain of `select`s over the already-evaluated ballot
1436    /// `words` (`words[0..4]` is `x, y, z, w`). `priority` counts up from 0 (the
1437    /// lowest-priority word, used as the fallback base case) to 3 (the
1438    /// highest-priority word, checked first: `x` for LSB, `w` for MSB), each
1439    /// overriding the lower-priority result when that word has any bit set.
1440    ///
1441    /// [`Statement::SubgroupBallotFindBit`]: crate::Statement::SubgroupBallotFindBit
1442    fn write_ballot_find_bit(
1443        &mut self,
1444        words: &[String; 4],
1445        order: crate::BallotFindBitOrder,
1446        priority: u32,
1447    ) -> BackendResult {
1448        let (word_index, base) = match (order, priority) {
1449            (crate::BallotFindBitOrder::Lsb, 0) => (3, 96),
1450            (crate::BallotFindBitOrder::Lsb, 1) => (2, 64),
1451            (crate::BallotFindBitOrder::Lsb, 2) => (1, 32),
1452            (crate::BallotFindBitOrder::Lsb, 3) => (0, 0),
1453            (crate::BallotFindBitOrder::Msb, 0) => (0, 0),
1454            (crate::BallotFindBitOrder::Msb, 1) => (1, 32),
1455            (crate::BallotFindBitOrder::Msb, 2) => (2, 64),
1456            (crate::BallotFindBitOrder::Msb, 3) => (3, 96),
1457            (_, _) => unreachable!(),
1458        };
1459        let word = &words[word_index];
1460
1461        if priority == 0 {
1462            self.write_ballot_find_bit_value(order, word, base)?;
1463        } else {
1464            write!(self.out, "select(")?;
1465            self.write_ballot_find_bit(words, order, priority - 1)?;
1466            write!(self.out, ", ")?;
1467            self.write_ballot_find_bit_value(order, word, base)?;
1468            write!(self.out, ", {word} != 0u)")?;
1469        }
1470        Ok(())
1471    }
1472
1473    /// Write `firstTrailingBit`/`firstLeadingBit` applied to an already-evaluated
1474    /// ballot word, offset by that word's base invocation index. Used by
1475    /// [`Self::write_ballot_find_bit`].
1476    fn write_ballot_find_bit_value(
1477        &mut self,
1478        order: crate::BallotFindBitOrder,
1479        word: &str,
1480        base: u32,
1481    ) -> BackendResult {
1482        let math_fn = match order {
1483            crate::BallotFindBitOrder::Lsb => "firstTrailingBit",
1484            crate::BallotFindBitOrder::Msb => "firstLeadingBit",
1485        };
1486        write!(self.out, "{math_fn}({word})")?;
1487        if base != 0 {
1488            write!(self.out, " + {base}u")?;
1489        }
1490        Ok(())
1491    }
1492
1493    /// Write the ordinary WGSL form of `expr`.
1494    ///
1495    /// See `write_expr_with_indirection` for details.
1496    fn write_expr(
1497        &mut self,
1498        module: &Module,
1499        expr: Handle<crate::Expression>,
1500        func_ctx: &back::FunctionCtx<'_>,
1501    ) -> BackendResult {
1502        self.write_expr_with_indirection(module, expr, func_ctx, Indirection::Ordinary)
1503    }
1504
1505    /// Write `expr` as a WGSL expression with the requested indirection.
1506    ///
1507    /// In terms of the WGSL grammar, the resulting expression is a
1508    /// `singular_expression`. It may be parenthesized. This makes it suitable
1509    /// for use as the operand of a unary or binary operator without worrying
1510    /// about precedence.
1511    ///
1512    /// This does not produce newlines or indentation.
1513    ///
1514    /// The `requested` argument indicates (roughly) whether Naga
1515    /// `Pointer`-valued expressions represent WGSL references or pointers. See
1516    /// `Indirection` for details.
1517    fn write_expr_with_indirection(
1518        &mut self,
1519        module: &Module,
1520        expr: Handle<crate::Expression>,
1521        func_ctx: &back::FunctionCtx<'_>,
1522        requested: Indirection,
1523    ) -> BackendResult {
1524        // If the plain form of the expression is not what we need, emit the
1525        // operator necessary to correct that.
1526        let plain = self.plain_form_indirection(expr, module, func_ctx);
1527        log::trace!(
1528            "expression {:?}={:?} is {:?}, expected {:?}",
1529            expr,
1530            func_ctx.expressions[expr],
1531            plain,
1532            requested,
1533        );
1534        match (requested, plain) {
1535            (Indirection::Ordinary, Indirection::Reference) => {
1536                write!(self.out, "(&")?;
1537                self.write_expr_plain_form(module, expr, func_ctx, plain)?;
1538                write!(self.out, ")")?;
1539            }
1540            (Indirection::Reference, Indirection::Ordinary) => {
1541                write!(self.out, "(*")?;
1542                self.write_expr_plain_form(module, expr, func_ctx, plain)?;
1543                write!(self.out, ")")?;
1544            }
1545            (_, _) => self.write_expr_plain_form(module, expr, func_ctx, plain)?,
1546        }
1547
1548        Ok(())
1549    }
1550
1551    fn write_const_expression(
1552        &mut self,
1553        module: &Module,
1554        expr: Handle<crate::Expression>,
1555        arena: &crate::Arena<crate::Expression>,
1556    ) -> BackendResult {
1557        self.write_possibly_const_expression(module, expr, arena, |writer, expr| {
1558            writer.write_const_expression(module, expr, arena)
1559        })
1560    }
1561
1562    fn write_possibly_const_expression<E>(
1563        &mut self,
1564        module: &Module,
1565        expr: Handle<crate::Expression>,
1566        expressions: &crate::Arena<crate::Expression>,
1567        write_expression: E,
1568    ) -> BackendResult
1569    where
1570        E: Fn(&mut Self, Handle<crate::Expression>) -> BackendResult,
1571    {
1572        use crate::Expression;
1573
1574        match expressions[expr] {
1575            Expression::Literal(literal) => match literal {
1576                crate::Literal::F16(value) => write!(self.out, "{value}h")?,
1577                crate::Literal::F32(value) => write!(self.out, "{value}f")?,
1578                crate::Literal::U16(value) => write!(self.out, "u16({value})")?,
1579                crate::Literal::I16(value) => write!(self.out, "i16({value})")?,
1580                crate::Literal::U32(value) => write!(self.out, "{value}u")?,
1581                crate::Literal::I32(value) => {
1582                    // `-2147483648i` is not valid WGSL. The most negative `i32`
1583                    // value can only be expressed in WGSL using AbstractInt and
1584                    // a unary negation operator.
1585                    if value == i32::MIN {
1586                        write!(self.out, "i32({value})")?;
1587                    } else {
1588                        write!(self.out, "{value}i")?;
1589                    }
1590                }
1591                crate::Literal::Bool(value) => write!(self.out, "{value}")?,
1592                crate::Literal::F64(value) => write!(self.out, "{value:?}lf")?,
1593                crate::Literal::I64(value) => {
1594                    // `-9223372036854775808li` is not valid WGSL. Nor can we simply use the
1595                    // AbstractInt trick above, as AbstractInt also cannot represent
1596                    // `9223372036854775808`. Instead construct the second most negative
1597                    // AbstractInt, subtract one from it, then cast to i64.
1598                    if value == i64::MIN {
1599                        write!(self.out, "i64({} - 1)", value + 1)?;
1600                    } else {
1601                        write!(self.out, "{value}li")?;
1602                    }
1603                }
1604                crate::Literal::U64(value) => write!(self.out, "{value:?}lu")?,
1605                crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
1606                    return Err(Error::Custom(
1607                        "Abstract types should not appear in IR presented to backends".into(),
1608                    ));
1609                }
1610            },
1611            Expression::Constant(handle) => {
1612                let constant = &module.constants[handle];
1613                if constant.name.is_some() {
1614                    write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
1615                } else {
1616                    self.write_const_expression(module, constant.init, &module.global_expressions)?;
1617                }
1618            }
1619            Expression::ZeroValue(ty) => {
1620                self.write_type(module, ty)?;
1621                write!(self.out, "()")?;
1622            }
1623            Expression::Compose { ty, ref components } => {
1624                self.write_type(module, ty)?;
1625                write!(self.out, "(")?;
1626                for (index, component) in components.iter().enumerate() {
1627                    if index != 0 {
1628                        write!(self.out, ", ")?;
1629                    }
1630                    write_expression(self, *component)?;
1631                }
1632                write!(self.out, ")")?
1633            }
1634            Expression::Splat { size, value } => {
1635                let size = common::vector_size_str(size);
1636                write!(self.out, "vec{size}(")?;
1637                write_expression(self, value)?;
1638                write!(self.out, ")")?;
1639            }
1640            Expression::Override(handle) => {
1641                write!(self.out, "{}", self.names[&NameKey::Override(handle)])?;
1642            }
1643            _ => unreachable!(),
1644        }
1645
1646        Ok(())
1647    }
1648
1649    /// Write the 'plain form' of `expr`.
1650    ///
1651    /// An expression's 'plain form' is the most general rendition of that
1652    /// expression into WGSL, lacking `&` or `*` operators. The plain forms of
1653    /// `LocalVariable(x)` and `GlobalVariable(g)` are simply `x` and `g`. Such
1654    /// Naga expressions represent both WGSL pointers and references; it's the
1655    /// caller's responsibility to distinguish those cases appropriately.
1656    fn write_expr_plain_form(
1657        &mut self,
1658        module: &Module,
1659        expr: Handle<crate::Expression>,
1660        func_ctx: &back::FunctionCtx<'_>,
1661        indirection: Indirection,
1662    ) -> BackendResult {
1663        use crate::Expression;
1664
1665        if let Some(name) = self.named_expressions.get(&expr) {
1666            write!(self.out, "{name}")?;
1667            return Ok(());
1668        }
1669
1670        let expression = &func_ctx.expressions[expr];
1671
1672        // Write the plain WGSL form of a Naga expression.
1673        //
1674        // The plain form of `LocalVariable` and `GlobalVariable` expressions is
1675        // simply the variable name; `*` and `&` operators are never emitted.
1676        //
1677        // The plain form of `Access` and `AccessIndex` expressions are WGSL
1678        // `postfix_expression` forms for member/component access and
1679        // subscripting.
1680        match *expression {
1681            Expression::Literal(_)
1682            | Expression::Constant(_)
1683            | Expression::ZeroValue(_)
1684            | Expression::Compose { .. }
1685            | Expression::Splat { .. } => {
1686                self.write_possibly_const_expression(
1687                    module,
1688                    expr,
1689                    func_ctx.expressions,
1690                    |writer, expr| writer.write_expr(module, expr, func_ctx),
1691                )?;
1692            }
1693            Expression::Override(handle) => {
1694                write!(self.out, "{}", self.names[&NameKey::Override(handle)])?;
1695            }
1696            Expression::FunctionArgument(pos) => {
1697                let name_key = func_ctx.argument_key(pos);
1698                let name = &self.names[&name_key];
1699                write!(self.out, "{name}")?;
1700            }
1701            Expression::Binary { op, left, right } => {
1702                write!(self.out, "(")?;
1703                self.write_expr(module, left, func_ctx)?;
1704                write!(self.out, " {} ", back::binary_operation_str(op))?;
1705                self.write_expr(module, right, func_ctx)?;
1706                write!(self.out, ")")?;
1707            }
1708            Expression::Access { base, index } => {
1709                self.write_expr_with_indirection(module, base, func_ctx, indirection)?;
1710                write!(self.out, "[")?;
1711                self.write_expr(module, index, func_ctx)?;
1712                write!(self.out, "]")?
1713            }
1714            Expression::AccessIndex { base, index } => {
1715                let base_ty_res = &func_ctx.info[base].ty;
1716                let mut resolved = base_ty_res.inner_with(&module.types);
1717
1718                self.write_expr_with_indirection(module, base, func_ctx, indirection)?;
1719
1720                let base_ty_handle = match *resolved {
1721                    TypeInner::Pointer { base, space: _ } => {
1722                        resolved = &module.types[base].inner;
1723                        Some(base)
1724                    }
1725                    _ => base_ty_res.handle(),
1726                };
1727
1728                match *resolved {
1729                    TypeInner::Vector { .. } => {
1730                        // Write vector access as a swizzle
1731                        write!(self.out, ".{}", back::COMPONENTS[index as usize])?
1732                    }
1733                    TypeInner::Matrix { .. }
1734                    | TypeInner::Array { .. }
1735                    | TypeInner::BindingArray { .. }
1736                    | TypeInner::ValuePointer { .. } => write!(self.out, "[{index}]")?,
1737                    TypeInner::Struct { .. } => {
1738                        // This will never panic in case the type is a `Struct`, this is not true
1739                        // for other types so we can only check while inside this match arm
1740                        let ty = base_ty_handle.unwrap();
1741
1742                        write!(
1743                            self.out,
1744                            ".{}",
1745                            self.names[&NameKey::StructMember(ty, index)]
1746                        )?
1747                    }
1748                    ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))),
1749                }
1750            }
1751            Expression::ImageSample {
1752                image,
1753                sampler,
1754                gather: None,
1755                coordinate,
1756                array_index,
1757                offset,
1758                level,
1759                depth_ref,
1760                clamp_to_edge,
1761            } => {
1762                use crate::SampleLevel as Sl;
1763
1764                let suffix_cmp = match depth_ref {
1765                    Some(_) => "Compare",
1766                    None => "",
1767                };
1768                let suffix_level = match level {
1769                    Sl::Auto => "",
1770                    Sl::Zero if clamp_to_edge => "BaseClampToEdge",
1771                    Sl::Zero | Sl::Exact(_) => "Level",
1772                    Sl::Bias(_) => "Bias",
1773                    Sl::Gradient { .. } => "Grad",
1774                };
1775
1776                write!(self.out, "textureSample{suffix_cmp}{suffix_level}(")?;
1777                self.write_expr(module, image, func_ctx)?;
1778                write!(self.out, ", ")?;
1779                self.write_expr(module, sampler, func_ctx)?;
1780                write!(self.out, ", ")?;
1781                self.write_expr(module, coordinate, func_ctx)?;
1782
1783                if let Some(array_index) = array_index {
1784                    write!(self.out, ", ")?;
1785                    self.write_expr(module, array_index, func_ctx)?;
1786                }
1787
1788                if let Some(depth_ref) = depth_ref {
1789                    write!(self.out, ", ")?;
1790                    self.write_expr(module, depth_ref, func_ctx)?;
1791                }
1792
1793                match level {
1794                    Sl::Auto => {}
1795                    Sl::Zero => {
1796                        // Level 0 is implied for depth comparison and BaseClampToEdge
1797                        if depth_ref.is_none() && !clamp_to_edge {
1798                            write!(self.out, ", 0.0")?;
1799                        }
1800                    }
1801                    Sl::Exact(expr) => {
1802                        write!(self.out, ", ")?;
1803                        self.write_expr(module, expr, func_ctx)?;
1804                    }
1805                    Sl::Bias(expr) => {
1806                        write!(self.out, ", ")?;
1807                        self.write_expr(module, expr, func_ctx)?;
1808                    }
1809                    Sl::Gradient { x, y } => {
1810                        write!(self.out, ", ")?;
1811                        self.write_expr(module, x, func_ctx)?;
1812                        write!(self.out, ", ")?;
1813                        self.write_expr(module, y, func_ctx)?;
1814                    }
1815                }
1816
1817                if let Some(offset) = offset {
1818                    write!(self.out, ", ")?;
1819                    self.write_const_expression(module, offset, func_ctx.expressions)?;
1820                }
1821
1822                write!(self.out, ")")?;
1823            }
1824
1825            Expression::ImageSample {
1826                image,
1827                sampler,
1828                gather: Some(component),
1829                coordinate,
1830                array_index,
1831                offset,
1832                level: _,
1833                depth_ref,
1834                clamp_to_edge: _,
1835            } => {
1836                let suffix_cmp = match depth_ref {
1837                    Some(_) => "Compare",
1838                    None => "",
1839                };
1840
1841                write!(self.out, "textureGather{suffix_cmp}(")?;
1842                match *func_ctx.resolve_type(image, &module.types) {
1843                    TypeInner::Image {
1844                        class: crate::ImageClass::Depth { multi: _ },
1845                        ..
1846                    } => {}
1847                    _ => {
1848                        write!(self.out, "{}, ", component as u8)?;
1849                    }
1850                }
1851                self.write_expr(module, image, func_ctx)?;
1852                write!(self.out, ", ")?;
1853                self.write_expr(module, sampler, func_ctx)?;
1854                write!(self.out, ", ")?;
1855                self.write_expr(module, coordinate, func_ctx)?;
1856
1857                if let Some(array_index) = array_index {
1858                    write!(self.out, ", ")?;
1859                    self.write_expr(module, array_index, func_ctx)?;
1860                }
1861
1862                if let Some(depth_ref) = depth_ref {
1863                    write!(self.out, ", ")?;
1864                    self.write_expr(module, depth_ref, func_ctx)?;
1865                }
1866
1867                if let Some(offset) = offset {
1868                    write!(self.out, ", ")?;
1869                    self.write_const_expression(module, offset, func_ctx.expressions)?;
1870                }
1871
1872                write!(self.out, ")")?;
1873            }
1874            Expression::ImageQuery { image, query } => {
1875                use crate::ImageQuery as Iq;
1876
1877                let texture_function = match query {
1878                    Iq::Size { .. } => "textureDimensions",
1879                    Iq::NumLevels => "textureNumLevels",
1880                    Iq::NumLayers => "textureNumLayers",
1881                    Iq::NumSamples => "textureNumSamples",
1882                };
1883
1884                write!(self.out, "{texture_function}(")?;
1885                self.write_expr(module, image, func_ctx)?;
1886                if let Iq::Size { level: Some(level) } = query {
1887                    write!(self.out, ", ")?;
1888                    self.write_expr(module, level, func_ctx)?;
1889                };
1890                write!(self.out, ")")?;
1891            }
1892
1893            Expression::ImageLoad {
1894                image,
1895                coordinate,
1896                array_index,
1897                sample,
1898                level,
1899            } => {
1900                write!(self.out, "textureLoad(")?;
1901                self.write_expr(module, image, func_ctx)?;
1902                write!(self.out, ", ")?;
1903                self.write_expr(module, coordinate, func_ctx)?;
1904                if let Some(array_index) = array_index {
1905                    write!(self.out, ", ")?;
1906                    self.write_expr(module, array_index, func_ctx)?;
1907                }
1908                if let Some(index) = sample.or(level) {
1909                    write!(self.out, ", ")?;
1910                    self.write_expr(module, index, func_ctx)?;
1911                }
1912                write!(self.out, ")")?;
1913            }
1914            Expression::GlobalVariable(handle) => {
1915                let name = &self.names[&NameKey::GlobalVariable(handle)];
1916                write!(self.out, "{name}")?;
1917            }
1918
1919            Expression::As { expr, target } => {
1920                let inner = func_ctx.resolve_type(expr, &module.types);
1921                let scalar_str = target.to_wgsl_if_implemented()?;
1922                match *inner {
1923                    TypeInner::Matrix { columns, rows, .. } => write!(
1924                        self.out,
1925                        "mat{}x{}<{}>",
1926                        common::vector_size_str(columns),
1927                        common::vector_size_str(rows),
1928                        scalar_str
1929                    )?,
1930                    TypeInner::Vector { size, .. } => {
1931                        write!(
1932                            self.out,
1933                            "vec{}<{}>",
1934                            common::vector_size_str(size),
1935                            scalar_str
1936                        )?;
1937                    }
1938                    TypeInner::Scalar(_) => write!(self.out, "{scalar_str}")?,
1939                    _ => {
1940                        return Err(Error::Unimplemented(format!(
1941                            "write_expr expression::as {inner:?}"
1942                        )));
1943                    }
1944                };
1945                write!(self.out, "(")?;
1946                self.write_expr(module, expr, func_ctx)?;
1947                write!(self.out, ")")?;
1948            }
1949            Expression::Bitcast { expr, ty } => {
1950                write!(self.out, "bitcast<")?;
1951                self.write_type(module, ty)?;
1952                write!(self.out, ">(")?;
1953                self.write_expr(module, expr, func_ctx)?;
1954                write!(self.out, ")")?;
1955            }
1956            Expression::Load { pointer } => {
1957                let is_atomic_pointer = func_ctx
1958                    .resolve_type(pointer, &module.types)
1959                    .is_atomic_pointer(&module.types);
1960
1961                if is_atomic_pointer {
1962                    write!(self.out, "atomicLoad(")?;
1963                    self.write_expr(module, pointer, func_ctx)?;
1964                    write!(self.out, ")")?;
1965                } else {
1966                    self.write_expr_with_indirection(
1967                        module,
1968                        pointer,
1969                        func_ctx,
1970                        Indirection::Reference,
1971                    )?;
1972                }
1973            }
1974            Expression::LocalVariable(handle) => {
1975                write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])?
1976            }
1977            Expression::ArrayLength(expr) => {
1978                write!(self.out, "arrayLength(")?;
1979                self.write_expr(module, expr, func_ctx)?;
1980                write!(self.out, ")")?;
1981            }
1982
1983            Expression::Math {
1984                fun,
1985                arg,
1986                arg1,
1987                arg2,
1988                arg3,
1989            } => {
1990                use crate::MathFunction as Mf;
1991
1992                enum Function {
1993                    Regular(&'static str),
1994                    InversePolyfill(InversePolyfill),
1995                }
1996
1997                let function = match fun.try_to_wgsl() {
1998                    Some(name) => Function::Regular(name),
1999                    None => match fun {
2000                        Mf::Inverse => {
2001                            let ty = func_ctx.resolve_type(arg, &module.types);
2002                            let Some(overload) = InversePolyfill::find_overload(ty) else {
2003                                return Err(Error::unsupported("math function", fun));
2004                            };
2005
2006                            Function::InversePolyfill(overload)
2007                        }
2008                        _ => return Err(Error::unsupported("math function", fun)),
2009                    },
2010                };
2011
2012                match function {
2013                    Function::Regular(fun_name) => {
2014                        write!(self.out, "{fun_name}(")?;
2015                        self.write_expr(module, arg, func_ctx)?;
2016                        for arg in IntoIterator::into_iter([arg1, arg2, arg3]).flatten() {
2017                            write!(self.out, ", ")?;
2018                            self.write_expr(module, arg, func_ctx)?;
2019                        }
2020                        write!(self.out, ")")?
2021                    }
2022                    Function::InversePolyfill(inverse) => {
2023                        write!(self.out, "{}(", inverse.fun_name)?;
2024                        self.write_expr(module, arg, func_ctx)?;
2025                        write!(self.out, ")")?;
2026                        self.required_polyfills.insert(inverse);
2027                    }
2028                }
2029            }
2030
2031            Expression::Swizzle {
2032                size,
2033                vector,
2034                pattern,
2035            } => {
2036                self.write_expr(module, vector, func_ctx)?;
2037                write!(self.out, ".")?;
2038                for &sc in pattern[..size as usize].iter() {
2039                    self.out.write_char(back::COMPONENTS[sc as usize])?;
2040                }
2041            }
2042            Expression::Unary { op, expr } => {
2043                let unary = match op {
2044                    crate::UnaryOperator::Negate => "-",
2045                    crate::UnaryOperator::LogicalNot => "!",
2046                    crate::UnaryOperator::BitwiseNot => "~",
2047                };
2048
2049                write!(self.out, "{unary}(")?;
2050                self.write_expr(module, expr, func_ctx)?;
2051
2052                write!(self.out, ")")?
2053            }
2054
2055            Expression::Select {
2056                condition,
2057                accept,
2058                reject,
2059            } => {
2060                write!(self.out, "select(")?;
2061                self.write_expr(module, reject, func_ctx)?;
2062                write!(self.out, ", ")?;
2063                self.write_expr(module, accept, func_ctx)?;
2064                write!(self.out, ", ")?;
2065                self.write_expr(module, condition, func_ctx)?;
2066                write!(self.out, ")")?
2067            }
2068            Expression::Derivative { axis, ctrl, expr } => {
2069                use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
2070                let op = match (axis, ctrl) {
2071                    (Axis::X, Ctrl::Coarse) => "dpdxCoarse",
2072                    (Axis::X, Ctrl::Fine) => "dpdxFine",
2073                    (Axis::X, Ctrl::None) => "dpdx",
2074                    (Axis::Y, Ctrl::Coarse) => "dpdyCoarse",
2075                    (Axis::Y, Ctrl::Fine) => "dpdyFine",
2076                    (Axis::Y, Ctrl::None) => "dpdy",
2077                    (Axis::Width, Ctrl::Coarse) => "fwidthCoarse",
2078                    (Axis::Width, Ctrl::Fine) => "fwidthFine",
2079                    (Axis::Width, Ctrl::None) => "fwidth",
2080                };
2081                write!(self.out, "{op}(")?;
2082                self.write_expr(module, expr, func_ctx)?;
2083                write!(self.out, ")")?
2084            }
2085            Expression::Relational { fun, argument } => {
2086                use crate::RelationalFunction as Rf;
2087
2088                let fun_name = match fun {
2089                    Rf::All => "all",
2090                    Rf::Any => "any",
2091                    _ => return Err(Error::UnsupportedRelationalFunction(fun)),
2092                };
2093                write!(self.out, "{fun_name}(")?;
2094
2095                self.write_expr(module, argument, func_ctx)?;
2096
2097                write!(self.out, ")")?
2098            }
2099            Expression::HitObjectQuery { hit_object, query } => {
2100                let name = match query {
2101                    crate::HitObjectQuery::IsEmpty => "hitObjectIsEmpty",
2102                    crate::HitObjectQuery::IsHit => "hitObjectIsHit",
2103                    crate::HitObjectQuery::IsMiss => "hitObjectIsMiss",
2104                    crate::HitObjectQuery::Intersection => "hitObjectGetIntersection",
2105                };
2106                write!(self.out, "{name}(")?;
2107                self.write_expr(module, hit_object, func_ctx)?;
2108                write!(self.out, ")")?
2109            }
2110            // Not supported yet
2111            Expression::RayQueryGetIntersection { .. }
2112            | Expression::RayQueryVertexPositions { .. } => unreachable!(),
2113            // Nothing to do here, since call expression already cached
2114            Expression::CallResult(_)
2115            | Expression::AtomicResult { .. }
2116            | Expression::RayQueryProceedResult
2117            | Expression::SubgroupBallotResult
2118            | Expression::SubgroupOperationResult { .. }
2119            | Expression::WorkGroupUniformLoadResult { .. } => {}
2120            Expression::CooperativeLoad {
2121                columns,
2122                rows,
2123                role,
2124                ref data,
2125            } => {
2126                let suffix = if data.row_major { "T" } else { "" };
2127                let scalar = func_ctx.info[data.pointer]
2128                    .ty
2129                    .inner_with(&module.types)
2130                    .pointer_base_type()
2131                    .unwrap()
2132                    .inner_with(&module.types)
2133                    .scalar()
2134                    .unwrap();
2135                write!(
2136                    self.out,
2137                    "coopLoad{suffix}<coop_mat{}x{}<{},{:?}>>(",
2138                    columns as u32,
2139                    rows as u32,
2140                    scalar.try_to_wgsl().unwrap(),
2141                    role,
2142                )?;
2143                self.write_expr(module, data.pointer, func_ctx)?;
2144                write!(self.out, ", ")?;
2145                self.write_expr(module, data.stride, func_ctx)?;
2146                write!(self.out, ")")?;
2147            }
2148            Expression::CooperativeMultiplyAdd { a, b, c } => {
2149                write!(self.out, "coopMultiplyAdd(")?;
2150                self.write_expr(module, a, func_ctx)?;
2151                write!(self.out, ", ")?;
2152                self.write_expr(module, b, func_ctx)?;
2153                write!(self.out, ", ")?;
2154                self.write_expr(module, c, func_ctx)?;
2155                write!(self.out, ")")?;
2156            }
2157        }
2158
2159        Ok(())
2160    }
2161
2162    /// Helper method used to write global variables
2163    /// # Notes
2164    /// Always adds a newline
2165    fn write_global(
2166        &mut self,
2167        module: &Module,
2168        global: &crate::GlobalVariable,
2169        handle: Handle<crate::GlobalVariable>,
2170    ) -> BackendResult {
2171        // Write group and binding attributes if present
2172        if let Some(ref binding) = global.binding {
2173            self.write_attributes_line(&[
2174                Attribute::Group(binding.group),
2175                Attribute::Binding(binding.binding),
2176            ])?;
2177        }
2178
2179        if global
2180            .memory_decorations
2181            .contains(crate::MemoryDecorations::COHERENT)
2182        {
2183            write!(self.out, "@coherent ")?;
2184        }
2185        if global
2186            .memory_decorations
2187            .contains(crate::MemoryDecorations::VOLATILE)
2188        {
2189            write!(self.out, "@volatile ")?;
2190        }
2191
2192        // First write global name and address space if supported
2193        write!(self.out, "var")?;
2194        let (address, maybe_access) = address_space_str(global.space);
2195        if let Some(space) = address {
2196            write!(self.out, "<{space}")?;
2197            if let Some(access) = maybe_access {
2198                write!(self.out, ", {access}")?;
2199            }
2200            write!(self.out, ">")?;
2201        }
2202        write!(
2203            self.out,
2204            " {}: ",
2205            self.names[&NameKey::GlobalVariable(handle)]
2206        )?;
2207
2208        // Write global type
2209        self.write_type(module, global.ty)?;
2210
2211        // Write initializer
2212        if let Some(init) = global.init {
2213            write!(self.out, " = ")?;
2214            self.write_const_expression(module, init, &module.global_expressions)?;
2215        }
2216
2217        // End with semicolon
2218        writeln!(self.out, ";")?;
2219
2220        Ok(())
2221    }
2222
2223    /// Helper method used to write global constants
2224    ///
2225    /// # Notes
2226    /// Ends in a newline
2227    fn write_global_constant(
2228        &mut self,
2229        module: &Module,
2230        handle: Handle<crate::Constant>,
2231    ) -> BackendResult {
2232        let name = &self.names[&NameKey::Constant(handle)];
2233        // First write only constant name
2234        write!(self.out, "const {name}: ")?;
2235        self.write_type(module, module.constants[handle].ty)?;
2236        write!(self.out, " = ")?;
2237        let init = module.constants[handle].init;
2238        self.write_const_expression(module, init, &module.global_expressions)?;
2239        writeln!(self.out, ";")?;
2240
2241        Ok(())
2242    }
2243
2244    /// Helper method used to write overrides
2245    ///
2246    /// # Notes
2247    /// Ends in a newline
2248    fn write_override(
2249        &mut self,
2250        module: &Module,
2251        handle: Handle<crate::Override>,
2252    ) -> BackendResult {
2253        let override_ = &module.overrides[handle];
2254        let name = &self.names[&NameKey::Override(handle)];
2255
2256        // Write @id attribute if present
2257        if let Some(id) = override_.id {
2258            write!(self.out, "@id({id}) ")?;
2259        }
2260
2261        // Write override declaration
2262        write!(self.out, "override {name}: ")?;
2263        self.write_type(module, override_.ty)?;
2264
2265        // Write initializer if present
2266        if let Some(init) = override_.init {
2267            write!(self.out, " = ")?;
2268            self.write_const_expression(module, init, &module.global_expressions)?;
2269        }
2270
2271        writeln!(self.out, ";")?;
2272
2273        Ok(())
2274    }
2275
2276    // See https://github.com/rust-lang/rust-clippy/issues/4979.
2277    pub fn finish(self) -> W {
2278        self.out
2279    }
2280}
2281
2282struct WriterTypeContext<'m> {
2283    module: &'m Module,
2284    names: &'m crate::FastHashMap<NameKey, String>,
2285}
2286
2287impl TypeContext for WriterTypeContext<'_> {
2288    fn lookup_type(&self, handle: Handle<crate::Type>) -> &crate::Type {
2289        &self.module.types[handle]
2290    }
2291
2292    fn type_name(&self, handle: Handle<crate::Type>) -> &str {
2293        self.names[&NameKey::Type(handle)].as_str()
2294    }
2295
2296    fn write_unnamed_struct<W: Write>(&self, _: &TypeInner, _: &mut W) -> core::fmt::Result {
2297        unreachable!("the WGSL back end should always provide type handles");
2298    }
2299
2300    fn write_override<W: Write>(
2301        &self,
2302        handle: Handle<crate::Override>,
2303        out: &mut W,
2304    ) -> core::fmt::Result {
2305        write!(out, "{}", self.names[&NameKey::Override(handle)])
2306    }
2307
2308    fn write_non_wgsl_inner<W: Write>(&self, _: &TypeInner, _: &mut W) -> core::fmt::Result {
2309        unreachable!("backends should only be passed validated modules");
2310    }
2311
2312    fn write_non_wgsl_scalar<W: Write>(&self, _: crate::Scalar, _: &mut W) -> core::fmt::Result {
2313        unreachable!("backends should only be passed validated modules");
2314    }
2315}
2316
2317fn map_binding_to_attribute(binding: &crate::Binding) -> Vec<Attribute> {
2318    match *binding {
2319        crate::Binding::BuiltIn(built_in) => {
2320            if let crate::BuiltIn::Position { invariant: true } = built_in {
2321                vec![Attribute::BuiltIn(built_in), Attribute::Invariant]
2322            } else {
2323                vec![Attribute::BuiltIn(built_in)]
2324            }
2325        }
2326        crate::Binding::Location {
2327            location,
2328            interpolation,
2329            sampling,
2330            blend_src: None,
2331            per_primitive,
2332        } => {
2333            let mut attrs = vec![
2334                Attribute::Location(location),
2335                Attribute::Interpolate(interpolation, sampling),
2336            ];
2337            if per_primitive {
2338                attrs.push(Attribute::PerPrimitive);
2339            }
2340            attrs
2341        }
2342        crate::Binding::Location {
2343            location,
2344            interpolation,
2345            sampling,
2346            blend_src: Some(blend_src),
2347            per_primitive,
2348        } => {
2349            let mut attrs = vec![
2350                Attribute::Location(location),
2351                Attribute::BlendSrc(blend_src),
2352                Attribute::Interpolate(interpolation, sampling),
2353            ];
2354            if per_primitive {
2355                attrs.push(Attribute::PerPrimitive);
2356            }
2357            attrs
2358        }
2359    }
2360}