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