Skip to main content

naga/back/glsl/
writer.rs

1use super::*;
2
3/// Writer responsible for all code generation.
4#[expect(missing_debug_implementations, reason = "would be way too verbose?")]
5pub struct Writer<'a, W> {
6    // Inputs
7    /// The module being written.
8    pub(in crate::back::glsl) module: &'a crate::Module,
9    /// The module analysis.
10    pub(in crate::back::glsl) info: &'a valid::ModuleInfo,
11    /// The output writer.
12    out: W,
13    /// User defined configuration to be used.
14    pub(in crate::back::glsl) options: &'a Options,
15    /// The bound checking policies to be used
16    pub(in crate::back::glsl) policies: proc::BoundsCheckPolicies,
17
18    // Internal State
19    /// Features manager used to store all the needed features and write them.
20    pub(in crate::back::glsl) features: FeaturesManager,
21    namer: proc::Namer,
22    /// A map with all the names needed for writing the module
23    /// (generated by a [`Namer`](crate::proc::Namer)).
24    names: crate::FastHashMap<NameKey, String>,
25    /// A map with the names of global variables needed for reflections.
26    reflection_names_globals: crate::FastHashMap<Handle<crate::GlobalVariable>, String>,
27    /// The selected entry point.
28    pub(in crate::back::glsl) entry_point: &'a crate::EntryPoint,
29    /// The index of the selected entry point.
30    pub(in crate::back::glsl) entry_point_idx: proc::EntryPointIndex,
31    /// A generator for unique block numbers.
32    block_id: IdGenerator,
33    /// Set of expressions that have associated temporary variables.
34    named_expressions: crate::NamedExpressions,
35    /// Set of expressions that need to be baked to avoid unnecessary repetition in output
36    need_bake_expressions: back::NeedBakeExpressions,
37    /// Information about nesting of loops and switches.
38    ///
39    /// Used for forwarding continue statements in switches that have been
40    /// transformed to `do {} while(false);` loops.
41    continue_ctx: back::continue_forward::ContinueCtx,
42    /// How many views to render to, if doing multiview rendering.
43    pub(in crate::back::glsl) multiview: Option<core::num::NonZeroU32>,
44    /// Mapping of varying variables to their location. Needed for reflections.
45    varying: crate::FastHashMap<String, VaryingLocation>,
46    /// Number of user-defined clip planes. Only non-zero for vertex shaders.
47    clip_distance_count: u32,
48}
49
50impl<'a, W: Write> Writer<'a, W> {
51    /// Creates a new [`Writer`] instance.
52    ///
53    /// # Errors
54    /// - If the version specified is invalid or supported.
55    /// - If the entry point couldn't be found in the module.
56    /// - If the version specified doesn't support some used features.
57    pub fn new(
58        out: W,
59        module: &'a crate::Module,
60        info: &'a valid::ModuleInfo,
61        options: &'a Options,
62        pipeline_options: &'a PipelineOptions,
63        policies: proc::BoundsCheckPolicies,
64    ) -> Result<Self, Error> {
65        // Check if the requested version is supported
66        if !options.version.is_supported() {
67            log::error!("Version {}", options.version);
68            return Err(Error::VersionNotSupported);
69        }
70
71        // Try to find the entry point and corresponding index
72        let ep_idx = module
73            .entry_points
74            .iter()
75            .position(|ep| {
76                pipeline_options.shader_stage == ep.stage && pipeline_options.entry_point == ep.name
77            })
78            .ok_or(Error::EntryPointNotFound)?;
79
80        // Generate a map with names required to write the module
81        let mut names = crate::FastHashMap::default();
82        let mut namer = proc::Namer::default();
83        namer.reset(
84            module,
85            &keywords::RESERVED_KEYWORD_SET,
86            proc::KeywordSet::empty(),
87            proc::CaseInsensitiveKeywordSet::empty(),
88            &[
89                "gl_",                  // all GL built-in variables
90                "_group",               // all normal bindings
91                "_immediates_binding_", // all immediate data bindings
92            ],
93            &mut names,
94        );
95
96        // Build the instance
97        let mut this = Self {
98            module,
99            info,
100            out,
101            options,
102            policies,
103
104            namer,
105            features: FeaturesManager::new(),
106            names,
107            reflection_names_globals: crate::FastHashMap::default(),
108            entry_point: &module.entry_points[ep_idx],
109            entry_point_idx: ep_idx as u16,
110            multiview: pipeline_options.multiview,
111            block_id: IdGenerator::default(),
112            named_expressions: Default::default(),
113            need_bake_expressions: Default::default(),
114            continue_ctx: back::continue_forward::ContinueCtx::default(),
115            varying: Default::default(),
116            clip_distance_count: 0,
117        };
118
119        // Find all features required to print this module
120        this.collect_required_features()?;
121
122        Ok(this)
123    }
124
125    /// Writes the [`Module`](crate::Module) as glsl to the output
126    ///
127    /// # Notes
128    /// If an error occurs while writing, the output might have been written partially
129    ///
130    /// # Panics
131    /// Might panic if the module is invalid
132    pub fn write(&mut self) -> Result<ReflectionInfo, Error> {
133        // We use `writeln!(self.out)` throughout the write to add newlines
134        // to make the output more readable
135
136        let es = self.options.version.is_es();
137
138        // Write the version (It must be the first thing or it isn't a valid glsl output)
139        writeln!(self.out, "#version {}", self.options.version)?;
140        // Write all the needed extensions
141        //
142        // This used to be the last thing being written as it allowed to search for features while
143        // writing the module saving some loops but some older versions (420 or less) required the
144        // extensions to appear before being used, even though extensions are part of the
145        // preprocessor not the processor ¯\_(ツ)_/¯
146        self.features.write(self.options, &mut self.out)?;
147
148        // glsl es requires a precision to be specified for floats and ints
149        // TODO: Should this be user configurable?
150        if es {
151            writeln!(self.out)?;
152            writeln!(self.out, "precision highp float;")?;
153            writeln!(self.out, "precision highp int;")?;
154            writeln!(self.out)?;
155        }
156
157        if self.entry_point.stage == ShaderStage::Compute {
158            let workgroup_size = self.entry_point.workgroup_size;
159            writeln!(
160                self.out,
161                "layout(local_size_x = {}, local_size_y = {}, local_size_z = {}) in;",
162                workgroup_size[0], workgroup_size[1], workgroup_size[2]
163            )?;
164            writeln!(self.out)?;
165        }
166
167        if self.entry_point.stage == ShaderStage::Vertex
168            && !self
169                .options
170                .writer_flags
171                .contains(WriterFlags::DRAW_PARAMETERS)
172            && self.features.contains(Features::INSTANCE_INDEX)
173        {
174            writeln!(self.out, "uniform uint {FIRST_INSTANCE_BINDING};")?;
175            writeln!(self.out)?;
176        }
177
178        // Enable early depth tests if needed
179        if let Some(early_depth_test) = self.entry_point.early_depth_test {
180            // If early depth test is supported for this version of GLSL
181            if self.options.version.supports_early_depth_test() {
182                match early_depth_test {
183                    crate::EarlyDepthTest::Force => {
184                        writeln!(self.out, "layout(early_fragment_tests) in;")?;
185                    }
186                    crate::EarlyDepthTest::Allow { conservative, .. } => {
187                        use crate::ConservativeDepth as Cd;
188                        let depth = match conservative {
189                            Cd::GreaterEqual => "greater",
190                            Cd::LessEqual => "less",
191                            Cd::Unchanged => "unchanged",
192                        };
193                        writeln!(self.out, "layout (depth_{depth}) out float gl_FragDepth;")?;
194                    }
195                }
196            } else {
197                log::warn!(
198                    "Early depth testing is not supported for this version of GLSL: {}",
199                    self.options.version
200                );
201            }
202        }
203
204        if self.entry_point.stage == ShaderStage::Vertex && self.options.version.is_webgl() {
205            if let Some(multiview) = self.multiview.as_ref() {
206                writeln!(self.out, "layout(num_views = {multiview}) in;")?;
207                writeln!(self.out)?;
208            }
209        }
210
211        // Write struct types.
212        //
213        // This are always ordered because the IR is structured in a way that
214        // you can't make a struct without adding all of its members first.
215        for (handle, ty) in self.module.types.iter() {
216            if let TypeInner::Struct { ref members, .. } = ty.inner {
217                let struct_name = &self.names[&NameKey::Type(handle)];
218
219                // Structures ending with runtime-sized arrays can only be
220                // rendered as shader storage blocks in GLSL, not stand-alone
221                // struct types.
222                if !self.module.types[members.last().unwrap().ty]
223                    .inner
224                    .is_dynamically_sized(&self.module.types)
225                {
226                    write!(self.out, "struct {struct_name} ")?;
227                    self.write_struct_body(handle, members)?;
228                    writeln!(self.out, ";")?;
229                }
230            }
231        }
232
233        // Write functions for special types.
234        for (type_key, struct_ty) in self.module.special_types.predeclared_types.iter() {
235            match type_key {
236                &crate::PredeclaredType::ModfResult { size, scalar }
237                | &crate::PredeclaredType::FrexpResult { size, scalar } => {
238                    let struct_name = &self.names[&NameKey::Type(*struct_ty)];
239                    let arg_type_name_owner;
240                    let arg_type_name = if let Some(size) = size {
241                        arg_type_name_owner = format!(
242                            "{}vec{}",
243                            if scalar.width == 8 { "d" } else { "" },
244                            size as u8
245                        );
246                        &arg_type_name_owner
247                    } else if scalar.width == 8 {
248                        "double"
249                    } else {
250                        "float"
251                    };
252
253                    let other_type_name_owner;
254                    let (defined_func_name, called_func_name, other_type_name) =
255                        if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) {
256                            (MODF_FUNCTION, "modf", arg_type_name)
257                        } else {
258                            let other_type_name = if let Some(size) = size {
259                                other_type_name_owner = format!("ivec{}", size as u8);
260                                &other_type_name_owner
261                            } else {
262                                "int"
263                            };
264                            (FREXP_FUNCTION, "frexp", other_type_name)
265                        };
266
267                    writeln!(self.out)?;
268                    if !self.options.version.supports_frexp_function()
269                        && matches!(type_key, &crate::PredeclaredType::FrexpResult { .. })
270                    {
271                        writeln!(
272                            self.out,
273                            "{struct_name} {defined_func_name}({arg_type_name} arg) {{
274    {other_type_name} other = arg == {arg_type_name}(0) ? {other_type_name}(0) : {other_type_name}({arg_type_name}(1) + log2(arg));
275    {arg_type_name} fract = arg * exp2({arg_type_name}(-other));
276    return {struct_name}(fract, other);
277}}",
278                        )?;
279                    } else {
280                        writeln!(
281                            self.out,
282                            "{struct_name} {defined_func_name}({arg_type_name} arg) {{
283    {other_type_name} other;
284    {arg_type_name} fract = {called_func_name}(arg, other);
285    return {struct_name}(fract, other);
286}}",
287                        )?;
288                    }
289                }
290                &crate::PredeclaredType::AtomicCompareExchangeWeakResult(_) => {
291                    // Handled by the general struct writing loop earlier.
292                }
293            }
294        }
295
296        // Write all named constants
297        let mut constants = self
298            .module
299            .constants
300            .iter()
301            .filter(|&(_, c)| c.name.is_some())
302            .peekable();
303        while let Some((handle, _)) = constants.next() {
304            self.write_global_constant(handle)?;
305            // Add extra newline for readability on last iteration
306            if constants.peek().is_none() {
307                writeln!(self.out)?;
308            }
309        }
310
311        let ep_info = self.info.get_entry_point(self.entry_point_idx as usize);
312
313        // Write the globals
314        //
315        // Unless explicitly disabled with WriterFlags::INCLUDE_UNUSED_ITEMS,
316        // we filter all globals that aren't used by the selected entry point as they might be
317        // interfere with each other (i.e. two globals with the same location but different with
318        // different classes)
319        let include_unused = self
320            .options
321            .writer_flags
322            .contains(WriterFlags::INCLUDE_UNUSED_ITEMS);
323        for (handle, global) in self.module.global_variables.iter() {
324            let is_unused = ep_info[handle].is_empty();
325            if !include_unused && is_unused {
326                continue;
327            }
328
329            match self.module.types[global.ty].inner {
330                // We treat images separately because they might require
331                // writing the storage format
332                TypeInner::Image {
333                    mut dim,
334                    arrayed,
335                    class,
336                } => {
337                    // Gather the storage format if needed
338                    let storage_format_access = match self.module.types[global.ty].inner {
339                        TypeInner::Image {
340                            class: crate::ImageClass::Storage { format, access },
341                            ..
342                        } => Some((format, access)),
343                        _ => None,
344                    };
345
346                    if dim == crate::ImageDimension::D1 && es {
347                        dim = crate::ImageDimension::D2
348                    }
349
350                    // Gether the location if needed
351                    let layout_binding = if self.options.version.supports_explicit_locations() {
352                        let br = global.binding.as_ref().unwrap();
353                        self.options.binding_map.get(br).cloned()
354                    } else {
355                        None
356                    };
357
358                    // Write all the layout qualifiers
359                    if layout_binding.is_some() || storage_format_access.is_some() {
360                        write!(self.out, "layout(")?;
361                        if let Some(binding) = layout_binding {
362                            write!(self.out, "binding = {binding}")?;
363                        }
364                        if let Some((format, _)) = storage_format_access {
365                            let format_str = glsl_storage_format(format)?;
366                            let separator = match layout_binding {
367                                Some(_) => ",",
368                                None => "",
369                            };
370                            write!(self.out, "{separator}{format_str}")?;
371                        }
372                        write!(self.out, ") ")?;
373                    }
374
375                    if let Some((_, access)) = storage_format_access {
376                        self.write_storage_access(access)?;
377                    }
378
379                    // All images in glsl are `uniform`
380                    // The trailing space is important
381                    write!(self.out, "uniform ")?;
382
383                    // write the type
384                    //
385                    // This is way we need the leading space because `write_image_type` doesn't add
386                    // any spaces at the beginning or end
387                    self.write_image_type(dim, arrayed, class)?;
388
389                    // Finally write the name and end the global with a `;`
390                    // The leading space is important
391                    let global_name = self.get_global_name(handle, global);
392                    writeln!(self.out, " {global_name};")?;
393                    writeln!(self.out)?;
394
395                    self.reflection_names_globals.insert(handle, global_name);
396                }
397                // glsl has no concept of samplers so we just ignore it
398                TypeInner::Sampler { .. } => continue,
399                // All other globals are written by `write_global`
400                _ => {
401                    self.write_global(handle, global)?;
402                    // Add a newline (only for readability)
403                    writeln!(self.out)?;
404                }
405            }
406        }
407
408        for arg in self.entry_point.function.arguments.iter() {
409            self.write_varying(arg.binding.as_ref(), arg.ty, false)?;
410        }
411        if let Some(ref result) = self.entry_point.function.result {
412            self.write_varying(result.binding.as_ref(), result.ty, true)?;
413        }
414        writeln!(self.out)?;
415
416        // Write all regular functions
417        for (handle, function) in self.module.functions.iter() {
418            // Check that the function doesn't use globals that aren't supported
419            // by the current entry point
420            if !include_unused && !ep_info.dominates_global_use(&self.info[handle]) {
421                continue;
422            }
423
424            let fun_info = &self.info[handle];
425
426            // Skip functions that that are not compatible with this entry point's stage.
427            //
428            // When validation is enabled, it rejects modules whose entry points try to call
429            // incompatible functions, so if we got this far, then any functions incompatible
430            // with our selected entry point must not be used.
431            //
432            // When validation is disabled, `fun_info.available_stages` is always just
433            // `ShaderStages::all()`, so this will write all functions in the module, and
434            // the downstream GLSL compiler will catch any problems.
435            if !fun_info.available_stages.contains(ep_info.available_stages) {
436                continue;
437            }
438
439            // Write the function
440            self.write_function(back::FunctionType::Function(handle), function, fun_info)?;
441
442            writeln!(self.out)?;
443        }
444
445        self.write_function(
446            back::FunctionType::EntryPoint(self.entry_point_idx),
447            &self.entry_point.function,
448            ep_info,
449        )?;
450
451        // Add newline at the end of file
452        writeln!(self.out)?;
453
454        // Collect all reflection info and return it to the user
455        self.collect_reflection_info()
456    }
457
458    fn write_array_size(
459        &mut self,
460        base: Handle<crate::Type>,
461        size: crate::ArraySize,
462    ) -> BackendResult {
463        write!(self.out, "[")?;
464
465        // Write the array size
466        // Writes nothing if `IndexableLength::Dynamic`
467        match size.resolve(self.module.to_ctx())? {
468            proc::IndexableLength::Known(size) => {
469                write!(self.out, "{size}")?;
470            }
471            proc::IndexableLength::Dynamic => (),
472        }
473
474        write!(self.out, "]")?;
475
476        if let TypeInner::Array {
477            base: next_base,
478            size: next_size,
479            ..
480        } = self.module.types[base].inner
481        {
482            self.write_array_size(next_base, next_size)?;
483        }
484
485        Ok(())
486    }
487
488    /// Helper method used to write value types
489    ///
490    /// # Notes
491    /// Adds no trailing or leading whitespace
492    fn write_value_type(&mut self, inner: &TypeInner) -> BackendResult {
493        match *inner {
494            // Scalars are simple we just get the full name from `glsl_scalar`
495            TypeInner::Scalar(scalar)
496            | TypeInner::Atomic(scalar)
497            | TypeInner::ValuePointer {
498                size: None,
499                scalar,
500                space: _,
501            } => write!(self.out, "{}", glsl_scalar(scalar)?.full)?,
502            // Vectors are just `gvecN` where `g` is the scalar prefix and `N` is the vector size
503            TypeInner::Vector { size, scalar }
504            | TypeInner::ValuePointer {
505                size: Some(size),
506                scalar,
507                space: _,
508            } => write!(self.out, "{}vec{}", glsl_scalar(scalar)?.prefix, size as u8)?,
509            // Matrices are written with `gmatMxN` where `g` is the scalar prefix (only floats and
510            // doubles are allowed), `M` is the columns count and `N` is the rows count
511            //
512            // glsl supports a matrix shorthand `gmatN` where `N` = `M` but it doesn't justify the
513            // extra branch to write matrices this way
514            TypeInner::Matrix {
515                columns,
516                rows,
517                scalar,
518            } => write!(
519                self.out,
520                "{}mat{}x{}",
521                glsl_scalar(scalar)?.prefix,
522                columns as u8,
523                rows as u8
524            )?,
525            // GLSL arrays are written as `type name[size]`
526            // Here we only write the size of the array i.e. `[size]`
527            // Base `type` and `name` should be written outside
528            TypeInner::Array { base, size, .. } => self.write_array_size(base, size)?,
529            // Write all variants instead of `_` so that if new variants are added a
530            // no exhaustiveness error is thrown
531            TypeInner::Pointer { .. }
532            | TypeInner::Struct { .. }
533            | TypeInner::Image { .. }
534            | TypeInner::Sampler { .. }
535            | TypeInner::AccelerationStructure { .. }
536            | TypeInner::RayQuery { .. }
537            | TypeInner::HitObject
538            | TypeInner::BindingArray { .. }
539            | TypeInner::CooperativeMatrix { .. } => {
540                return Err(Error::Custom(format!("Unable to write type {inner:?}")))
541            }
542        }
543
544        Ok(())
545    }
546
547    /// Helper method used to write non image/sampler types
548    ///
549    /// # Notes
550    /// Adds no trailing or leading whitespace
551    fn write_type(&mut self, ty: Handle<crate::Type>) -> BackendResult {
552        match self.module.types[ty].inner {
553            // glsl has no pointer types so just write types as normal and loads are skipped
554            TypeInner::Pointer { base, .. } => self.write_type(base),
555            // glsl structs are written as just the struct name
556            TypeInner::Struct { .. } => {
557                // Get the struct name
558                let name = &self.names[&NameKey::Type(ty)];
559                write!(self.out, "{name}")?;
560                Ok(())
561            }
562            // glsl array has the size separated from the base type
563            TypeInner::Array { base, .. } => self.write_type(base),
564            ref other => self.write_value_type(other),
565        }
566    }
567
568    /// Helper method to write a image type
569    ///
570    /// # Notes
571    /// Adds no leading or trailing whitespace
572    fn write_image_type(
573        &mut self,
574        dim: crate::ImageDimension,
575        arrayed: bool,
576        class: crate::ImageClass,
577    ) -> BackendResult {
578        // glsl images consist of four parts the scalar prefix, the image "type", the dimensions
579        // and modifiers
580        //
581        // There exists two image types
582        // - sampler - for sampled images
583        // - image - for storage images
584        //
585        // There are three possible modifiers that can be used together and must be written in
586        // this order to be valid
587        // - MS - used if it's a multisampled image
588        // - Array - used if it's an image array
589        // - Shadow - used if it's a depth image
590        use crate::ImageClass as Ic;
591        use crate::Scalar as S;
592        let float = S {
593            kind: crate::ScalarKind::Float,
594            width: 4,
595        };
596        let (base, scalar, ms, comparison) = match class {
597            Ic::Sampled { kind, multi: true } => ("sampler", S { kind, width: 4 }, "MS", ""),
598            Ic::Sampled { kind, multi: false } => ("sampler", S { kind, width: 4 }, "", ""),
599            Ic::Depth { multi: true } => ("sampler", float, "MS", ""),
600            Ic::Depth { multi: false } => ("sampler", float, "", "Shadow"),
601            Ic::Storage { format, .. } => ("image", format.into(), "", ""),
602            Ic::External => unimplemented!(),
603        };
604
605        let precision = if self.options.version.is_es() {
606            "highp "
607        } else {
608            ""
609        };
610
611        write!(
612            self.out,
613            "{}{}{}{}{}{}{}",
614            precision,
615            glsl_scalar(scalar)?.prefix,
616            base,
617            glsl_dimension(dim),
618            ms,
619            if arrayed { "Array" } else { "" },
620            comparison
621        )?;
622
623        Ok(())
624    }
625
626    /// Helper method used by [Self::write_global] to write just the layout part of
627    /// a non image/sampler global variable, if applicable.
628    ///
629    /// # Notes
630    ///
631    /// Adds trailing whitespace if any layout qualifier is written
632    fn write_global_layout(&mut self, global: &crate::GlobalVariable) -> BackendResult {
633        // Determine which (if any) explicit memory layout to use, and whether we support it
634        let layout = match global.space {
635            crate::AddressSpace::Uniform => {
636                if !self.options.version.supports_std140_layout() {
637                    return Err(Error::Custom(
638                        "Uniform address space requires std140 layout support".to_string(),
639                    ));
640                }
641
642                Some("std140")
643            }
644            crate::AddressSpace::Storage { .. } => {
645                if !self.options.version.supports_std430_layout() {
646                    return Err(Error::Custom(
647                        "Storage address space requires std430 layout support".to_string(),
648                    ));
649                }
650
651                Some("std430")
652            }
653            _ => None,
654        };
655
656        // If our version supports explicit layouts, we can also output the explicit binding
657        // if we have it
658        if self.options.version.supports_explicit_locations() {
659            if let Some(ref br) = global.binding {
660                match self.options.binding_map.get(br) {
661                    Some(binding) => {
662                        write!(self.out, "layout(")?;
663
664                        if let Some(layout) = layout {
665                            write!(self.out, "{layout}, ")?;
666                        }
667
668                        write!(self.out, "binding = {binding}) ")?;
669
670                        return Ok(());
671                    }
672                    None => {
673                        log::debug!("unassigned binding for {:?}", global.name);
674                    }
675                }
676            }
677        }
678
679        // Either no explicit bindings are supported or we didn't have any.
680        // Write just the memory layout.
681        if let Some(layout) = layout {
682            write!(self.out, "layout({layout}) ")?;
683        }
684
685        Ok(())
686    }
687
688    /// Helper method used to write non images/sampler globals
689    ///
690    /// # Notes
691    /// Adds a newline
692    ///
693    /// # Panics
694    /// If the global has type sampler
695    fn write_global(
696        &mut self,
697        handle: Handle<crate::GlobalVariable>,
698        global: &crate::GlobalVariable,
699    ) -> BackendResult {
700        self.write_global_layout(global)?;
701
702        if let crate::AddressSpace::Storage { access } = global.space {
703            self.write_storage_access(access)?;
704            if global
705                .memory_decorations
706                .contains(crate::MemoryDecorations::COHERENT)
707            {
708                write!(self.out, "coherent ")?;
709            }
710            if global
711                .memory_decorations
712                .contains(crate::MemoryDecorations::VOLATILE)
713            {
714                write!(self.out, "volatile ")?;
715            }
716        }
717
718        if let Some(storage_qualifier) = glsl_storage_qualifier(global.space) {
719            write!(self.out, "{storage_qualifier} ")?;
720        }
721
722        match global.space {
723            crate::AddressSpace::Private => {
724                self.write_simple_global(handle, global)?;
725            }
726            crate::AddressSpace::WorkGroup => {
727                self.write_simple_global(handle, global)?;
728            }
729            crate::AddressSpace::Immediate => {
730                self.write_simple_global(handle, global)?;
731            }
732            crate::AddressSpace::Uniform => {
733                self.write_interface_block(handle, global)?;
734            }
735            crate::AddressSpace::Storage { .. } => {
736                self.write_interface_block(handle, global)?;
737            }
738            crate::AddressSpace::TaskPayload => {
739                self.write_interface_block(handle, global)?;
740            }
741            // A global variable in the `Function` address space is a
742            // contradiction in terms.
743            crate::AddressSpace::Function => unreachable!(),
744            // Textures and samplers are handled directly in `Writer::write`.
745            crate::AddressSpace::Handle => unreachable!(),
746            // ray tracing pipelines unsupported
747            crate::AddressSpace::RayPayload | crate::AddressSpace::IncomingRayPayload => {
748                unreachable!()
749            }
750        }
751
752        Ok(())
753    }
754
755    fn write_simple_global(
756        &mut self,
757        handle: Handle<crate::GlobalVariable>,
758        global: &crate::GlobalVariable,
759    ) -> BackendResult {
760        self.write_type(global.ty)?;
761        write!(self.out, " ")?;
762        self.write_global_name(handle, global)?;
763
764        if let TypeInner::Array { base, size, .. } = self.module.types[global.ty].inner {
765            self.write_array_size(base, size)?;
766        }
767
768        if global.space.initializable() && is_value_init_supported(self.module, global.ty) {
769            write!(self.out, " = ")?;
770            if let Some(init) = global.init {
771                self.write_const_expr(init, &self.module.global_expressions)?;
772            } else {
773                self.write_zero_init_value(global.ty)?;
774            }
775        }
776
777        writeln!(self.out, ";")?;
778
779        if let crate::AddressSpace::Immediate = global.space {
780            let global_name = self.get_global_name(handle, global);
781            self.reflection_names_globals.insert(handle, global_name);
782        }
783
784        Ok(())
785    }
786
787    /// Write an interface block for a single Naga global.
788    ///
789    /// Write `block_name { members }`. Since `block_name` must be unique
790    /// between blocks and structs, we add `_block_ID` where `ID` is a
791    /// `IdGenerator` generated number. Write `members` in the same way we write
792    /// a struct's members.
793    fn write_interface_block(
794        &mut self,
795        handle: Handle<crate::GlobalVariable>,
796        global: &crate::GlobalVariable,
797    ) -> BackendResult {
798        // Write the block name, it's just the struct name appended with `_block_ID`
799        let ty_name = &self.names[&NameKey::Type(global.ty)];
800        let block_name = format!(
801            "{}_block_{}{:?}",
802            // avoid double underscores as they are reserved in GLSL
803            ty_name.trim_end_matches('_'),
804            self.block_id.generate(),
805            self.entry_point.stage,
806        );
807        write!(self.out, "{block_name} ")?;
808        self.reflection_names_globals.insert(handle, block_name);
809
810        match self.module.types[global.ty].inner {
811            TypeInner::Struct { ref members, .. }
812                if self.module.types[members.last().unwrap().ty]
813                    .inner
814                    .is_dynamically_sized(&self.module.types) =>
815            {
816                // Structs with dynamically sized arrays must have their
817                // members lifted up as members of the interface block. GLSL
818                // can't write such struct types anyway.
819                self.write_struct_body(global.ty, members)?;
820                write!(self.out, " ")?;
821                self.write_global_name(handle, global)?;
822            }
823            _ => {
824                // A global of any other type is written as the sole member
825                // of the interface block. Since the interface block is
826                // anonymous, this becomes visible in the global scope.
827                write!(self.out, "{{ ")?;
828                self.write_type(global.ty)?;
829                write!(self.out, " ")?;
830                self.write_global_name(handle, global)?;
831                if let TypeInner::Array { base, size, .. } = self.module.types[global.ty].inner {
832                    self.write_array_size(base, size)?;
833                }
834                write!(self.out, "; }}")?;
835            }
836        }
837
838        writeln!(self.out, ";")?;
839
840        Ok(())
841    }
842
843    /// Helper method used to find which expressions of a given function require baking
844    ///
845    /// # Notes
846    /// Clears `need_bake_expressions` set before adding to it
847    fn update_expressions_to_bake(&mut self, func: &crate::Function, info: &valid::FunctionInfo) {
848        use crate::Expression;
849        self.need_bake_expressions.clear();
850        for (fun_handle, expr) in func.expressions.iter() {
851            let expr_info = &info[fun_handle];
852            let min_ref_count = func.expressions[fun_handle].bake_ref_count();
853            if min_ref_count <= expr_info.ref_count {
854                self.need_bake_expressions.insert(fun_handle);
855            }
856
857            let inner = expr_info.ty.inner_with(&self.module.types);
858
859            if let Expression::Math {
860                fun,
861                arg,
862                arg1,
863                arg2,
864                ..
865            } = *expr
866            {
867                match fun {
868                    crate::MathFunction::Dot => {
869                        // if the expression is a Dot product with integer arguments,
870                        // then the args needs baking as well
871                        if let TypeInner::Scalar(crate::Scalar {
872                            kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
873                            ..
874                        }) = *inner
875                        {
876                            self.need_bake_expressions.insert(arg);
877                            self.need_bake_expressions.insert(arg1.unwrap());
878                        }
879                    }
880                    crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => {
881                        self.need_bake_expressions.insert(arg);
882                        self.need_bake_expressions.insert(arg1.unwrap());
883                    }
884                    crate::MathFunction::Pack4xI8
885                    | crate::MathFunction::Pack4xU8
886                    | crate::MathFunction::Pack4xI8Clamp
887                    | crate::MathFunction::Pack4xU8Clamp
888                    | crate::MathFunction::Unpack4xI8
889                    | crate::MathFunction::Unpack4xU8
890                    | crate::MathFunction::QuantizeToF16 => {
891                        self.need_bake_expressions.insert(arg);
892                    }
893                    /* crate::MathFunction::Pack4x8unorm | */
894                    crate::MathFunction::Unpack4x8snorm
895                        if !self.options.version.supports_pack_unpack_4x8() =>
896                    {
897                        // We have a fallback if the platform doesn't natively support these
898                        self.need_bake_expressions.insert(arg);
899                    }
900                    /* crate::MathFunction::Pack4x8unorm | */
901                    crate::MathFunction::Unpack4x8unorm
902                        if !self.options.version.supports_pack_unpack_4x8() =>
903                    {
904                        self.need_bake_expressions.insert(arg);
905                    }
906                    /* crate::MathFunction::Pack2x16snorm |  */
907                    crate::MathFunction::Unpack2x16snorm
908                        if !self.options.version.supports_pack_unpack_snorm_2x16() =>
909                    {
910                        self.need_bake_expressions.insert(arg);
911                    }
912                    /* crate::MathFunction::Pack2x16unorm | */
913                    crate::MathFunction::Unpack2x16unorm
914                        if !self.options.version.supports_pack_unpack_unorm_2x16() =>
915                    {
916                        self.need_bake_expressions.insert(arg);
917                    }
918                    crate::MathFunction::ExtractBits => {
919                        // Only argument 1 is re-used.
920                        self.need_bake_expressions.insert(arg1.unwrap());
921                    }
922                    crate::MathFunction::InsertBits => {
923                        // Only argument 2 is re-used.
924                        self.need_bake_expressions.insert(arg2.unwrap());
925                    }
926                    crate::MathFunction::CountLeadingZeros => {
927                        if let Some(crate::ScalarKind::Sint) = inner.scalar_kind() {
928                            self.need_bake_expressions.insert(arg);
929                        }
930                    }
931                    _ => {}
932                }
933            }
934
935            if let Expression::Binary {
936                op: crate::BinaryOperator::Modulo,
937                left,
938                right,
939            } = *expr
940            {
941                // Integer `%` is lowered to `left - right * (left / right)` in
942                // write_expr (`BinaryOperation::ModuloInt`), which references each
943                // operand twice, so bake both to avoid re-evaluating them.
944                if let Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint) = inner.scalar_kind()
945                {
946                    self.need_bake_expressions.insert(left);
947                    self.need_bake_expressions.insert(right);
948                }
949            }
950
951            if let Expression::Select {
952                condition,
953                accept,
954                reject,
955            } = *expr
956            {
957                // Componentwise `select` below names each operand once per component.
958                if !self.options.version.supports_integer_mix()
959                    && !matches!(inner.scalar_kind(), Some(crate::ScalarKind::Float))
960                {
961                    let cond_inner = info[condition].ty.inner_with(&self.module.types);
962                    if let TypeInner::Vector { .. } = *cond_inner {
963                        self.need_bake_expressions.insert(condition);
964                        self.need_bake_expressions.insert(accept);
965                        self.need_bake_expressions.insert(reject);
966                    }
967                }
968            }
969        }
970
971        for statement in func.body.iter() {
972            match *statement {
973                crate::Statement::Atomic {
974                    fun: crate::AtomicFunction::Exchange { compare: Some(cmp) },
975                    ..
976                } => {
977                    self.need_bake_expressions.insert(cmp);
978                }
979                _ => {}
980            }
981        }
982    }
983
984    /// Helper method used to get a name for a global
985    ///
986    /// Globals have different naming schemes depending on their binding:
987    /// - Globals without bindings use the name from the [`Namer`](crate::proc::Namer)
988    /// - Globals with resource binding are named `_group_X_binding_Y` where `X`
989    ///   is the group and `Y` is the binding
990    fn get_global_name(
991        &self,
992        handle: Handle<crate::GlobalVariable>,
993        global: &crate::GlobalVariable,
994    ) -> String {
995        match (&global.binding, global.space) {
996            (&Some(ref br), _) => {
997                format!(
998                    "_group_{}_binding_{}_{}",
999                    br.group,
1000                    br.binding,
1001                    shader_stage_to_str(self.entry_point.stage)
1002                )
1003            }
1004            (&None, crate::AddressSpace::Immediate) => {
1005                format!(
1006                    "_immediates_binding_{}",
1007                    shader_stage_to_str(self.entry_point.stage)
1008                )
1009            }
1010            (&None, _) => self.names[&NameKey::GlobalVariable(handle)].clone(),
1011        }
1012    }
1013
1014    /// Helper method used to write a name for a global without additional heap allocation
1015    fn write_global_name(
1016        &mut self,
1017        handle: Handle<crate::GlobalVariable>,
1018        global: &crate::GlobalVariable,
1019    ) -> BackendResult {
1020        match (&global.binding, global.space) {
1021            (&Some(ref br), _) => write!(
1022                self.out,
1023                "_group_{}_binding_{}_{}",
1024                br.group,
1025                br.binding,
1026                shader_stage_to_str(self.entry_point.stage)
1027            )?,
1028            (&None, crate::AddressSpace::Immediate) => write!(
1029                self.out,
1030                "_immediates_binding_{}",
1031                shader_stage_to_str(self.entry_point.stage)
1032            )?,
1033            (&None, _) => write!(self.out, "{}", self.names[&NameKey::GlobalVariable(handle)])?,
1034        }
1035
1036        Ok(())
1037    }
1038
1039    /// Write a GLSL global that will carry a Naga entry point's argument or return value.
1040    ///
1041    /// A Naga entry point's arguments and return value are rendered in GLSL as
1042    /// variables at global scope with the `in` and `out` storage qualifiers.
1043    /// The code we generate for `main` loads from all the `in` globals into
1044    /// appropriately named locals. Before it returns, `main` assigns the
1045    /// components of its return value into all the `out` globals.
1046    ///
1047    /// This function writes a declaration for one such GLSL global,
1048    /// representing a value passed into or returned from [`self.entry_point`]
1049    /// that has a [`Location`] binding. The global's name is generated based on
1050    /// the location index and the shader stages being connected; see
1051    /// [`VaryingName`]. This means we don't need to know the names of
1052    /// arguments, just their types and bindings.
1053    ///
1054    /// Emit nothing for entry point arguments or return values with [`BuiltIn`]
1055    /// bindings; `main` will read from or assign to the appropriate GLSL
1056    /// special variable; these are pre-declared. As an exception, we do declare
1057    /// `gl_Position` or `gl_FragCoord` with the `invariant` qualifier if
1058    /// needed.
1059    ///
1060    /// Use `output` together with [`self.entry_point.stage`] to determine which
1061    /// shader stages are being connected, and choose the `in` or `out` storage
1062    /// qualifier.
1063    ///
1064    /// [`self.entry_point`]: Writer::entry_point
1065    /// [`self.entry_point.stage`]: crate::EntryPoint::stage
1066    /// [`Location`]: crate::Binding::Location
1067    /// [`BuiltIn`]: crate::Binding::BuiltIn
1068    fn write_varying(
1069        &mut self,
1070        binding: Option<&crate::Binding>,
1071        ty: Handle<crate::Type>,
1072        output: bool,
1073    ) -> Result<(), Error> {
1074        // For a struct, emit a separate global for each member with a binding.
1075        if let TypeInner::Struct { ref members, .. } = self.module.types[ty].inner {
1076            for member in members {
1077                self.write_varying(member.binding.as_ref(), member.ty, output)?;
1078            }
1079            return Ok(());
1080        }
1081
1082        let binding = match binding {
1083            None => return Ok(()),
1084            Some(binding) => binding,
1085        };
1086
1087        let (location, interpolation, sampling, blend_src) = match *binding {
1088            crate::Binding::Location {
1089                location,
1090                interpolation,
1091                sampling,
1092                blend_src,
1093                per_primitive: _,
1094            } => (location, interpolation, sampling, blend_src),
1095            crate::Binding::BuiltIn(built_in) => {
1096                match built_in {
1097                    crate::BuiltIn::Position { invariant: true } => {
1098                        match (self.options.version, self.entry_point.stage) {
1099                            (Version::Embedded { .. }, ShaderStage::Fragment) => {
1100                                // `invariant gl_FragCoord` is illegal in all OpenGL ES versions:
1101                                // `invariant` may only qualify writable variables, and
1102                                // `gl_FragCoord` is read-only in the fragment stage
1103                                // (GLSL ES 3.00 spec §4.6.1, same language through 3.20).
1104                                //
1105                                // See https://github.com/KhronosGroup/WebGL/issues/3518
1106                            }
1107                            _ => {
1108                                writeln!(
1109                                    self.out,
1110                                    "invariant {};",
1111                                    glsl_built_in(
1112                                        built_in,
1113                                        VaryingOptions::from_writer_options(self.options, output)
1114                                    )
1115                                )?;
1116                            }
1117                        }
1118                    }
1119                    crate::BuiltIn::ClipDistances => {
1120                        // Re-declare `gl_ClipDistance` with number of clip planes.
1121                        let TypeInner::Array { size, .. } = self.module.types[ty].inner else {
1122                            unreachable!();
1123                        };
1124                        let proc::IndexableLength::Known(size) =
1125                            size.resolve(self.module.to_ctx())?
1126                        else {
1127                            unreachable!();
1128                        };
1129                        self.clip_distance_count = size;
1130                        writeln!(self.out, "out float gl_ClipDistance[{size}];")?;
1131                    }
1132                    _ => {}
1133                }
1134                return Ok(());
1135            }
1136        };
1137
1138        // Write the interpolation modifier if needed
1139        //
1140        // We ignore all interpolation and auxiliary modifiers that aren't used in fragment
1141        // shaders' input globals or vertex shaders' output globals.
1142        let emit_interpolation_and_auxiliary = match self.entry_point.stage {
1143            ShaderStage::Vertex => output,
1144            ShaderStage::Fragment => !output,
1145            ShaderStage::Compute => false,
1146            ShaderStage::Task
1147            | ShaderStage::Mesh
1148            | ShaderStage::RayGeneration
1149            | ShaderStage::AnyHit
1150            | ShaderStage::ClosestHit
1151            | ShaderStage::Miss => unreachable!(),
1152        };
1153
1154        // Write the I/O locations, if allowed
1155        let io_location = if self.options.version.supports_explicit_locations()
1156            || !emit_interpolation_and_auxiliary
1157        {
1158            if self.options.version.supports_io_locations() {
1159                if let Some(blend_src) = blend_src {
1160                    write!(
1161                        self.out,
1162                        "layout(location = {location}, index = {blend_src}) "
1163                    )?;
1164                } else {
1165                    write!(self.out, "layout(location = {location}) ")?;
1166                }
1167                None
1168            } else {
1169                Some(VaryingLocation {
1170                    location,
1171                    index: blend_src.unwrap_or(0),
1172                })
1173            }
1174        } else {
1175            None
1176        };
1177
1178        // Write the interpolation qualifier.
1179        if let Some(interp) = interpolation {
1180            if emit_interpolation_and_auxiliary {
1181                write!(self.out, "{} ", glsl_interpolation(interp))?;
1182            }
1183        }
1184
1185        // Write the sampling auxiliary qualifier.
1186        //
1187        // Before GLSL 4.2, the `centroid` and `sample` qualifiers were required to appear
1188        // immediately before the `in` / `out` qualifier, so we'll just follow that rule
1189        // here, regardless of the version.
1190        if let Some(sampling) = sampling {
1191            if emit_interpolation_and_auxiliary {
1192                if let Some(qualifier) = glsl_sampling(sampling)? {
1193                    write!(self.out, "{qualifier} ")?;
1194                }
1195            }
1196        }
1197
1198        // Write the input/output qualifier.
1199        write!(self.out, "{} ", if output { "out" } else { "in" })?;
1200
1201        // Write the type
1202        // `write_type` adds no leading or trailing spaces
1203        self.write_type(ty)?;
1204
1205        // Finally write the global name and end the global with a `;` and a newline
1206        // Leading space is important
1207        let vname = VaryingName {
1208            binding: &crate::Binding::Location {
1209                location,
1210                interpolation: None,
1211                sampling: None,
1212                blend_src,
1213                per_primitive: false,
1214            },
1215            stage: self.entry_point.stage,
1216            options: VaryingOptions::from_writer_options(self.options, output),
1217        };
1218        writeln!(self.out, " {vname};")?;
1219
1220        if let Some(location) = io_location {
1221            self.varying.insert(vname.to_string(), location);
1222        }
1223
1224        Ok(())
1225    }
1226
1227    /// Helper method used to write functions (both entry points and regular functions)
1228    ///
1229    /// # Notes
1230    /// Adds a newline
1231    fn write_function(
1232        &mut self,
1233        ty: back::FunctionType,
1234        func: &crate::Function,
1235        info: &valid::FunctionInfo,
1236    ) -> BackendResult {
1237        // Create a function context for the function being written
1238        let ctx = back::FunctionCtx {
1239            ty,
1240            info,
1241            expressions: &func.expressions,
1242            named_expressions: &func.named_expressions,
1243        };
1244
1245        self.named_expressions.clear();
1246        self.update_expressions_to_bake(func, info);
1247
1248        // Write the function header
1249        //
1250        // glsl headers are the same as in c:
1251        // `ret_type name(args)`
1252        // `ret_type` is the return type
1253        // `name` is the function name
1254        // `args` is a comma separated list of `type name`
1255        //  | - `type` is the argument type
1256        //  | - `name` is the argument name
1257
1258        // Start by writing the return type if any otherwise write void
1259        // This is the only place where `void` is a valid type
1260        // (though it's more a keyword than a type)
1261        if let back::FunctionType::EntryPoint(_) = ctx.ty {
1262            write!(self.out, "void")?;
1263        } else if let Some(ref result) = func.result {
1264            self.write_type(result.ty)?;
1265            if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner {
1266                self.write_array_size(base, size)?
1267            }
1268        } else {
1269            write!(self.out, "void")?;
1270        }
1271
1272        // Write the function name and open parentheses for the argument list
1273        let function_name = match ctx.ty {
1274            back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)],
1275            back::FunctionType::EntryPoint(_) => "main",
1276        };
1277        write!(self.out, " {function_name}(")?;
1278
1279        // Write the comma separated argument list
1280        //
1281        // We need access to `Self` here so we use the reference passed to the closure as an
1282        // argument instead of capturing as that would cause a borrow checker error
1283        let arguments = match ctx.ty {
1284            back::FunctionType::EntryPoint(_) => &[][..],
1285            back::FunctionType::Function(_) => &func.arguments,
1286        };
1287        let arguments: Vec<_> = arguments
1288            .iter()
1289            .enumerate()
1290            .filter(|&(_, arg)| match self.module.types[arg.ty].inner {
1291                TypeInner::Sampler { .. } => false,
1292                _ => true,
1293            })
1294            .collect();
1295        self.write_slice(&arguments, |this, _, &(i, arg)| {
1296            // Write the argument type
1297            match this.module.types[arg.ty].inner {
1298                // We treat images separately because they might require
1299                // writing the storage format
1300                TypeInner::Image {
1301                    dim,
1302                    arrayed,
1303                    class,
1304                } => {
1305                    // Write the storage format if needed
1306                    if let TypeInner::Image {
1307                        class: crate::ImageClass::Storage { format, .. },
1308                        ..
1309                    } = this.module.types[arg.ty].inner
1310                    {
1311                        write!(this.out, "layout({}) ", glsl_storage_format(format)?)?;
1312                    }
1313
1314                    // write the type
1315                    //
1316                    // This is way we need the leading space because `write_image_type` doesn't add
1317                    // any spaces at the beginning or end
1318                    this.write_image_type(dim, arrayed, class)?;
1319                }
1320                TypeInner::Pointer { base, .. } => {
1321                    // write parameter qualifiers
1322                    write!(this.out, "inout ")?;
1323                    this.write_type(base)?;
1324                }
1325                // All other types are written by `write_type`
1326                _ => {
1327                    this.write_type(arg.ty)?;
1328                }
1329            }
1330
1331            // Write the argument name
1332            // The leading space is important
1333            write!(this.out, " {}", this.names[&ctx.argument_key(i as u32)])?;
1334
1335            // Write array size
1336            match this.module.types[arg.ty].inner {
1337                TypeInner::Array { base, size, .. } => {
1338                    this.write_array_size(base, size)?;
1339                }
1340                TypeInner::Pointer { base, .. } => {
1341                    if let TypeInner::Array { base, size, .. } = this.module.types[base].inner {
1342                        this.write_array_size(base, size)?;
1343                    }
1344                }
1345                _ => {}
1346            }
1347
1348            Ok(())
1349        })?;
1350
1351        // Close the parentheses and open braces to start the function body
1352        writeln!(self.out, ") {{")?;
1353
1354        if self.options.zero_initialize_workgroup_memory
1355            && ctx.ty.is_compute_like_entry_point(self.module)
1356        {
1357            self.write_workgroup_variables_initialization(&ctx)?;
1358        }
1359
1360        // Compose the function arguments from globals, in case of an entry point.
1361        if let back::FunctionType::EntryPoint(ep_index) = ctx.ty {
1362            let stage = self.module.entry_points[ep_index as usize].stage;
1363            for (index, arg) in func.arguments.iter().enumerate() {
1364                write!(self.out, "{}", back::INDENT)?;
1365                self.write_type(arg.ty)?;
1366                let name = &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)];
1367                write!(self.out, " {name}")?;
1368                write!(self.out, " = ")?;
1369                match self.module.types[arg.ty].inner {
1370                    TypeInner::Struct { ref members, .. } => {
1371                        self.write_type(arg.ty)?;
1372                        write!(self.out, "(")?;
1373                        for (index, member) in members.iter().enumerate() {
1374                            let varying_name = VaryingName {
1375                                binding: member.binding.as_ref().unwrap(),
1376                                stage,
1377                                options: VaryingOptions::from_writer_options(self.options, false),
1378                            };
1379                            if index != 0 {
1380                                write!(self.out, ", ")?;
1381                            }
1382                            write!(self.out, "{varying_name}")?;
1383                        }
1384                        writeln!(self.out, ");")?;
1385                    }
1386                    _ => {
1387                        let varying_name = VaryingName {
1388                            binding: arg.binding.as_ref().unwrap(),
1389                            stage,
1390                            options: VaryingOptions::from_writer_options(self.options, false),
1391                        };
1392                        writeln!(self.out, "{varying_name};")?;
1393                    }
1394                }
1395            }
1396        }
1397
1398        // Write all function locals
1399        // Locals are `type name (= init)?;` where the init part (including the =) are optional
1400        //
1401        // Always adds a newline
1402        for (handle, local) in func.local_variables.iter() {
1403            // Write indentation (only for readability) and the type
1404            // `write_type` adds no trailing space
1405            write!(self.out, "{}", back::INDENT)?;
1406            self.write_type(local.ty)?;
1407
1408            // Write the local name
1409            // The leading space is important
1410            write!(self.out, " {}", self.names[&ctx.name_key(handle)])?;
1411            // Write size for array type
1412            if let TypeInner::Array { base, size, .. } = self.module.types[local.ty].inner {
1413                self.write_array_size(base, size)?;
1414            }
1415            // Write the local initializer if needed
1416            if let Some(init) = local.init {
1417                // Put the equal signal only if there's a initializer
1418                // The leading and trailing spaces aren't needed but help with readability
1419                write!(self.out, " = ")?;
1420
1421                // Write the constant
1422                // `write_constant` adds no trailing or leading space/newline
1423                self.write_expr(init, &ctx)?;
1424            } else if is_value_init_supported(self.module, local.ty) {
1425                write!(self.out, " = ")?;
1426                self.write_zero_init_value(local.ty)?;
1427            }
1428
1429            // Finish the local with `;` and add a newline (only for readability)
1430            writeln!(self.out, ";")?
1431        }
1432
1433        // Write the function body (statement list)
1434        for sta in func.body.iter() {
1435            // Write a statement, the indentation should always be 1 when writing the function body
1436            // `write_stmt` adds a newline
1437            self.write_stmt(sta, &ctx, back::Level(1))?;
1438        }
1439
1440        // Close braces and add a newline
1441        writeln!(self.out, "}}")?;
1442
1443        Ok(())
1444    }
1445
1446    fn write_workgroup_variables_initialization(
1447        &mut self,
1448        ctx: &back::FunctionCtx,
1449    ) -> BackendResult {
1450        let mut vars = self
1451            .module
1452            .global_variables
1453            .iter()
1454            .filter(|&(handle, var)| {
1455                !ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
1456            })
1457            .peekable();
1458
1459        if vars.peek().is_some() {
1460            let level = back::Level(1);
1461
1462            writeln!(self.out, "{level}if (gl_LocalInvocationID == uvec3(0u)) {{")?;
1463
1464            for (handle, var) in vars {
1465                let name = &self.names[&NameKey::GlobalVariable(handle)];
1466                write!(self.out, "{}{} = ", level.next(), name)?;
1467                self.write_zero_init_value(var.ty)?;
1468                writeln!(self.out, ";")?;
1469            }
1470
1471            writeln!(self.out, "{level}}}")?;
1472            self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
1473        }
1474
1475        Ok(())
1476    }
1477
1478    /// Write a list of comma separated `T` values using a writer function `F`.
1479    ///
1480    /// The writer function `F` receives a mutable reference to `self` that if needed won't cause
1481    /// borrow checker issues (using for example a closure with `self` will cause issues), the
1482    /// second argument is the 0 based index of the element on the list, and the last element is
1483    /// a reference to the element `T` being written
1484    ///
1485    /// # Notes
1486    /// - Adds no newlines or leading/trailing whitespace
1487    /// - The last element won't have a trailing `,`
1488    fn write_slice<T, F: FnMut(&mut Self, u32, &T) -> BackendResult>(
1489        &mut self,
1490        data: &[T],
1491        mut f: F,
1492    ) -> BackendResult {
1493        // Loop through `data` invoking `f` for each element
1494        for (index, item) in data.iter().enumerate() {
1495            if index != 0 {
1496                write!(self.out, ", ")?;
1497            }
1498            f(self, index as u32, item)?;
1499        }
1500
1501        Ok(())
1502    }
1503
1504    /// Helper method used to write global constants
1505    fn write_global_constant(&mut self, handle: Handle<crate::Constant>) -> BackendResult {
1506        write!(self.out, "const ")?;
1507        let constant = &self.module.constants[handle];
1508        self.write_type(constant.ty)?;
1509        let name = &self.names[&NameKey::Constant(handle)];
1510        write!(self.out, " {name}")?;
1511        if let TypeInner::Array { base, size, .. } = self.module.types[constant.ty].inner {
1512            self.write_array_size(base, size)?;
1513        }
1514        write!(self.out, " = ")?;
1515        self.write_const_expr(constant.init, &self.module.global_expressions)?;
1516        writeln!(self.out, ";")?;
1517        Ok(())
1518    }
1519
1520    /// Helper method used to output a dot product as an arithmetic expression
1521    ///
1522    fn write_dot_product(
1523        &mut self,
1524        arg: Handle<crate::Expression>,
1525        arg1: Handle<crate::Expression>,
1526        size: usize,
1527        ctx: &back::FunctionCtx,
1528    ) -> BackendResult {
1529        // Write parentheses around the dot product expression to prevent operators
1530        // with different precedences from applying earlier.
1531        write!(self.out, "(")?;
1532
1533        // Cycle through all the components of the vector
1534        for index in 0..size {
1535            let component = back::COMPONENTS[index];
1536            // Write the addition to the previous product
1537            // This will print an extra '+' at the beginning but that is fine in glsl
1538            write!(self.out, " + ")?;
1539            // Write the first vector expression, this expression is marked to be
1540            // cached so unless it can't be cached (for example, it's a Constant)
1541            // it shouldn't produce large expressions.
1542            self.write_expr(arg, ctx)?;
1543            // Access the current component on the first vector
1544            write!(self.out, ".{component} * ")?;
1545            // Write the second vector expression, this expression is marked to be
1546            // cached so unless it can't be cached (for example, it's a Constant)
1547            // it shouldn't produce large expressions.
1548            self.write_expr(arg1, ctx)?;
1549            // Access the current component on the second vector
1550            write!(self.out, ".{component}")?;
1551        }
1552
1553        write!(self.out, ")")?;
1554        Ok(())
1555    }
1556
1557    /// Helper method used to write structs
1558    ///
1559    /// # Notes
1560    /// Ends in a newline
1561    fn write_struct_body(
1562        &mut self,
1563        handle: Handle<crate::Type>,
1564        members: &[crate::StructMember],
1565    ) -> BackendResult {
1566        // glsl structs are written as in C
1567        // `struct name() { members };`
1568        //  | `struct` is a keyword
1569        //  | `name` is the struct name
1570        //  | `members` is a semicolon separated list of `type name`
1571        //      | `type` is the member type
1572        //      | `name` is the member name
1573        writeln!(self.out, "{{")?;
1574
1575        for (idx, member) in members.iter().enumerate() {
1576            // The indentation is only for readability
1577            write!(self.out, "{}", back::INDENT)?;
1578
1579            match self.module.types[member.ty].inner {
1580                TypeInner::Array {
1581                    base,
1582                    size,
1583                    stride: _,
1584                } => {
1585                    self.write_type(base)?;
1586                    write!(
1587                        self.out,
1588                        " {}",
1589                        self.names[&NameKey::StructMember(handle, idx as u32)]
1590                    )?;
1591                    // Write [size]
1592                    self.write_array_size(base, size)?;
1593                    // Newline is important
1594                    writeln!(self.out, ";")?;
1595                }
1596                _ => {
1597                    // Write the member type
1598                    // Adds no trailing space
1599                    self.write_type(member.ty)?;
1600
1601                    // Write the member name and put a semicolon
1602                    // The leading space is important
1603                    // All members must have a semicolon even the last one
1604                    writeln!(
1605                        self.out,
1606                        " {};",
1607                        self.names[&NameKey::StructMember(handle, idx as u32)]
1608                    )?;
1609                }
1610            }
1611        }
1612
1613        write!(self.out, "}}")?;
1614        Ok(())
1615    }
1616
1617    /// Helper method used to write statements
1618    ///
1619    /// # Notes
1620    /// Always adds a newline
1621    fn write_stmt(
1622        &mut self,
1623        sta: &crate::Statement,
1624        ctx: &back::FunctionCtx,
1625        level: back::Level,
1626    ) -> BackendResult {
1627        use crate::Statement;
1628
1629        match *sta {
1630            // This is where we can generate intermediate constants for some expression types.
1631            Statement::Emit(ref range) => {
1632                for handle in range.clone() {
1633                    let ptr_class = ctx.resolve_type(handle, &self.module.types).pointer_space();
1634                    let expr_name = if ptr_class.is_some() {
1635                        // GLSL can't save a pointer-valued expression in a variable,
1636                        // but we shouldn't ever need to: they should never be named expressions,
1637                        // and none of the expression types flagged by bake_ref_count can be pointer-valued.
1638                        None
1639                    } else if let Some(name) = ctx.named_expressions.get(&handle) {
1640                        // Front end provides names for all variables at the start of writing.
1641                        // But we write them to step by step. We need to recache them
1642                        // Otherwise, we could accidentally write variable name instead of full expression.
1643                        // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords.
1644                        Some(self.namer.call(name))
1645                    } else if self.need_bake_expressions.contains(&handle) {
1646                        Some(Baked(handle).to_string())
1647                    } else {
1648                        None
1649                    };
1650
1651                    // If we are going to write an `ImageLoad` next and the target image
1652                    // is sampled and we are using the `Restrict` policy for bounds
1653                    // checking images we need to write a local holding the clamped lod.
1654                    if let crate::Expression::ImageLoad {
1655                        image,
1656                        level: Some(level_expr),
1657                        ..
1658                    } = ctx.expressions[handle]
1659                    {
1660                        if let TypeInner::Image {
1661                            class: crate::ImageClass::Sampled { .. },
1662                            ..
1663                        } = *ctx.resolve_type(image, &self.module.types)
1664                        {
1665                            if let proc::BoundsCheckPolicy::Restrict = self.policies.image_load {
1666                                write!(self.out, "{level}")?;
1667                                self.write_clamped_lod(ctx, handle, image, level_expr)?
1668                            }
1669                        }
1670                    }
1671
1672                    if let Some(name) = expr_name {
1673                        write!(self.out, "{level}")?;
1674                        self.write_named_expr(handle, name, handle, ctx)?;
1675                    }
1676                }
1677            }
1678            // Blocks are simple we just need to write the block statements between braces
1679            // We could also just print the statements but this is more readable and maps more
1680            // closely to the IR
1681            Statement::Block(ref block) => {
1682                write!(self.out, "{level}")?;
1683                writeln!(self.out, "{{")?;
1684                for sta in block.iter() {
1685                    // Increase the indentation to help with readability
1686                    self.write_stmt(sta, ctx, level.next())?
1687                }
1688                writeln!(self.out, "{level}}}")?
1689            }
1690            // Ifs are written as in C:
1691            // ```
1692            // if(condition) {
1693            //  accept
1694            // } else {
1695            //  reject
1696            // }
1697            // ```
1698            Statement::If {
1699                condition,
1700                ref accept,
1701                ref reject,
1702            } => {
1703                write!(self.out, "{level}")?;
1704                write!(self.out, "if (")?;
1705                self.write_expr(condition, ctx)?;
1706                writeln!(self.out, ") {{")?;
1707
1708                for sta in accept {
1709                    // Increase indentation to help with readability
1710                    self.write_stmt(sta, ctx, level.next())?;
1711                }
1712
1713                // If there are no statements in the reject block we skip writing it
1714                // This is only for readability
1715                if !reject.is_empty() {
1716                    writeln!(self.out, "{level}}} else {{")?;
1717
1718                    for sta in reject {
1719                        // Increase indentation to help with readability
1720                        self.write_stmt(sta, ctx, level.next())?;
1721                    }
1722                }
1723
1724                writeln!(self.out, "{level}}}")?
1725            }
1726            // Switch are written as in C:
1727            // ```
1728            // switch (selector) {
1729            //      // Fallthrough
1730            //      case label:
1731            //          block
1732            //      // Non fallthrough
1733            //      case label:
1734            //          block
1735            //          break;
1736            //      default:
1737            //          block
1738            //  }
1739            //  ```
1740            //  Where the `default` case happens isn't important but we put it last
1741            //  so that we don't need to print a `break` for it
1742            Statement::Switch {
1743                selector,
1744                ref cases,
1745            } => {
1746                let l2 = level.next();
1747                // Some GLSL consumers may not handle switches with a single
1748                // body correctly: See wgpu#4514. Write such switch statements
1749                // as a `do {} while(false);` loop instead.
1750                //
1751                // Since doing so may inadvertently capture `continue`
1752                // statements in the switch body, we must apply continue
1753                // forwarding. See the `naga::back::continue_forward` module
1754                // docs for details.
1755                let one_body = cases
1756                    .iter()
1757                    .rev()
1758                    .skip(1)
1759                    .all(|case| case.fall_through && case.body.is_empty());
1760                if one_body {
1761                    // Unlike HLSL, in GLSL `continue_ctx` only needs to know
1762                    // about [`Switch`] statements that are being rendered as
1763                    // `do-while` loops.
1764                    if let Some(variable) = self.continue_ctx.enter_switch(&mut self.namer) {
1765                        writeln!(self.out, "{level}bool {variable} = false;",)?;
1766                    };
1767                    writeln!(self.out, "{level}do {{")?;
1768                    // Note: Expressions have no side-effects so we don't need to emit selector expression.
1769
1770                    // Body
1771                    if let Some(case) = cases.last() {
1772                        for sta in case.body.iter() {
1773                            self.write_stmt(sta, ctx, l2)?;
1774                        }
1775                    }
1776                    // End do-while
1777                    writeln!(self.out, "{level}}} while(false);")?;
1778
1779                    // Handle any forwarded continue statements.
1780                    use back::continue_forward::ExitControlFlow;
1781                    let op = match self.continue_ctx.exit_switch() {
1782                        ExitControlFlow::None => None,
1783                        ExitControlFlow::Continue { variable } => Some(("continue", variable)),
1784                        ExitControlFlow::Break { variable } => Some(("break", variable)),
1785                    };
1786                    if let Some((control_flow, variable)) = op {
1787                        writeln!(self.out, "{level}if ({variable}) {{")?;
1788                        writeln!(self.out, "{l2}{control_flow};")?;
1789                        writeln!(self.out, "{level}}}")?;
1790                    }
1791                } else {
1792                    // Start the switch
1793                    write!(self.out, "{level}")?;
1794                    write!(self.out, "switch(")?;
1795                    self.write_expr(selector, ctx)?;
1796                    writeln!(self.out, ") {{")?;
1797
1798                    // Write all cases
1799                    for case in cases {
1800                        match case.value {
1801                            crate::SwitchValue::I32(value) => {
1802                                write!(self.out, "{l2}case {value}:")?
1803                            }
1804                            crate::SwitchValue::U32(value) => {
1805                                write!(self.out, "{l2}case {value}u:")?
1806                            }
1807                            crate::SwitchValue::Default => write!(self.out, "{l2}default:")?,
1808                        }
1809
1810                        let write_block_braces = !(case.fall_through && case.body.is_empty());
1811                        if write_block_braces {
1812                            writeln!(self.out, " {{")?;
1813                        } else {
1814                            writeln!(self.out)?;
1815                        }
1816
1817                        for sta in case.body.iter() {
1818                            self.write_stmt(sta, ctx, l2.next())?;
1819                        }
1820
1821                        if !case.fall_through && case.body.last().is_none_or(|s| !s.is_terminator())
1822                        {
1823                            writeln!(self.out, "{}break;", l2.next())?;
1824                        }
1825
1826                        if write_block_braces {
1827                            writeln!(self.out, "{l2}}}")?;
1828                        }
1829                    }
1830
1831                    writeln!(self.out, "{level}}}")?
1832                }
1833            }
1834            // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a
1835            // while true loop and appending the continuing block to the body resulting on:
1836            // ```
1837            // bool loop_init = true;
1838            // while(true) {
1839            //  if (!loop_init) { <continuing> }
1840            //  loop_init = false;
1841            //  <body>
1842            // }
1843            // ```
1844            Statement::Loop {
1845                ref body,
1846                ref continuing,
1847                break_if,
1848            } => {
1849                self.continue_ctx.enter_loop();
1850                if !continuing.is_empty() || break_if.is_some() {
1851                    let gate_name = self.namer.call("loop_init");
1852                    writeln!(self.out, "{level}bool {gate_name} = true;")?;
1853                    writeln!(self.out, "{level}while(true) {{")?;
1854                    let l2 = level.next();
1855                    let l3 = l2.next();
1856                    writeln!(self.out, "{l2}if (!{gate_name}) {{")?;
1857                    for sta in continuing {
1858                        self.write_stmt(sta, ctx, l3)?;
1859                    }
1860                    if let Some(condition) = break_if {
1861                        write!(self.out, "{l3}if (")?;
1862                        self.write_expr(condition, ctx)?;
1863                        writeln!(self.out, ") {{")?;
1864                        writeln!(self.out, "{}break;", l3.next())?;
1865                        writeln!(self.out, "{l3}}}")?;
1866                    }
1867                    writeln!(self.out, "{l2}}}")?;
1868                    writeln!(self.out, "{}{} = false;", level.next(), gate_name)?;
1869                } else {
1870                    writeln!(self.out, "{level}while(true) {{")?;
1871                }
1872                for sta in body {
1873                    self.write_stmt(sta, ctx, level.next())?;
1874                }
1875                writeln!(self.out, "{level}}}")?;
1876                self.continue_ctx.exit_loop();
1877            }
1878            // Break, continue and return as written as in C
1879            // `break;`
1880            Statement::Break => {
1881                write!(self.out, "{level}")?;
1882                writeln!(self.out, "break;")?
1883            }
1884            // `continue;`
1885            Statement::Continue => {
1886                // Sometimes we must render a `Continue` statement as a `break`.
1887                // See the docs for the `back::continue_forward` module.
1888                if let Some(variable) = self.continue_ctx.continue_encountered() {
1889                    writeln!(self.out, "{level}{variable} = true;",)?;
1890                    writeln!(self.out, "{level}break;")?
1891                } else {
1892                    writeln!(self.out, "{level}continue;")?
1893                }
1894            }
1895            // `return expr;`, `expr` is optional
1896            Statement::Return { value } => {
1897                write!(self.out, "{level}")?;
1898                match ctx.ty {
1899                    back::FunctionType::Function(_) => {
1900                        write!(self.out, "return")?;
1901                        // Write the expression to be returned if needed
1902                        if let Some(expr) = value {
1903                            write!(self.out, " ")?;
1904                            self.write_expr(expr, ctx)?;
1905                        }
1906                        writeln!(self.out, ";")?;
1907                    }
1908                    back::FunctionType::EntryPoint(ep_index) => {
1909                        let mut has_point_size = false;
1910                        let ep = &self.module.entry_points[ep_index as usize];
1911                        if let Some(ref result) = ep.function.result {
1912                            let value = value.unwrap();
1913                            match self.module.types[result.ty].inner {
1914                                TypeInner::Struct { ref members, .. } => {
1915                                    let temp_struct_name = match ctx.expressions[value] {
1916                                        crate::Expression::Compose { .. } => {
1917                                            let return_struct = "_tmp_return";
1918                                            write!(
1919                                                self.out,
1920                                                "{ty} {return_struct} = ",
1921                                                ty = self.names[&NameKey::Type(result.ty)],
1922                                            )?;
1923                                            self.write_expr(value, ctx)?;
1924                                            writeln!(self.out, ";")?;
1925                                            write!(self.out, "{level}")?;
1926                                            Some(return_struct)
1927                                        }
1928                                        _ => None,
1929                                    };
1930
1931                                    for (index, member) in members.iter().enumerate() {
1932                                        if let Some(crate::Binding::BuiltIn(
1933                                            crate::BuiltIn::PointSize,
1934                                        )) = member.binding
1935                                        {
1936                                            has_point_size = true;
1937                                        }
1938
1939                                        let varying_name = VaryingName {
1940                                            binding: member.binding.as_ref().unwrap(),
1941                                            stage: ep.stage,
1942                                            options: VaryingOptions::from_writer_options(
1943                                                self.options,
1944                                                true,
1945                                            ),
1946                                        };
1947                                        write!(self.out, "{varying_name} = ")?;
1948
1949                                        if let Some(struct_name) = temp_struct_name {
1950                                            write!(self.out, "{struct_name}")?;
1951                                        } else {
1952                                            self.write_expr(value, ctx)?;
1953                                        }
1954
1955                                        // Write field name
1956                                        writeln!(
1957                                            self.out,
1958                                            ".{};",
1959                                            self.names
1960                                                [&NameKey::StructMember(result.ty, index as u32)]
1961                                        )?;
1962                                        write!(self.out, "{level}")?;
1963                                    }
1964                                }
1965                                _ => {
1966                                    let name = VaryingName {
1967                                        binding: result.binding.as_ref().unwrap(),
1968                                        stage: ep.stage,
1969                                        options: VaryingOptions::from_writer_options(
1970                                            self.options,
1971                                            true,
1972                                        ),
1973                                    };
1974                                    write!(self.out, "{name} = ")?;
1975                                    self.write_expr(value, ctx)?;
1976                                    writeln!(self.out, ";")?;
1977                                    write!(self.out, "{level}")?;
1978                                }
1979                            }
1980                        }
1981
1982                        let is_vertex_stage = self.module.entry_points[ep_index as usize].stage
1983                            == ShaderStage::Vertex;
1984                        if is_vertex_stage
1985                            && self
1986                                .options
1987                                .writer_flags
1988                                .contains(WriterFlags::ADJUST_COORDINATE_SPACE)
1989                        {
1990                            writeln!(
1991                                self.out,
1992                                "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);",
1993                            )?;
1994                            write!(self.out, "{level}")?;
1995                        }
1996
1997                        if is_vertex_stage
1998                            && self
1999                                .options
2000                                .writer_flags
2001                                .contains(WriterFlags::FORCE_POINT_SIZE)
2002                            && !has_point_size
2003                        {
2004                            writeln!(self.out, "gl_PointSize = 1.0;")?;
2005                            write!(self.out, "{level}")?;
2006                        }
2007                        writeln!(self.out, "return;")?;
2008                    }
2009                }
2010            }
2011            // This is one of the places were glsl adds to the syntax of C in this case the discard
2012            // keyword which ceases all further processing in a fragment shader, it's called OpKill
2013            // in spir-v that's why it's called `Statement::Kill`
2014            Statement::Kill => writeln!(self.out, "{level}discard;")?,
2015            Statement::ControlBarrier(flags) => {
2016                self.write_control_barrier(flags, level)?;
2017            }
2018            Statement::MemoryBarrier(flags) => {
2019                self.write_memory_barrier(flags, level)?;
2020            }
2021            // Stores in glsl are just variable assignments written as `pointer = value;`
2022            Statement::Store { pointer, value } => {
2023                write!(self.out, "{level}")?;
2024                let is_atomic_pointer = ctx
2025                    .resolve_type(pointer, &self.module.types)
2026                    .is_atomic_pointer(&self.module.types);
2027                if is_atomic_pointer {
2028                    write!(self.out, "atomicExchange(")?;
2029                    self.write_expr(pointer, ctx)?;
2030                    write!(self.out, ", ")?;
2031                    self.write_expr(value, ctx)?;
2032                    writeln!(self.out, ");")?
2033                } else {
2034                    self.write_expr(pointer, ctx)?;
2035                    write!(self.out, " = ")?;
2036                    self.write_expr(value, ctx)?;
2037                    writeln!(self.out, ";")?
2038                }
2039            }
2040            Statement::WorkGroupUniformLoad { pointer, result } => {
2041                // GLSL doesn't have pointers, which means that this backend needs to ensure that
2042                // the actual "loading" is happening between the two barriers.
2043                // This is done in `Emit` by never emitting a variable name for pointer variables
2044                self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
2045
2046                let result_name = Baked(result).to_string();
2047                write!(self.out, "{level}")?;
2048                // Expressions cannot have side effects, so just writing the expression here is fine.
2049                self.write_named_expr(pointer, result_name, result, ctx)?;
2050
2051                self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
2052            }
2053            // Stores a value into an image.
2054            Statement::ImageStore {
2055                image,
2056                coordinate,
2057                array_index,
2058                value,
2059            } => {
2060                write!(self.out, "{level}")?;
2061                self.write_image_store(ctx, image, coordinate, array_index, value)?
2062            }
2063            // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list
2064            Statement::Call {
2065                function,
2066                ref arguments,
2067                result,
2068            } => {
2069                write!(self.out, "{level}")?;
2070                if let Some(expr) = result {
2071                    let name = Baked(expr).to_string();
2072                    let result = self.module.functions[function].result.as_ref().unwrap();
2073                    self.write_type(result.ty)?;
2074                    write!(self.out, " {name}")?;
2075                    if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner
2076                    {
2077                        self.write_array_size(base, size)?
2078                    }
2079                    write!(self.out, " = ")?;
2080                    self.named_expressions.insert(expr, name);
2081                }
2082                write!(self.out, "{}(", self.names[&NameKey::Function(function)])?;
2083                let arguments: Vec<_> = arguments
2084                    .iter()
2085                    .enumerate()
2086                    .filter_map(|(i, arg)| {
2087                        let arg_ty = self.module.functions[function].arguments[i].ty;
2088                        match self.module.types[arg_ty].inner {
2089                            TypeInner::Sampler { .. } => None,
2090                            _ => Some(*arg),
2091                        }
2092                    })
2093                    .collect();
2094                self.write_slice(&arguments, |this, _, arg| this.write_expr(*arg, ctx))?;
2095                writeln!(self.out, ");")?
2096            }
2097            Statement::Atomic {
2098                pointer,
2099                ref fun,
2100                value,
2101                result,
2102            } => {
2103                write!(self.out, "{level}")?;
2104
2105                match *fun {
2106                    crate::AtomicFunction::Exchange {
2107                        compare: Some(compare_expr),
2108                    } => {
2109                        let result_handle = result.expect("CompareExchange must have a result");
2110                        let res_name = Baked(result_handle).to_string();
2111                        self.write_type(ctx.info[result_handle].ty.handle().unwrap())?;
2112                        write!(self.out, " {res_name};")?;
2113                        write!(self.out, " {res_name}.old_value = atomicCompSwap(")?;
2114                        self.write_expr(pointer, ctx)?;
2115                        write!(self.out, ", ")?;
2116                        self.write_expr(compare_expr, ctx)?;
2117                        write!(self.out, ", ")?;
2118                        self.write_expr(value, ctx)?;
2119                        writeln!(self.out, ");")?;
2120
2121                        write!(
2122                            self.out,
2123                            "{level}{res_name}.exchanged = ({res_name}.old_value == "
2124                        )?;
2125                        self.write_expr(compare_expr, ctx)?;
2126                        writeln!(self.out, ");")?;
2127                        self.named_expressions.insert(result_handle, res_name);
2128                    }
2129                    _ => {
2130                        if let Some(result) = result {
2131                            let res_name = Baked(result).to_string();
2132                            self.write_type(ctx.info[result].ty.handle().unwrap())?;
2133                            write!(self.out, " {res_name} = ")?;
2134                            self.named_expressions.insert(result, res_name);
2135                        }
2136                        let fun_str = fun.to_glsl();
2137                        write!(self.out, "atomic{fun_str}(")?;
2138                        self.write_expr(pointer, ctx)?;
2139                        write!(self.out, ", ")?;
2140                        if let crate::AtomicFunction::Subtract = *fun {
2141                            // Emulate `atomicSub` with `atomicAdd` by negating the value.
2142                            //
2143                            // Use a space to avoid accidentally producing a prefix increment
2144                            // (`--`).
2145                            write!(self.out, "- ")?;
2146                        }
2147                        self.write_expr(value, ctx)?;
2148                        writeln!(self.out, ");")?;
2149                    }
2150                }
2151            }
2152            // Stores a value into an image.
2153            Statement::ImageAtomic {
2154                image,
2155                coordinate,
2156                array_index,
2157                fun,
2158                value,
2159            } => {
2160                write!(self.out, "{level}")?;
2161                self.write_image_atomic(ctx, image, coordinate, array_index, fun, value)?
2162            }
2163            Statement::RayQuery { .. } => unreachable!(),
2164            Statement::SubgroupBallot { result, predicate } => {
2165                write!(self.out, "{level}")?;
2166                let res_name = Baked(result).to_string();
2167                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2168                self.write_value_type(res_ty)?;
2169                write!(self.out, " {res_name} = ")?;
2170                self.named_expressions.insert(result, res_name);
2171
2172                write!(self.out, "subgroupBallot(")?;
2173                match predicate {
2174                    Some(predicate) => self.write_expr(predicate, ctx)?,
2175                    None => write!(self.out, "true")?,
2176                }
2177                writeln!(self.out, ");")?;
2178            }
2179            Statement::SubgroupCollectiveOperation {
2180                op,
2181                collective_op,
2182                argument,
2183                result,
2184            } => {
2185                write!(self.out, "{level}")?;
2186                let res_name = Baked(result).to_string();
2187                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2188                self.write_value_type(res_ty)?;
2189                write!(self.out, " {res_name} = ")?;
2190                self.named_expressions.insert(result, res_name);
2191
2192                match (collective_op, op) {
2193                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
2194                        write!(self.out, "subgroupAll(")?
2195                    }
2196                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
2197                        write!(self.out, "subgroupAny(")?
2198                    }
2199                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
2200                        write!(self.out, "subgroupAdd(")?
2201                    }
2202                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
2203                        write!(self.out, "subgroupMul(")?
2204                    }
2205                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
2206                        write!(self.out, "subgroupMax(")?
2207                    }
2208                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
2209                        write!(self.out, "subgroupMin(")?
2210                    }
2211                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
2212                        write!(self.out, "subgroupAnd(")?
2213                    }
2214                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
2215                        write!(self.out, "subgroupOr(")?
2216                    }
2217                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
2218                        write!(self.out, "subgroupXor(")?
2219                    }
2220                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Add) => {
2221                        write!(self.out, "subgroupExclusiveAdd(")?
2222                    }
2223                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Mul) => {
2224                        write!(self.out, "subgroupExclusiveMul(")?
2225                    }
2226                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Add) => {
2227                        write!(self.out, "subgroupInclusiveAdd(")?
2228                    }
2229                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Mul) => {
2230                        write!(self.out, "subgroupInclusiveMul(")?
2231                    }
2232                    _ => unimplemented!(),
2233                }
2234                self.write_expr(argument, ctx)?;
2235                writeln!(self.out, ");")?;
2236            }
2237            Statement::SubgroupGather {
2238                mode,
2239                argument,
2240                result,
2241            } => {
2242                write!(self.out, "{level}")?;
2243                let res_name = Baked(result).to_string();
2244                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2245                self.write_value_type(res_ty)?;
2246                write!(self.out, " {res_name} = ")?;
2247                self.named_expressions.insert(result, res_name);
2248
2249                match mode {
2250                    crate::GatherMode::BroadcastFirst => {
2251                        write!(self.out, "subgroupBroadcastFirst(")?;
2252                    }
2253                    crate::GatherMode::Broadcast(_) => {
2254                        write!(self.out, "subgroupBroadcast(")?;
2255                    }
2256                    crate::GatherMode::Shuffle(_) => {
2257                        write!(self.out, "subgroupShuffle(")?;
2258                    }
2259                    crate::GatherMode::ShuffleDown(_) => {
2260                        write!(self.out, "subgroupShuffleDown(")?;
2261                    }
2262                    crate::GatherMode::ShuffleUp(_) => {
2263                        write!(self.out, "subgroupShuffleUp(")?;
2264                    }
2265                    crate::GatherMode::ShuffleXor(_) => {
2266                        write!(self.out, "subgroupShuffleXor(")?;
2267                    }
2268                    crate::GatherMode::QuadBroadcast(_) => {
2269                        write!(self.out, "subgroupQuadBroadcast(")?;
2270                    }
2271                    crate::GatherMode::QuadSwap(direction) => match direction {
2272                        crate::Direction::X => {
2273                            write!(self.out, "subgroupQuadSwapHorizontal(")?;
2274                        }
2275                        crate::Direction::Y => {
2276                            write!(self.out, "subgroupQuadSwapVertical(")?;
2277                        }
2278                        crate::Direction::Diagonal => {
2279                            write!(self.out, "subgroupQuadSwapDiagonal(")?;
2280                        }
2281                    },
2282                }
2283                self.write_expr(argument, ctx)?;
2284                match mode {
2285                    crate::GatherMode::BroadcastFirst => {}
2286                    crate::GatherMode::Broadcast(index)
2287                    | crate::GatherMode::Shuffle(index)
2288                    | crate::GatherMode::ShuffleDown(index)
2289                    | crate::GatherMode::ShuffleUp(index)
2290                    | crate::GatherMode::ShuffleXor(index)
2291                    | crate::GatherMode::QuadBroadcast(index) => {
2292                        write!(self.out, ", ")?;
2293                        self.write_expr(index, ctx)?;
2294                    }
2295                    crate::GatherMode::QuadSwap(_) => {}
2296                }
2297                writeln!(self.out, ");")?;
2298            }
2299            Statement::SubgroupBallotFindBit {
2300                order,
2301                argument,
2302                result,
2303            } => {
2304                write!(self.out, "{level}")?;
2305                let res_name = Baked(result).to_string();
2306                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2307                self.write_value_type(res_ty)?;
2308                write!(self.out, " {res_name} = ")?;
2309                self.named_expressions.insert(result, res_name);
2310
2311                match order {
2312                    crate::BallotFindBitOrder::Lsb => {
2313                        write!(self.out, "subgroupBallotFindLSB(")?;
2314                    }
2315                    crate::BallotFindBitOrder::Msb => {
2316                        write!(self.out, "subgroupBallotFindMSB(")?;
2317                    }
2318                }
2319                self.write_expr(argument, ctx)?;
2320                writeln!(self.out, ");")?;
2321            }
2322            Statement::CooperativeStore { .. } => unimplemented!(),
2323            Statement::RayPipelineFunction(_) | Statement::HitObject { .. } => unimplemented!(),
2324            Statement::DebugPrintf { .. } => unimplemented!(),
2325        }
2326
2327        Ok(())
2328    }
2329
2330    /// Write a const expression.
2331    ///
2332    /// Write `expr`, a handle to an [`Expression`] in the current [`Module`]'s
2333    /// constant expression arena, as GLSL expression.
2334    ///
2335    /// # Notes
2336    /// Adds no newlines or leading/trailing whitespace
2337    ///
2338    /// [`Expression`]: crate::Expression
2339    /// [`Module`]: crate::Module
2340    fn write_const_expr(
2341        &mut self,
2342        expr: Handle<crate::Expression>,
2343        arena: &crate::Arena<crate::Expression>,
2344    ) -> BackendResult {
2345        self.write_possibly_const_expr(
2346            expr,
2347            arena,
2348            |expr| &self.info[expr],
2349            |writer, expr| writer.write_const_expr(expr, arena),
2350        )
2351    }
2352
2353    /// Write [`Expression`] variants that can occur in both runtime and const expressions.
2354    ///
2355    /// Write `expr`, a handle to an [`Expression`] in the arena `expressions`,
2356    /// as as GLSL expression. This must be one of the [`Expression`] variants
2357    /// that is allowed to occur in constant expressions.
2358    ///
2359    /// Use `write_expression` to write subexpressions.
2360    ///
2361    /// This is the common code for `write_expr`, which handles arbitrary
2362    /// runtime expressions, and `write_const_expr`, which only handles
2363    /// const-expressions. Each of those callers passes itself (essentially) as
2364    /// the `write_expression` callback, so that subexpressions are restricted
2365    /// to the appropriate variants.
2366    ///
2367    /// # Notes
2368    /// Adds no newlines or leading/trailing whitespace
2369    ///
2370    /// [`Expression`]: crate::Expression
2371    fn write_possibly_const_expr<'w, I, E>(
2372        &'w mut self,
2373        expr: Handle<crate::Expression>,
2374        expressions: &crate::Arena<crate::Expression>,
2375        info: I,
2376        write_expression: E,
2377    ) -> BackendResult
2378    where
2379        I: Fn(Handle<crate::Expression>) -> &'w proc::TypeResolution,
2380        E: Fn(&mut Self, Handle<crate::Expression>) -> BackendResult,
2381    {
2382        use crate::Expression;
2383
2384        match expressions[expr] {
2385            Expression::Literal(literal) => {
2386                match literal {
2387                    // Floats are written using `Debug` instead of `Display` because it always appends the
2388                    // decimal part even it's zero which is needed for a valid glsl float constant
2389                    crate::Literal::F64(value) => write!(self.out, "{value:?}LF")?,
2390                    crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
2391                    crate::Literal::F16(_) => {
2392                        return Err(Error::Custom("GLSL has no 16-bit float type".into()));
2393                    }
2394                    // Unsigned integers need a `u` at the end
2395                    //
2396                    // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we
2397                    // always write it as the extra branch wouldn't have any benefit in readability
2398                    crate::Literal::U16(value) => write!(self.out, "uint16_t({value})")?,
2399                    crate::Literal::I16(value) => write!(self.out, "int16_t({value})")?,
2400                    crate::Literal::U32(value) => write!(self.out, "{value}u")?,
2401                    crate::Literal::I32(value) => write!(self.out, "{value}")?,
2402                    crate::Literal::Bool(value) => write!(self.out, "{value}")?,
2403                    crate::Literal::I64(_) => {
2404                        return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
2405                    }
2406                    crate::Literal::U64(_) => {
2407                        return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
2408                    }
2409                    crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
2410                        return Err(Error::Custom(
2411                            "Abstract types should not appear in IR presented to backends".into(),
2412                        ));
2413                    }
2414                }
2415            }
2416            Expression::Constant(handle) => {
2417                let constant = &self.module.constants[handle];
2418                if constant.name.is_some() {
2419                    write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
2420                } else {
2421                    self.write_const_expr(constant.init, &self.module.global_expressions)?;
2422                }
2423            }
2424            Expression::ZeroValue(ty) => {
2425                self.write_zero_init_value(ty)?;
2426            }
2427            Expression::Compose { ty, ref components } => {
2428                self.write_type(ty)?;
2429
2430                if let TypeInner::Array { base, size, .. } = self.module.types[ty].inner {
2431                    self.write_array_size(base, size)?;
2432                }
2433
2434                write!(self.out, "(")?;
2435                for (index, component) in components.iter().enumerate() {
2436                    if index != 0 {
2437                        write!(self.out, ", ")?;
2438                    }
2439                    write_expression(self, *component)?;
2440                }
2441                write!(self.out, ")")?
2442            }
2443            // `Splat` needs to actually write down a vector, it's not always inferred in GLSL.
2444            Expression::Splat { size: _, value } => {
2445                let resolved = info(expr).inner_with(&self.module.types);
2446                self.write_value_type(resolved)?;
2447                write!(self.out, "(")?;
2448                write_expression(self, value)?;
2449                write!(self.out, ")")?
2450            }
2451            _ => {
2452                return Err(Error::Override);
2453            }
2454        }
2455
2456        Ok(())
2457    }
2458
2459    /// Helper method to write expressions
2460    ///
2461    /// # Notes
2462    /// Doesn't add any newlines or leading/trailing spaces
2463    #[allow(clippy::large_stack_frames)] // TODO(https://github.com/gfx-rs/wgpu/issues/9456)
2464    fn write_expr(
2465        &mut self,
2466        expr: Handle<crate::Expression>,
2467        ctx: &back::FunctionCtx,
2468    ) -> BackendResult {
2469        use crate::Expression;
2470
2471        if let Some(name) = self.named_expressions.get(&expr) {
2472            write!(self.out, "{name}")?;
2473            return Ok(());
2474        }
2475
2476        match ctx.expressions[expr] {
2477            Expression::Literal(_)
2478            | Expression::Constant(_)
2479            | Expression::ZeroValue(_)
2480            | Expression::Compose { .. }
2481            | Expression::Splat { .. } => {
2482                self.write_possibly_const_expr(
2483                    expr,
2484                    ctx.expressions,
2485                    |expr| &ctx.info[expr].ty,
2486                    |writer, expr| writer.write_expr(expr, ctx),
2487                )?;
2488            }
2489            Expression::Override(_) => return Err(Error::Override),
2490            // `Access` is applied to arrays, vectors and matrices and is written as indexing
2491            Expression::Access { base, index } => {
2492                self.write_expr(base, ctx)?;
2493                write!(self.out, "[")?;
2494                self.write_expr(index, ctx)?;
2495                write!(self.out, "]")?
2496            }
2497            // `AccessIndex` is the same as `Access` except that the index is a constant and it can
2498            // be applied to structs, in this case we need to find the name of the field at that
2499            // index and write `base.field_name`
2500            Expression::AccessIndex { base, index } => {
2501                self.write_expr(base, ctx)?;
2502
2503                let base_ty_res = &ctx.info[base].ty;
2504                let mut resolved = base_ty_res.inner_with(&self.module.types);
2505                let base_ty_handle = match *resolved {
2506                    TypeInner::Pointer { base, space: _ } => {
2507                        resolved = &self.module.types[base].inner;
2508                        Some(base)
2509                    }
2510                    _ => base_ty_res.handle(),
2511                };
2512
2513                match *resolved {
2514                    TypeInner::Vector { .. } => {
2515                        // Write vector access as a swizzle
2516                        write!(self.out, ".{}", back::COMPONENTS[index as usize])?
2517                    }
2518                    TypeInner::Matrix { .. }
2519                    | TypeInner::Array { .. }
2520                    | TypeInner::ValuePointer { .. } => write!(self.out, "[{index}]")?,
2521                    TypeInner::Struct { .. } => {
2522                        // This will never panic in case the type is a `Struct`, this is not true
2523                        // for other types so we can only check while inside this match arm
2524                        let ty = base_ty_handle.unwrap();
2525
2526                        write!(
2527                            self.out,
2528                            ".{}",
2529                            self.names[&NameKey::StructMember(ty, index)]
2530                        )?
2531                    }
2532                    ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))),
2533                }
2534            }
2535            // `Swizzle` adds a few letters behind the dot.
2536            Expression::Swizzle {
2537                size,
2538                vector,
2539                pattern,
2540            } => {
2541                self.write_expr(vector, ctx)?;
2542                write!(self.out, ".")?;
2543                for &sc in pattern[..size as usize].iter() {
2544                    self.out.write_char(back::COMPONENTS[sc as usize])?;
2545                }
2546            }
2547            // Function arguments are written as the argument name
2548            Expression::FunctionArgument(pos) => {
2549                write!(self.out, "{}", self.names[&ctx.argument_key(pos)])?
2550            }
2551            // Global variables need some special work for their name but
2552            // `get_global_name` does the work for us
2553            Expression::GlobalVariable(handle) => {
2554                let global = &self.module.global_variables[handle];
2555                self.write_global_name(handle, global)?
2556            }
2557            // A local is written as it's name
2558            Expression::LocalVariable(handle) => {
2559                write!(self.out, "{}", self.names[&ctx.name_key(handle)])?
2560            }
2561            // glsl has no pointers so there's no load operation, just write the pointer expression
2562            Expression::Load { pointer } => {
2563                let ty_inner = ctx.resolve_type(pointer, &self.module.types);
2564                if ty_inner.is_atomic_pointer(&self.module.types) {
2565                    let mut suffix = "";
2566                    if let TypeInner::Pointer { base, .. } = *ty_inner {
2567                        if let TypeInner::Atomic(scalar) = self.module.types[base].inner {
2568                            suffix = match (scalar.kind, scalar.width) {
2569                                (crate::ScalarKind::Uint, 8) => "ul",
2570                                (crate::ScalarKind::Sint, 8) => "l",
2571                                (crate::ScalarKind::Uint, _) => "u",
2572                                _ => "",
2573                            };
2574                        }
2575                    }
2576                    write!(self.out, "atomicOr(")?;
2577                    self.write_expr(pointer, ctx)?;
2578                    write!(self.out, ", 0{})", suffix)?
2579                } else {
2580                    self.write_expr(pointer, ctx)?
2581                }
2582            }
2583            // `ImageSample` is a bit complicated compared to the rest of the IR.
2584            //
2585            // First there are three variations depending whether the sample level is explicitly set,
2586            // if it's automatic or it it's bias:
2587            // `texture(image, coordinate)` - Automatic sample level
2588            // `texture(image, coordinate, bias)` - Bias sample level
2589            // `textureLod(image, coordinate, level)` - Zero or Exact sample level
2590            //
2591            // Furthermore if `depth_ref` is some we need to append it to the coordinate vector
2592            Expression::ImageSample {
2593                image,
2594                sampler: _, //TODO?
2595                gather,
2596                coordinate,
2597                array_index,
2598                offset,
2599                level,
2600                depth_ref,
2601                clamp_to_edge: _,
2602            } => {
2603                let (dim, class, arrayed) = match *ctx.resolve_type(image, &self.module.types) {
2604                    TypeInner::Image {
2605                        dim,
2606                        class,
2607                        arrayed,
2608                        ..
2609                    } => (dim, class, arrayed),
2610                    _ => unreachable!(),
2611                };
2612                let mut err = None;
2613                if dim == crate::ImageDimension::Cube {
2614                    if offset.is_some() {
2615                        err = Some("gsamplerCube[Array][Shadow] doesn't support texture sampling with offsets");
2616                    }
2617                    if arrayed
2618                        && matches!(class, crate::ImageClass::Depth { .. })
2619                        && matches!(level, crate::SampleLevel::Gradient { .. })
2620                    {
2621                        err = Some("samplerCubeArrayShadow don't support textureGrad");
2622                    }
2623                }
2624                if gather.is_some() && level != crate::SampleLevel::Zero {
2625                    err = Some("textureGather doesn't support LOD parameters");
2626                }
2627                if let Some(err) = err {
2628                    return Err(Error::Custom(String::from(err)));
2629                }
2630
2631                // `textureLod[Offset]` on `sampler2DArrayShadow` and `samplerCubeShadow` does not exist in GLSL,
2632                // unless `GL_EXT_texture_shadow_lod` is present.
2633                // But if the target LOD is zero, we can emulate that by using `textureGrad[Offset]` with a constant gradient of 0.
2634                let workaround_lod_with_grad = ((dim == crate::ImageDimension::Cube && !arrayed)
2635                    || (dim == crate::ImageDimension::D2 && arrayed))
2636                    && level == crate::SampleLevel::Zero
2637                    && matches!(class, crate::ImageClass::Depth { .. })
2638                    && !self.features.contains(Features::TEXTURE_SHADOW_LOD);
2639
2640                // Write the function to be used depending on the sample level
2641                let fun_name = match level {
2642                    crate::SampleLevel::Zero if gather.is_some() => "textureGather",
2643                    crate::SampleLevel::Zero if workaround_lod_with_grad => "textureGrad",
2644                    crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture",
2645                    crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod",
2646                    crate::SampleLevel::Gradient { .. } => "textureGrad",
2647                };
2648                let offset_name = match offset {
2649                    Some(_) => "Offset",
2650                    None => "",
2651                };
2652
2653                write!(self.out, "{fun_name}{offset_name}(")?;
2654
2655                // Write the image that will be used
2656                self.write_expr(image, ctx)?;
2657                // The space here isn't required but it helps with readability
2658                write!(self.out, ", ")?;
2659
2660                // TODO: handle clamp_to_edge
2661                // https://github.com/gfx-rs/wgpu/issues/7791
2662
2663                // We need to get the coordinates vector size to later build a vector that's `size + 1`
2664                // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression
2665                let mut coord_dim = match *ctx.resolve_type(coordinate, &self.module.types) {
2666                    TypeInner::Vector { size, .. } => size as u8,
2667                    TypeInner::Scalar { .. } => 1,
2668                    _ => unreachable!(),
2669                };
2670
2671                if array_index.is_some() {
2672                    coord_dim += 1;
2673                }
2674                let merge_depth_ref = depth_ref.is_some() && gather.is_none() && coord_dim < 4;
2675                if merge_depth_ref {
2676                    coord_dim += 1;
2677                }
2678
2679                let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es();
2680                let is_vec = tex_1d_hack || coord_dim != 1;
2681                // Compose a new texture coordinates vector
2682                if is_vec {
2683                    write!(self.out, "vec{}(", coord_dim + tex_1d_hack as u8)?;
2684                }
2685                self.write_expr(coordinate, ctx)?;
2686                if tex_1d_hack {
2687                    write!(self.out, ", 0.0")?;
2688                }
2689                if let Some(expr) = array_index {
2690                    write!(self.out, ", ")?;
2691                    self.write_expr(expr, ctx)?;
2692                }
2693                if merge_depth_ref {
2694                    write!(self.out, ", ")?;
2695                    self.write_expr(depth_ref.unwrap(), ctx)?;
2696                }
2697                if is_vec {
2698                    write!(self.out, ")")?;
2699                }
2700
2701                if let (Some(expr), false) = (depth_ref, merge_depth_ref) {
2702                    write!(self.out, ", ")?;
2703                    self.write_expr(expr, ctx)?;
2704                }
2705
2706                match level {
2707                    // Auto needs no more arguments
2708                    crate::SampleLevel::Auto => (),
2709                    // Zero needs level set to 0
2710                    crate::SampleLevel::Zero => {
2711                        if workaround_lod_with_grad {
2712                            let vec_dim = match dim {
2713                                crate::ImageDimension::Cube => 3,
2714                                _ => 2,
2715                            };
2716                            write!(self.out, ", vec{vec_dim}(0.0), vec{vec_dim}(0.0)")?;
2717                        } else if gather.is_none() {
2718                            write!(self.out, ", 0.0")?;
2719                        }
2720                    }
2721                    // Exact and bias require another argument
2722                    crate::SampleLevel::Exact(expr) => {
2723                        write!(self.out, ", ")?;
2724                        self.write_expr(expr, ctx)?;
2725                    }
2726                    crate::SampleLevel::Bias(_) => {
2727                        // This needs to be done after the offset writing
2728                    }
2729                    crate::SampleLevel::Gradient { x, y } => {
2730                        // If we are using sampler2D to replace sampler1D, we also
2731                        // need to make sure to use vec2 gradients
2732                        if tex_1d_hack {
2733                            write!(self.out, ", vec2(")?;
2734                            self.write_expr(x, ctx)?;
2735                            write!(self.out, ", 0.0)")?;
2736                            write!(self.out, ", vec2(")?;
2737                            self.write_expr(y, ctx)?;
2738                            write!(self.out, ", 0.0)")?;
2739                        } else {
2740                            write!(self.out, ", ")?;
2741                            self.write_expr(x, ctx)?;
2742                            write!(self.out, ", ")?;
2743                            self.write_expr(y, ctx)?;
2744                        }
2745                    }
2746                }
2747
2748                if let Some(constant) = offset {
2749                    write!(self.out, ", ")?;
2750                    if tex_1d_hack {
2751                        write!(self.out, "ivec2(")?;
2752                    }
2753                    self.write_const_expr(constant, ctx.expressions)?;
2754                    if tex_1d_hack {
2755                        write!(self.out, ", 0)")?;
2756                    }
2757                }
2758
2759                // Bias is always the last argument
2760                if let crate::SampleLevel::Bias(expr) = level {
2761                    write!(self.out, ", ")?;
2762                    self.write_expr(expr, ctx)?;
2763                }
2764
2765                if let (Some(component), None) = (gather, depth_ref) {
2766                    write!(self.out, ", {}", component as usize)?;
2767                }
2768
2769                // End the function
2770                write!(self.out, ")")?
2771            }
2772            Expression::ImageLoad {
2773                image,
2774                coordinate,
2775                array_index,
2776                sample,
2777                level,
2778            } => self.write_image_load(expr, ctx, image, coordinate, array_index, sample, level)?,
2779            // Query translates into one of the:
2780            // - textureSize/imageSize
2781            // - textureQueryLevels
2782            // - textureSamples/imageSamples
2783            Expression::ImageQuery { image, query } => {
2784                use crate::ImageClass;
2785
2786                // This will only panic if the module is invalid
2787                let (dim, class) = match *ctx.resolve_type(image, &self.module.types) {
2788                    TypeInner::Image {
2789                        dim,
2790                        arrayed: _,
2791                        class,
2792                    } => (dim, class),
2793                    _ => unreachable!(),
2794                };
2795                let components = match dim {
2796                    crate::ImageDimension::D1 => 1,
2797                    crate::ImageDimension::D2 => 2,
2798                    crate::ImageDimension::D3 => 3,
2799                    crate::ImageDimension::Cube => 2,
2800                };
2801
2802                if let crate::ImageQuery::Size { .. } = query {
2803                    match components {
2804                        1 => write!(self.out, "uint(")?,
2805                        _ => write!(self.out, "uvec{components}(")?,
2806                    }
2807                } else {
2808                    write!(self.out, "uint(")?;
2809                }
2810
2811                match query {
2812                    crate::ImageQuery::Size { level } => {
2813                        match class {
2814                            ImageClass::Sampled { multi, .. } | ImageClass::Depth { multi } => {
2815                                write!(self.out, "textureSize(")?;
2816                                self.write_expr(image, ctx)?;
2817                                if let Some(expr) = level {
2818                                    write!(self.out, ", ")?;
2819                                    self.write_expr_as_int(expr, ctx)?;
2820                                } else if !multi {
2821                                    // All textureSize calls requires an lod argument
2822                                    // except for multisampled samplers
2823                                    write!(self.out, ", 0")?;
2824                                }
2825                            }
2826                            ImageClass::Storage { .. } => {
2827                                write!(self.out, "imageSize(")?;
2828                                self.write_expr(image, ctx)?;
2829                            }
2830                            ImageClass::External => unimplemented!(),
2831                        }
2832                        write!(self.out, ")")?;
2833                        if components != 1 || self.options.version.is_es() {
2834                            write!(self.out, ".{}", &"xyz"[..components])?;
2835                        }
2836                    }
2837                    crate::ImageQuery::NumLevels => {
2838                        write!(self.out, "textureQueryLevels(",)?;
2839                        self.write_expr(image, ctx)?;
2840                        write!(self.out, ")",)?;
2841                    }
2842                    crate::ImageQuery::NumLayers => {
2843                        let fun_name = match class {
2844                            ImageClass::Sampled { .. } | ImageClass::Depth { .. } => "textureSize",
2845                            ImageClass::Storage { .. } => "imageSize",
2846                            ImageClass::External => unimplemented!(),
2847                        };
2848                        write!(self.out, "{fun_name}(")?;
2849                        self.write_expr(image, ctx)?;
2850                        // All textureSize calls requires an lod argument
2851                        // except for multisampled samplers
2852                        if !class.is_multisampled() {
2853                            write!(self.out, ", 0")?;
2854                        }
2855                        write!(self.out, ")")?;
2856                        if components != 1 || self.options.version.is_es() {
2857                            write!(self.out, ".{}", back::COMPONENTS[components])?;
2858                        }
2859                    }
2860                    crate::ImageQuery::NumSamples => {
2861                        let fun_name = match class {
2862                            ImageClass::Sampled { .. } | ImageClass::Depth { .. } => {
2863                                "textureSamples"
2864                            }
2865                            ImageClass::Storage { .. } => "imageSamples",
2866                            ImageClass::External => unimplemented!(),
2867                        };
2868                        write!(self.out, "{fun_name}(")?;
2869                        self.write_expr(image, ctx)?;
2870                        write!(self.out, ")",)?;
2871                    }
2872                }
2873
2874                write!(self.out, ")")?;
2875            }
2876            Expression::Unary { op, expr } => {
2877                let operator_or_fn = match op {
2878                    crate::UnaryOperator::Negate => "-",
2879                    crate::UnaryOperator::LogicalNot => {
2880                        match *ctx.resolve_type(expr, &self.module.types) {
2881                            TypeInner::Vector { .. } => "not",
2882                            _ => "!",
2883                        }
2884                    }
2885                    crate::UnaryOperator::BitwiseNot => "~",
2886                };
2887                write!(self.out, "{operator_or_fn}(")?;
2888
2889                self.write_expr(expr, ctx)?;
2890
2891                write!(self.out, ")")?
2892            }
2893            // `Binary` we just write `left op right`, except when dealing with
2894            // comparison operations on vectors as they are implemented with
2895            // builtin functions.
2896            // Once again we wrap everything in parentheses to avoid precedence issues
2897            Expression::Binary {
2898                mut op,
2899                left,
2900                right,
2901            } => {
2902                // Holds `Some(function_name)` if the binary operation is
2903                // implemented as a function call
2904                use crate::{BinaryOperator as Bo, ScalarKind as Sk, TypeInner as Ti};
2905
2906                let left_inner = ctx.resolve_type(left, &self.module.types);
2907                let right_inner = ctx.resolve_type(right, &self.module.types);
2908
2909                let function = match (left_inner, right_inner) {
2910                    (&Ti::Vector { scalar, .. }, &Ti::Vector { .. }) => match op {
2911                        Bo::Less
2912                        | Bo::LessEqual
2913                        | Bo::Greater
2914                        | Bo::GreaterEqual
2915                        | Bo::Equal
2916                        | Bo::NotEqual => BinaryOperation::VectorCompare,
2917                        Bo::Modulo if scalar.kind == Sk::Float => BinaryOperation::Modulo,
2918                        Bo::Modulo if scalar.kind == Sk::Sint || scalar.kind == Sk::Uint => {
2919                            BinaryOperation::ModuloInt
2920                        }
2921                        Bo::And if scalar.kind == Sk::Bool => {
2922                            op = crate::BinaryOperator::LogicalAnd;
2923                            BinaryOperation::VectorComponentWise
2924                        }
2925                        Bo::InclusiveOr if scalar.kind == Sk::Bool => {
2926                            op = crate::BinaryOperator::LogicalOr;
2927                            BinaryOperation::VectorComponentWise
2928                        }
2929                        _ => BinaryOperation::Other,
2930                    },
2931                    _ => match (left_inner.scalar_kind(), right_inner.scalar_kind()) {
2932                        (Some(Sk::Float), _) | (_, Some(Sk::Float)) => match op {
2933                            Bo::Modulo => BinaryOperation::Modulo,
2934                            _ => BinaryOperation::Other,
2935                        },
2936                        (Some(Sk::Sint | Sk::Uint), _) | (_, Some(Sk::Sint | Sk::Uint))
2937                            if op == Bo::Modulo =>
2938                        {
2939                            BinaryOperation::ModuloInt
2940                        }
2941                        (Some(Sk::Bool), Some(Sk::Bool)) => match op {
2942                            Bo::InclusiveOr => {
2943                                op = crate::BinaryOperator::LogicalOr;
2944                                BinaryOperation::Other
2945                            }
2946                            Bo::And => {
2947                                op = crate::BinaryOperator::LogicalAnd;
2948                                BinaryOperation::Other
2949                            }
2950                            _ => BinaryOperation::Other,
2951                        },
2952                        _ => BinaryOperation::Other,
2953                    },
2954                };
2955
2956                match function {
2957                    BinaryOperation::VectorCompare => {
2958                        let op_str = match op {
2959                            Bo::Less => "lessThan(",
2960                            Bo::LessEqual => "lessThanEqual(",
2961                            Bo::Greater => "greaterThan(",
2962                            Bo::GreaterEqual => "greaterThanEqual(",
2963                            Bo::Equal => "equal(",
2964                            Bo::NotEqual => "notEqual(",
2965                            _ => unreachable!(),
2966                        };
2967                        write!(self.out, "{op_str}")?;
2968                        self.write_expr(left, ctx)?;
2969                        write!(self.out, ", ")?;
2970                        self.write_expr(right, ctx)?;
2971                        write!(self.out, ")")?;
2972                    }
2973                    BinaryOperation::VectorComponentWise => {
2974                        self.write_value_type(left_inner)?;
2975                        write!(self.out, "(")?;
2976
2977                        let size = match *left_inner {
2978                            Ti::Vector { size, .. } => size,
2979                            _ => unreachable!(),
2980                        };
2981
2982                        for i in 0..size as usize {
2983                            if i != 0 {
2984                                write!(self.out, ", ")?;
2985                            }
2986
2987                            self.write_expr(left, ctx)?;
2988                            write!(self.out, ".{}", back::COMPONENTS[i])?;
2989
2990                            write!(self.out, " {} ", back::binary_operation_str(op))?;
2991
2992                            self.write_expr(right, ctx)?;
2993                            write!(self.out, ".{}", back::COMPONENTS[i])?;
2994                        }
2995
2996                        write!(self.out, ")")?;
2997                    }
2998                    // Signed/unsigned integer `%` with a negative operand is handled by
2999                    // `BinaryOperation::ModuloInt` below. Remaining TODO: the degenerate
3000                    // div-by-zero / `INT_MIN % -1` cases (this backend also leaves integer
3001                    // `/` unguarded), and float `% 0` (see
3002                    // https://github.com/gpuweb/gpuweb/issues/2798).
3003                    BinaryOperation::Modulo => {
3004                        write!(self.out, "(")?;
3005
3006                        // write `e1 - e2 * trunc(e1 / e2)`
3007                        self.write_expr(left, ctx)?;
3008                        write!(self.out, " - ")?;
3009                        self.write_expr(right, ctx)?;
3010                        write!(self.out, " * ")?;
3011                        write!(self.out, "trunc(")?;
3012                        self.write_expr(left, ctx)?;
3013                        write!(self.out, " / ")?;
3014                        self.write_expr(right, ctx)?;
3015                        write!(self.out, ")")?;
3016
3017                        write!(self.out, ")")?;
3018                    }
3019                    BinaryOperation::ModuloInt => {
3020                        // GLSL's `%` is undefined when either operand is negative.
3021                        // Integer division truncates toward zero (which is well
3022                        // defined), so reconstruct the remainder as `e1 - e2 * (e1 / e2)`.
3023                        // This matches WGSL's truncated `%` for all operands; the
3024                        // degenerate `x % 0` / `INT_MIN % -1` cases stay consistent
3025                        // with this backend's unguarded integer `/`.
3026                        write!(self.out, "(")?;
3027                        self.write_expr(left, ctx)?;
3028                        write!(self.out, " - ")?;
3029                        self.write_expr(right, ctx)?;
3030                        write!(self.out, " * (")?;
3031                        self.write_expr(left, ctx)?;
3032                        write!(self.out, " / ")?;
3033                        self.write_expr(right, ctx)?;
3034                        write!(self.out, "))")?;
3035                    }
3036                    BinaryOperation::Other => {
3037                        write!(self.out, "(")?;
3038
3039                        self.write_expr(left, ctx)?;
3040                        write!(self.out, " {} ", back::binary_operation_str(op))?;
3041                        self.write_expr(right, ctx)?;
3042
3043                        write!(self.out, ")")?;
3044                    }
3045                }
3046            }
3047            // `Select` is written as `condition ? accept : reject`
3048            // We wrap everything in parentheses to avoid precedence issues
3049            Expression::Select {
3050                condition,
3051                accept,
3052                reject,
3053            } => {
3054                let cond_ty = ctx.resolve_type(condition, &self.module.types);
3055                let vec_select = if let TypeInner::Vector { .. } = *cond_ty {
3056                    true
3057                } else {
3058                    false
3059                };
3060
3061                if vec_select {
3062                    let result_ty = ctx.resolve_type(accept, &self.module.types);
3063                    let size = match *result_ty {
3064                        TypeInner::Vector { size, .. } => size,
3065                        _ => unreachable!(),
3066                    };
3067                    let is_float =
3068                        matches!(result_ty.scalar_kind(), Some(crate::ScalarKind::Float));
3069
3070                    if is_float || self.options.version.supports_integer_mix() {
3071                        // Glsl defines that for mix when the condition is a boolean the first
3072                        // element is picked if condition is false and the second if condition
3073                        // is true
3074                        write!(self.out, "mix(")?;
3075                        self.write_expr(reject, ctx)?;
3076                        write!(self.out, ", ")?;
3077                        self.write_expr(accept, ctx)?;
3078                        write!(self.out, ", ")?;
3079                        self.write_expr(condition, ctx)?;
3080                        write!(self.out, ")")?;
3081                    } else {
3082                        // No integer `mix` before GLSL 4.50 / ES 3.10.
3083                        self.write_value_type(result_ty)?;
3084                        write!(self.out, "(")?;
3085
3086                        for i in 0..size as usize {
3087                            if i != 0 {
3088                                write!(self.out, ", ")?;
3089                            }
3090
3091                            self.write_expr(condition, ctx)?;
3092                            write!(self.out, ".{} ? ", back::COMPONENTS[i])?;
3093                            self.write_expr(accept, ctx)?;
3094                            write!(self.out, ".{} : ", back::COMPONENTS[i])?;
3095                            self.write_expr(reject, ctx)?;
3096                            write!(self.out, ".{}", back::COMPONENTS[i])?;
3097                        }
3098
3099                        write!(self.out, ")")?;
3100                    }
3101                } else {
3102                    write!(self.out, "(")?;
3103                    self.write_expr(condition, ctx)?;
3104                    write!(self.out, " ? ")?;
3105                    self.write_expr(accept, ctx)?;
3106                    write!(self.out, " : ")?;
3107                    self.write_expr(reject, ctx)?;
3108                    write!(self.out, ")")?;
3109                }
3110            }
3111            // `Derivative` is a function call to a glsl provided function
3112            Expression::Derivative { axis, ctrl, expr } => {
3113                use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
3114                let fun_name = if self.options.version.supports_derivative_control() {
3115                    match (axis, ctrl) {
3116                        (Axis::X, Ctrl::Coarse) => "dFdxCoarse",
3117                        (Axis::X, Ctrl::Fine) => "dFdxFine",
3118                        (Axis::X, Ctrl::None) => "dFdx",
3119                        (Axis::Y, Ctrl::Coarse) => "dFdyCoarse",
3120                        (Axis::Y, Ctrl::Fine) => "dFdyFine",
3121                        (Axis::Y, Ctrl::None) => "dFdy",
3122                        (Axis::Width, Ctrl::Coarse) => "fwidthCoarse",
3123                        (Axis::Width, Ctrl::Fine) => "fwidthFine",
3124                        (Axis::Width, Ctrl::None) => "fwidth",
3125                    }
3126                } else {
3127                    match axis {
3128                        Axis::X => "dFdx",
3129                        Axis::Y => "dFdy",
3130                        Axis::Width => "fwidth",
3131                    }
3132                };
3133                write!(self.out, "{fun_name}(")?;
3134                self.write_expr(expr, ctx)?;
3135                write!(self.out, ")")?
3136            }
3137            // `Relational` is a normal function call to some glsl provided functions
3138            Expression::Relational { fun, argument } => {
3139                use crate::RelationalFunction as Rf;
3140
3141                let fun_name = match fun {
3142                    Rf::IsInf => "isinf",
3143                    Rf::IsNan => "isnan",
3144                    Rf::All => "all",
3145                    Rf::Any => "any",
3146                };
3147                write!(self.out, "{fun_name}(")?;
3148
3149                self.write_expr(argument, ctx)?;
3150
3151                write!(self.out, ")")?
3152            }
3153            Expression::Math {
3154                fun,
3155                arg,
3156                arg1,
3157                arg2,
3158                arg3,
3159            } => {
3160                use crate::MathFunction as Mf;
3161
3162                let fun_name = match fun {
3163                    // comparison
3164                    Mf::Abs => "abs",
3165                    Mf::Min => "min",
3166                    Mf::Max => "max",
3167                    Mf::Clamp => {
3168                        let scalar_kind = ctx
3169                            .resolve_type(arg, &self.module.types)
3170                            .scalar_kind()
3171                            .unwrap();
3172                        match scalar_kind {
3173                            crate::ScalarKind::Float => "clamp",
3174                            // Clamp is undefined if min > max. In practice this means it can use a median-of-three
3175                            // instruction to determine the value. This is fine according to the WGSL spec for float
3176                            // clamp, but integer clamp _must_ use min-max. As such we write out min/max.
3177                            _ => {
3178                                write!(self.out, "min(max(")?;
3179                                self.write_expr(arg, ctx)?;
3180                                write!(self.out, ", ")?;
3181                                self.write_expr(arg1.unwrap(), ctx)?;
3182                                write!(self.out, "), ")?;
3183                                self.write_expr(arg2.unwrap(), ctx)?;
3184                                write!(self.out, ")")?;
3185
3186                                return Ok(());
3187                            }
3188                        }
3189                    }
3190                    Mf::Saturate => {
3191                        write!(self.out, "clamp(")?;
3192
3193                        self.write_expr(arg, ctx)?;
3194
3195                        match *ctx.resolve_type(arg, &self.module.types) {
3196                            TypeInner::Vector { size, .. } => write!(
3197                                self.out,
3198                                ", vec{}(0.0), vec{0}(1.0)",
3199                                common::vector_size_str(size)
3200                            )?,
3201                            _ => write!(self.out, ", 0.0, 1.0")?,
3202                        }
3203
3204                        write!(self.out, ")")?;
3205
3206                        return Ok(());
3207                    }
3208                    // trigonometry
3209                    Mf::Cos => "cos",
3210                    Mf::Cosh => "cosh",
3211                    Mf::Sin => "sin",
3212                    Mf::Sinh => "sinh",
3213                    Mf::Tan => "tan",
3214                    Mf::Tanh => "tanh",
3215                    Mf::Acos => "acos",
3216                    Mf::Asin => "asin",
3217                    Mf::Atan => "atan",
3218                    Mf::Asinh => "asinh",
3219                    Mf::Acosh => "acosh",
3220                    Mf::Atanh => "atanh",
3221                    Mf::Radians => "radians",
3222                    Mf::Degrees => "degrees",
3223                    // glsl doesn't have atan2 function
3224                    // use two-argument variation of the atan function
3225                    Mf::Atan2 => "atan",
3226                    // decomposition
3227                    Mf::Ceil => "ceil",
3228                    Mf::Floor => "floor",
3229                    Mf::Round => "roundEven",
3230                    Mf::Fract => "fract",
3231                    Mf::Trunc => "trunc",
3232                    Mf::Modf => MODF_FUNCTION,
3233                    Mf::Frexp => FREXP_FUNCTION,
3234                    Mf::Ldexp => "ldexp",
3235                    // exponent
3236                    Mf::Exp => "exp",
3237                    Mf::Exp2 => "exp2",
3238                    Mf::Log => "log",
3239                    Mf::Log2 => "log2",
3240                    Mf::Pow => "pow",
3241                    // geometry
3242                    Mf::Dot => match *ctx.resolve_type(arg, &self.module.types) {
3243                        TypeInner::Vector {
3244                            scalar:
3245                                crate::Scalar {
3246                                    kind: crate::ScalarKind::Float,
3247                                    ..
3248                                },
3249                            ..
3250                        } => "dot",
3251                        TypeInner::Vector { size, .. } => {
3252                            return self.write_dot_product(arg, arg1.unwrap(), size as usize, ctx)
3253                        }
3254                        _ => unreachable!(
3255                            "Correct TypeInner for dot product should be already validated"
3256                        ),
3257                    },
3258                    fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => {
3259                        let conversion = match fun {
3260                            Mf::Dot4I8Packed => "int",
3261                            Mf::Dot4U8Packed => "",
3262                            _ => unreachable!(),
3263                        };
3264
3265                        let arg1 = arg1.unwrap();
3266
3267                        // Write parentheses around the dot product expression to prevent operators
3268                        // with different precedences from applying earlier.
3269                        write!(self.out, "(")?;
3270                        for i in 0..4 {
3271                            // Since `bitfieldExtract` only sign extends if the value is signed, we
3272                            // need to convert the inputs to `int` in case of `Dot4I8Packed`. For
3273                            // `Dot4U8Packed`, the code below only introduces parenthesis around
3274                            // each factor, which aren't strictly needed because both operands are
3275                            // baked, but which don't hurt either.
3276                            write!(self.out, "bitfieldExtract({conversion}(")?;
3277                            self.write_expr(arg, ctx)?;
3278                            write!(self.out, "), {}, 8)", i * 8)?;
3279
3280                            write!(self.out, " * bitfieldExtract({conversion}(")?;
3281                            self.write_expr(arg1, ctx)?;
3282                            write!(self.out, "), {}, 8)", i * 8)?;
3283
3284                            if i != 3 {
3285                                write!(self.out, " + ")?;
3286                            }
3287                        }
3288                        write!(self.out, ")")?;
3289
3290                        return Ok(());
3291                    }
3292                    Mf::Outer => "outerProduct",
3293                    Mf::Cross => "cross",
3294                    Mf::Distance => "distance",
3295                    Mf::Length => "length",
3296                    Mf::Normalize => "normalize",
3297                    Mf::FaceForward => "faceforward",
3298                    Mf::Reflect => "reflect",
3299                    Mf::Refract => "refract",
3300                    // computational
3301                    Mf::Sign => "sign",
3302                    Mf::Fma => {
3303                        if self.options.version.supports_fma_function() {
3304                            // Use the fma function when available
3305                            "fma"
3306                        } else {
3307                            // No fma support. Transform the function call into an arithmetic expression
3308                            write!(self.out, "(")?;
3309
3310                            self.write_expr(arg, ctx)?;
3311                            write!(self.out, " * ")?;
3312
3313                            let arg1 =
3314                                arg1.ok_or_else(|| Error::Custom("Missing fma arg1".to_owned()))?;
3315                            self.write_expr(arg1, ctx)?;
3316                            write!(self.out, " + ")?;
3317
3318                            let arg2 =
3319                                arg2.ok_or_else(|| Error::Custom("Missing fma arg2".to_owned()))?;
3320                            self.write_expr(arg2, ctx)?;
3321                            write!(self.out, ")")?;
3322
3323                            return Ok(());
3324                        }
3325                    }
3326                    Mf::Mix => "mix",
3327                    Mf::Step => "step",
3328                    Mf::SmoothStep => "smoothstep",
3329                    Mf::Sqrt => "sqrt",
3330                    Mf::InverseSqrt => "inversesqrt",
3331                    Mf::Inverse => "inverse",
3332                    Mf::Transpose => "transpose",
3333                    Mf::Determinant => "determinant",
3334                    Mf::QuantizeToF16 => match *ctx.resolve_type(arg, &self.module.types) {
3335                        TypeInner::Scalar { .. } => {
3336                            write!(self.out, "unpackHalf2x16(packHalf2x16(vec2(")?;
3337                            self.write_expr(arg, ctx)?;
3338                            write!(self.out, "))).x")?;
3339                            return Ok(());
3340                        }
3341                        TypeInner::Vector {
3342                            size: crate::VectorSize::Bi,
3343                            ..
3344                        } => {
3345                            write!(self.out, "unpackHalf2x16(packHalf2x16(")?;
3346                            self.write_expr(arg, ctx)?;
3347                            write!(self.out, "))")?;
3348                            return Ok(());
3349                        }
3350                        TypeInner::Vector {
3351                            size: crate::VectorSize::Tri,
3352                            ..
3353                        } => {
3354                            write!(self.out, "vec3(unpackHalf2x16(packHalf2x16(")?;
3355                            self.write_expr(arg, ctx)?;
3356                            write!(self.out, ".xy)), unpackHalf2x16(packHalf2x16(")?;
3357                            self.write_expr(arg, ctx)?;
3358                            write!(self.out, ".zz)).x)")?;
3359                            return Ok(());
3360                        }
3361                        TypeInner::Vector {
3362                            size: crate::VectorSize::Quad,
3363                            ..
3364                        } => {
3365                            write!(self.out, "vec4(unpackHalf2x16(packHalf2x16(")?;
3366                            self.write_expr(arg, ctx)?;
3367                            write!(self.out, ".xy)), unpackHalf2x16(packHalf2x16(")?;
3368                            self.write_expr(arg, ctx)?;
3369                            write!(self.out, ".zw)))")?;
3370                            return Ok(());
3371                        }
3372                        _ => unreachable!(
3373                            "Correct TypeInner for QuantizeToF16 should be already validated"
3374                        ),
3375                    },
3376                    // bits
3377                    Mf::CountTrailingZeros => {
3378                        match *ctx.resolve_type(arg, &self.module.types) {
3379                            TypeInner::Vector { size, scalar, .. } => {
3380                                let s = common::vector_size_str(size);
3381                                if let crate::ScalarKind::Uint = scalar.kind {
3382                                    write!(self.out, "min(uvec{s}(findLSB(")?;
3383                                    self.write_expr(arg, ctx)?;
3384                                    write!(self.out, ")), uvec{s}(32u))")?;
3385                                } else {
3386                                    write!(self.out, "ivec{s}(min(uvec{s}(findLSB(")?;
3387                                    self.write_expr(arg, ctx)?;
3388                                    write!(self.out, ")), uvec{s}(32u)))")?;
3389                                }
3390                            }
3391                            TypeInner::Scalar(scalar) => {
3392                                if let crate::ScalarKind::Uint = scalar.kind {
3393                                    write!(self.out, "min(uint(findLSB(")?;
3394                                    self.write_expr(arg, ctx)?;
3395                                    write!(self.out, ")), 32u)")?;
3396                                } else {
3397                                    write!(self.out, "int(min(uint(findLSB(")?;
3398                                    self.write_expr(arg, ctx)?;
3399                                    write!(self.out, ")), 32u))")?;
3400                                }
3401                            }
3402                            _ => unreachable!(),
3403                        };
3404                        return Ok(());
3405                    }
3406                    Mf::CountLeadingZeros => {
3407                        if self.options.version.supports_integer_functions() {
3408                            match *ctx.resolve_type(arg, &self.module.types) {
3409                                TypeInner::Vector { size, scalar } => {
3410                                    let s = common::vector_size_str(size);
3411
3412                                    if let crate::ScalarKind::Uint = scalar.kind {
3413                                        write!(self.out, "uvec{s}(ivec{s}(31) - findMSB(")?;
3414                                        self.write_expr(arg, ctx)?;
3415                                        write!(self.out, "))")?;
3416                                    } else {
3417                                        write!(self.out, "mix(ivec{s}(31) - findMSB(")?;
3418                                        self.write_expr(arg, ctx)?;
3419                                        write!(self.out, "), ivec{s}(0), lessThan(")?;
3420                                        self.write_expr(arg, ctx)?;
3421                                        write!(self.out, ", ivec{s}(0)))")?;
3422                                    }
3423                                }
3424                                TypeInner::Scalar(scalar) => {
3425                                    if let crate::ScalarKind::Uint = scalar.kind {
3426                                        write!(self.out, "uint(31 - findMSB(")?;
3427                                    } else {
3428                                        write!(self.out, "(")?;
3429                                        self.write_expr(arg, ctx)?;
3430                                        write!(self.out, " < 0 ? 0 : 31 - findMSB(")?;
3431                                    }
3432
3433                                    self.write_expr(arg, ctx)?;
3434                                    write!(self.out, "))")?;
3435                                }
3436                                _ => unreachable!(),
3437                            };
3438                        } else {
3439                            match *ctx.resolve_type(arg, &self.module.types) {
3440                                TypeInner::Vector { size, scalar } => {
3441                                    let s = common::vector_size_str(size);
3442
3443                                    if let crate::ScalarKind::Uint = scalar.kind {
3444                                        write!(self.out, "uvec{s}(")?;
3445                                        write!(self.out, "vec{s}(31.0) - floor(log2(vec{s}(")?;
3446                                        self.write_expr(arg, ctx)?;
3447                                        write!(self.out, ") + 0.5)))")?;
3448                                    } else {
3449                                        write!(self.out, "ivec{s}(")?;
3450                                        write!(self.out, "mix(vec{s}(31.0) - floor(log2(vec{s}(")?;
3451                                        self.write_expr(arg, ctx)?;
3452                                        write!(self.out, ") + 0.5)), ")?;
3453                                        write!(self.out, "vec{s}(0.0), lessThan(")?;
3454                                        self.write_expr(arg, ctx)?;
3455                                        write!(self.out, ", ivec{s}(0u))))")?;
3456                                    }
3457                                }
3458                                TypeInner::Scalar(scalar) => {
3459                                    if let crate::ScalarKind::Uint = scalar.kind {
3460                                        write!(self.out, "uint(31.0 - floor(log2(float(")?;
3461                                        self.write_expr(arg, ctx)?;
3462                                        write!(self.out, ") + 0.5)))")?;
3463                                    } else {
3464                                        write!(self.out, "(")?;
3465                                        self.write_expr(arg, ctx)?;
3466                                        write!(self.out, " < 0 ? 0 : int(")?;
3467                                        write!(self.out, "31.0 - floor(log2(float(")?;
3468                                        self.write_expr(arg, ctx)?;
3469                                        write!(self.out, ") + 0.5))))")?;
3470                                    }
3471                                }
3472                                _ => unreachable!(),
3473                            };
3474                        }
3475
3476                        return Ok(());
3477                    }
3478                    Mf::CountOneBits => "bitCount",
3479                    Mf::ReverseBits => "bitfieldReverse",
3480                    Mf::ExtractBits => {
3481                        // The behavior of ExtractBits is undefined when offset + count > bit_width. We need
3482                        // to first sanitize the offset and count first. If we don't do this, AMD and Intel chips
3483                        // will return out-of-spec values if the extracted range is not within the bit width.
3484                        //
3485                        // This encodes the exact formula specified by the wgsl spec, without temporary values:
3486                        // https://gpuweb.github.io/gpuweb/wgsl/#extractBits-unsigned-builtin
3487                        //
3488                        // w = sizeof(x) * 8
3489                        // o = min(offset, w)
3490                        // c = min(count, w - o)
3491                        //
3492                        // bitfieldExtract(x, o, c)
3493                        //
3494                        // extract_bits(e, min(offset, w), min(count, w - min(offset, w))))
3495                        let scalar_bits = ctx
3496                            .resolve_type(arg, &self.module.types)
3497                            .scalar_width()
3498                            .unwrap()
3499                            * 8;
3500
3501                        write!(self.out, "bitfieldExtract(")?;
3502                        self.write_expr(arg, ctx)?;
3503                        write!(self.out, ", int(min(")?;
3504                        self.write_expr(arg1.unwrap(), ctx)?;
3505                        write!(self.out, ", {scalar_bits}u)), int(min(",)?;
3506                        self.write_expr(arg2.unwrap(), ctx)?;
3507                        write!(self.out, ", {scalar_bits}u - min(")?;
3508                        self.write_expr(arg1.unwrap(), ctx)?;
3509                        write!(self.out, ", {scalar_bits}u))))")?;
3510
3511                        return Ok(());
3512                    }
3513                    Mf::InsertBits => {
3514                        // InsertBits has the same considerations as ExtractBits above
3515                        let scalar_bits = ctx
3516                            .resolve_type(arg, &self.module.types)
3517                            .scalar_width()
3518                            .unwrap()
3519                            * 8;
3520
3521                        write!(self.out, "bitfieldInsert(")?;
3522                        self.write_expr(arg, ctx)?;
3523                        write!(self.out, ", ")?;
3524                        self.write_expr(arg1.unwrap(), ctx)?;
3525                        write!(self.out, ", int(min(")?;
3526                        self.write_expr(arg2.unwrap(), ctx)?;
3527                        write!(self.out, ", {scalar_bits}u)), int(min(",)?;
3528                        self.write_expr(arg3.unwrap(), ctx)?;
3529                        write!(self.out, ", {scalar_bits}u - min(")?;
3530                        self.write_expr(arg2.unwrap(), ctx)?;
3531                        write!(self.out, ", {scalar_bits}u))))")?;
3532
3533                        return Ok(());
3534                    }
3535                    Mf::FirstTrailingBit => "findLSB",
3536                    Mf::FirstLeadingBit => "findMSB",
3537                    // data packing
3538                    Mf::Pack4x8snorm => {
3539                        if self.options.version.supports_pack_unpack_4x8() {
3540                            "packSnorm4x8"
3541                        } else {
3542                            // polyfill should go here. Needs a corresponding entry in `need_bake_expression`
3543                            return Err(Error::UnsupportedExternal("packSnorm4x8".into()));
3544                        }
3545                    }
3546                    Mf::Pack4x8unorm => {
3547                        if self.options.version.supports_pack_unpack_4x8() {
3548                            "packUnorm4x8"
3549                        } else {
3550                            return Err(Error::UnsupportedExternal("packUnorm4x8".to_owned()));
3551                        }
3552                    }
3553                    Mf::Pack2x16snorm => {
3554                        if self.options.version.supports_pack_unpack_snorm_2x16() {
3555                            "packSnorm2x16"
3556                        } else {
3557                            return Err(Error::UnsupportedExternal("packSnorm2x16".to_owned()));
3558                        }
3559                    }
3560                    Mf::Pack2x16unorm => {
3561                        if self.options.version.supports_pack_unpack_unorm_2x16() {
3562                            "packUnorm2x16"
3563                        } else {
3564                            return Err(Error::UnsupportedExternal("packUnorm2x16".to_owned()));
3565                        }
3566                    }
3567                    Mf::Pack2x16float => {
3568                        if self.options.version.supports_pack_unpack_half_2x16() {
3569                            "packHalf2x16"
3570                        } else {
3571                            return Err(Error::UnsupportedExternal("packHalf2x16".to_owned()));
3572                        }
3573                    }
3574
3575                    fun @ (Mf::Pack4xI8 | Mf::Pack4xU8 | Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp) => {
3576                        let was_signed = matches!(fun, Mf::Pack4xI8 | Mf::Pack4xI8Clamp);
3577                        let clamp_bounds = match fun {
3578                            Mf::Pack4xI8Clamp => Some(("-128", "127")),
3579                            Mf::Pack4xU8Clamp => Some(("0", "255")),
3580                            _ => None,
3581                        };
3582                        let const_suffix = if was_signed { "" } else { "u" };
3583                        if was_signed {
3584                            write!(self.out, "uint(")?;
3585                        }
3586                        let write_arg = |this: &mut Self| -> BackendResult {
3587                            if let Some((min, max)) = clamp_bounds {
3588                                write!(this.out, "clamp(")?;
3589                                this.write_expr(arg, ctx)?;
3590                                write!(this.out, ", {min}{const_suffix}, {max}{const_suffix})")?;
3591                            } else {
3592                                this.write_expr(arg, ctx)?;
3593                            }
3594                            Ok(())
3595                        };
3596                        write!(self.out, "(")?;
3597                        write_arg(self)?;
3598                        write!(self.out, "[0] & 0xFF{const_suffix}) | ((")?;
3599                        write_arg(self)?;
3600                        write!(self.out, "[1] & 0xFF{const_suffix}) << 8) | ((")?;
3601                        write_arg(self)?;
3602                        write!(self.out, "[2] & 0xFF{const_suffix}) << 16) | ((")?;
3603                        write_arg(self)?;
3604                        write!(self.out, "[3] & 0xFF{const_suffix}) << 24)")?;
3605                        if was_signed {
3606                            write!(self.out, ")")?;
3607                        }
3608
3609                        return Ok(());
3610                    }
3611                    // data unpacking
3612                    Mf::Unpack2x16float => {
3613                        if self.options.version.supports_pack_unpack_half_2x16() {
3614                            "unpackHalf2x16"
3615                        } else {
3616                            return Err(Error::UnsupportedExternal("unpackHalf2x16".into()));
3617                        }
3618                    }
3619                    Mf::Unpack2x16snorm => {
3620                        if self.options.version.supports_pack_unpack_snorm_2x16() {
3621                            "unpackSnorm2x16"
3622                        } else {
3623                            let scale = 32767;
3624
3625                            write!(self.out, "(vec2(ivec2(")?;
3626                            self.write_expr(arg, ctx)?;
3627                            write!(self.out, " << 16, ")?;
3628                            self.write_expr(arg, ctx)?;
3629                            write!(self.out, ") >> 16) / {scale}.0)")?;
3630                            return Ok(());
3631                        }
3632                    }
3633                    Mf::Unpack2x16unorm => {
3634                        if self.options.version.supports_pack_unpack_unorm_2x16() {
3635                            "unpackUnorm2x16"
3636                        } else {
3637                            let scale = 65535;
3638
3639                            write!(self.out, "(vec2(")?;
3640                            self.write_expr(arg, ctx)?;
3641                            write!(self.out, " & 0xFFFFu, ")?;
3642                            self.write_expr(arg, ctx)?;
3643                            write!(self.out, " >> 16) / {scale}.0)")?;
3644                            return Ok(());
3645                        }
3646                    }
3647                    Mf::Unpack4x8snorm => {
3648                        if self.options.version.supports_pack_unpack_4x8() {
3649                            "unpackSnorm4x8"
3650                        } else {
3651                            let scale = 127;
3652
3653                            write!(self.out, "(vec4(ivec4(")?;
3654                            self.write_expr(arg, ctx)?;
3655                            write!(self.out, " << 24, ")?;
3656                            self.write_expr(arg, ctx)?;
3657                            write!(self.out, " << 16, ")?;
3658                            self.write_expr(arg, ctx)?;
3659                            write!(self.out, " << 8, ")?;
3660                            self.write_expr(arg, ctx)?;
3661                            write!(self.out, ") >> 24) / {scale}.0)")?;
3662                            return Ok(());
3663                        }
3664                    }
3665                    Mf::Unpack4x8unorm => {
3666                        if self.options.version.supports_pack_unpack_4x8() {
3667                            "unpackUnorm4x8"
3668                        } else {
3669                            let scale = 255;
3670
3671                            write!(self.out, "(vec4(")?;
3672                            self.write_expr(arg, ctx)?;
3673                            write!(self.out, " & 0xFFu, ")?;
3674                            self.write_expr(arg, ctx)?;
3675                            write!(self.out, " >> 8 & 0xFFu, ")?;
3676                            self.write_expr(arg, ctx)?;
3677                            write!(self.out, " >> 16 & 0xFFu, ")?;
3678                            self.write_expr(arg, ctx)?;
3679                            write!(self.out, " >> 24) / {scale}.0)")?;
3680                            return Ok(());
3681                        }
3682                    }
3683                    fun @ (Mf::Unpack4xI8 | Mf::Unpack4xU8) => {
3684                        let sign_prefix = match fun {
3685                            Mf::Unpack4xI8 => 'i',
3686                            Mf::Unpack4xU8 => 'u',
3687                            _ => unreachable!(),
3688                        };
3689                        write!(self.out, "{sign_prefix}vec4(")?;
3690                        for i in 0..4 {
3691                            write!(self.out, "bitfieldExtract(")?;
3692                            // Since bitfieldExtract only sign extends if the value is signed, this
3693                            // cast is needed
3694                            match fun {
3695                                Mf::Unpack4xI8 => {
3696                                    write!(self.out, "int(")?;
3697                                    self.write_expr(arg, ctx)?;
3698                                    write!(self.out, ")")?;
3699                                }
3700                                Mf::Unpack4xU8 => self.write_expr(arg, ctx)?,
3701                                _ => unreachable!(),
3702                            };
3703                            write!(self.out, ", {}, 8)", i * 8)?;
3704                            if i != 3 {
3705                                write!(self.out, ", ")?;
3706                            }
3707                        }
3708                        write!(self.out, ")")?;
3709
3710                        return Ok(());
3711                    }
3712                };
3713
3714                let extract_bits = fun == Mf::ExtractBits;
3715                let insert_bits = fun == Mf::InsertBits;
3716
3717                // Some GLSL functions always return signed integers (like findMSB),
3718                // so they need to be cast to uint if the argument is also an uint.
3719                let ret_might_need_int_to_uint = matches!(
3720                    fun,
3721                    Mf::FirstTrailingBit | Mf::FirstLeadingBit | Mf::CountOneBits | Mf::Abs
3722                );
3723
3724                // Some GLSL functions only accept signed integers (like abs),
3725                // so they need their argument cast from uint to int.
3726                let arg_might_need_uint_to_int = matches!(fun, Mf::Abs);
3727
3728                // Check if the argument is an unsigned integer and return the vector size
3729                // in case it's a vector
3730                let maybe_uint_size = match *ctx.resolve_type(arg, &self.module.types) {
3731                    TypeInner::Scalar(crate::Scalar {
3732                        kind: crate::ScalarKind::Uint,
3733                        ..
3734                    }) => Some(None),
3735                    TypeInner::Vector {
3736                        scalar:
3737                            crate::Scalar {
3738                                kind: crate::ScalarKind::Uint,
3739                                ..
3740                            },
3741                        size,
3742                    } => Some(Some(size)),
3743                    _ => None,
3744                };
3745
3746                // Cast to uint if the function needs it
3747                if ret_might_need_int_to_uint {
3748                    if let Some(maybe_size) = maybe_uint_size {
3749                        match maybe_size {
3750                            Some(size) => write!(self.out, "uvec{}(", size as u8)?,
3751                            None => write!(self.out, "uint(")?,
3752                        }
3753                    }
3754                }
3755
3756                write!(self.out, "{fun_name}(")?;
3757
3758                // Cast to int if the function needs it
3759                if arg_might_need_uint_to_int {
3760                    if let Some(maybe_size) = maybe_uint_size {
3761                        match maybe_size {
3762                            Some(size) => write!(self.out, "ivec{}(", size as u8)?,
3763                            None => write!(self.out, "int(")?,
3764                        }
3765                    }
3766                }
3767
3768                self.write_expr(arg, ctx)?;
3769
3770                // Close the cast from uint to int
3771                if arg_might_need_uint_to_int && maybe_uint_size.is_some() {
3772                    write!(self.out, ")")?
3773                }
3774
3775                if let Some(arg) = arg1 {
3776                    write!(self.out, ", ")?;
3777                    if extract_bits {
3778                        write!(self.out, "int(")?;
3779                        self.write_expr(arg, ctx)?;
3780                        write!(self.out, ")")?;
3781                    } else {
3782                        self.write_expr(arg, ctx)?;
3783                    }
3784                }
3785                if let Some(arg) = arg2 {
3786                    write!(self.out, ", ")?;
3787                    if extract_bits || insert_bits {
3788                        write!(self.out, "int(")?;
3789                        self.write_expr(arg, ctx)?;
3790                        write!(self.out, ")")?;
3791                    } else {
3792                        self.write_expr(arg, ctx)?;
3793                    }
3794                }
3795                if let Some(arg) = arg3 {
3796                    write!(self.out, ", ")?;
3797                    if insert_bits {
3798                        write!(self.out, "int(")?;
3799                        self.write_expr(arg, ctx)?;
3800                        write!(self.out, ")")?;
3801                    } else {
3802                        self.write_expr(arg, ctx)?;
3803                    }
3804                }
3805                write!(self.out, ")")?;
3806
3807                // Close the cast from int to uint
3808                if ret_might_need_int_to_uint && maybe_uint_size.is_some() {
3809                    write!(self.out, ")")?
3810                }
3811            }
3812            // `As` is always a call, whose name is the target type.
3813            Expression::As { expr, target } => {
3814                let inner = ctx.resolve_type(expr, &self.module.types);
3815                // this is similar to `write_type`, but with the target scalar
3816                let scalar = glsl_scalar(target)?;
3817                match *inner {
3818                    TypeInner::Matrix { columns, rows, .. } => write!(
3819                        self.out,
3820                        "{}mat{}x{}",
3821                        scalar.prefix, columns as u8, rows as u8
3822                    )?,
3823                    TypeInner::Vector { size, .. } => {
3824                        write!(self.out, "{}vec{}", scalar.prefix, size as u8)?
3825                    }
3826                    _ => write!(self.out, "{}", scalar.full)?,
3827                }
3828
3829                write!(self.out, "(")?;
3830                self.write_expr(expr, ctx)?;
3831                write!(self.out, ")")?
3832            }
3833            // `Bitcast` is a call to one of the glsl provided bitcast functions,
3834            // or to a constructor when only the signedness of an integer changes.
3835            Expression::Bitcast { expr, ty } => {
3836                use crate::ScalarKind as Sk;
3837
3838                let inner = ctx.resolve_type(expr, &self.module.types);
3839                let target = &self.module.types[ty].inner;
3840
3841                if inner == target {
3842                    return self.write_expr(expr, ctx);
3843                }
3844
3845                let unsupported =
3846                    || Error::Custom(format!("GLSL cannot bitcast from {inner:?} to {target:?}"));
3847                let (Some((src_size, src)), Some((dst_size, dst))) = (
3848                    inner.vector_size_and_scalar(),
3849                    target.vector_size_and_scalar(),
3850                ) else {
3851                    return Err(unsupported());
3852                };
3853                if src_size != dst_size {
3854                    return Err(unsupported());
3855                }
3856
3857                match (src.kind, dst.kind) {
3858                    (Sk::Float, Sk::Sint) if src.width == 4 => write!(self.out, "floatBitsToInt")?,
3859                    (Sk::Float, Sk::Uint) if src.width == 4 => write!(self.out, "floatBitsToUint")?,
3860                    (Sk::Sint, Sk::Float) if src.width == 4 => write!(self.out, "intBitsToFloat")?,
3861                    (Sk::Uint, Sk::Float) if src.width == 4 => write!(self.out, "uintBitsToFloat")?,
3862                    // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion
3863                    (Sk::Uint, Sk::Sint) | (Sk::Sint, Sk::Uint) => {
3864                        self.write_value_type(target)?;
3865                    }
3866                    _ => return Err(unsupported()),
3867                };
3868
3869                write!(self.out, "(")?;
3870                self.write_expr(expr, ctx)?;
3871                write!(self.out, ")")?;
3872            }
3873            // These expressions never show up in `Emit`.
3874            Expression::CallResult(_)
3875            | Expression::AtomicResult { .. }
3876            | Expression::RayQueryProceedResult
3877            | Expression::WorkGroupUniformLoadResult { .. }
3878            | Expression::SubgroupOperationResult { .. }
3879            | Expression::SubgroupBallotResult => unreachable!(),
3880            // `ArrayLength` is written as `expr.length()` and we convert it to a uint
3881            Expression::ArrayLength(expr) => {
3882                write!(self.out, "uint(")?;
3883                self.write_expr(expr, ctx)?;
3884                write!(self.out, ".length())")?
3885            }
3886            // not supported yet
3887            Expression::RayQueryGetIntersection { .. }
3888            | Expression::RayQueryVertexPositions { .. }
3889            | Expression::HitObjectQuery { .. }
3890            | Expression::CooperativeLoad { .. }
3891            | Expression::CooperativeMultiplyAdd { .. } => unreachable!(),
3892        }
3893
3894        Ok(())
3895    }
3896
3897    /// Writes `expr`, wrapped in `int(...)` if it is an unsigned scalar.
3898    ///
3899    /// GLSL image functions only take `int` levels and sample indices, while WGSL also
3900    /// allows `u32`.
3901    fn write_expr_as_int(
3902        &mut self,
3903        expr: Handle<crate::Expression>,
3904        ctx: &back::FunctionCtx,
3905    ) -> BackendResult {
3906        let cast_to_int = matches!(
3907            *ctx.resolve_type(expr, &self.module.types),
3908            TypeInner::Scalar(crate::Scalar {
3909                kind: crate::ScalarKind::Uint,
3910                ..
3911            })
3912        );
3913
3914        if cast_to_int {
3915            write!(self.out, "int(")?;
3916        }
3917
3918        self.write_expr(expr, ctx)?;
3919
3920        if cast_to_int {
3921            write!(self.out, ")")?;
3922        }
3923
3924        Ok(())
3925    }
3926
3927    /// Helper function to write the local holding the clamped lod
3928    fn write_clamped_lod(
3929        &mut self,
3930        ctx: &back::FunctionCtx,
3931        expr: Handle<crate::Expression>,
3932        image: Handle<crate::Expression>,
3933        level_expr: Handle<crate::Expression>,
3934    ) -> Result<(), Error> {
3935        // Define our local and start a call to `clamp`
3936        write!(
3937            self.out,
3938            "int {}{} = clamp(",
3939            Baked(expr),
3940            CLAMPED_LOD_SUFFIX
3941        )?;
3942        // Write the lod that will be clamped
3943        self.write_expr_as_int(level_expr, ctx)?;
3944        // Set the min value to 0 and start a call to `textureQueryLevels` to get
3945        // the maximum value
3946        write!(self.out, ", 0, textureQueryLevels(")?;
3947        // Write the target image as an argument to `textureQueryLevels`
3948        self.write_expr(image, ctx)?;
3949        // Close the call to `textureQueryLevels` subtract 1 from it since
3950        // the lod argument is 0 based, close the `clamp` call and end the
3951        // local declaration statement.
3952        writeln!(self.out, ") - 1);")?;
3953
3954        Ok(())
3955    }
3956
3957    // Helper method used to retrieve how many elements a coordinate vector
3958    // for the images operations need.
3959    fn get_coordinate_vector_size(&self, dim: crate::ImageDimension, arrayed: bool) -> u8 {
3960        // openGL es doesn't have 1D images so we need workaround it
3961        let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es();
3962        // Get how many components the coordinate vector needs for the dimensions only
3963        let tex_coord_size = match dim {
3964            crate::ImageDimension::D1 => 1,
3965            crate::ImageDimension::D2 => 2,
3966            crate::ImageDimension::D3 => 3,
3967            crate::ImageDimension::Cube => 2,
3968        };
3969        // Calculate the true size of the coordinate vector by adding 1 for arrayed images
3970        // and another 1 if we need to workaround 1D images by making them 2D
3971        tex_coord_size + tex_1d_hack as u8 + arrayed as u8
3972    }
3973
3974    /// Helper method to write the coordinate vector for image operations
3975    fn write_texture_coord(
3976        &mut self,
3977        ctx: &back::FunctionCtx,
3978        vector_size: u8,
3979        coordinate: Handle<crate::Expression>,
3980        array_index: Option<Handle<crate::Expression>>,
3981        // Emulate 1D images as 2D for profiles that don't support it (glsl es)
3982        tex_1d_hack: bool,
3983    ) -> Result<(), Error> {
3984        match array_index {
3985            // If the image needs an array indice we need to add it to the end of our
3986            // coordinate vector, to do so we will use the `ivec(ivec, scalar)`
3987            // constructor notation (NOTE: the inner `ivec` can also be a scalar, this
3988            // is important for 1D arrayed images).
3989            Some(layer_expr) => {
3990                write!(self.out, "ivec{vector_size}(")?;
3991                self.write_expr(coordinate, ctx)?;
3992                write!(self.out, ", ")?;
3993                // If we are replacing sampler1D with sampler2D we also need
3994                // to add another zero to the coordinates vector for the y component
3995                if tex_1d_hack {
3996                    write!(self.out, "0, ")?;
3997                }
3998                self.write_expr(layer_expr, ctx)?;
3999                write!(self.out, ")")?;
4000            }
4001            // Otherwise write just the expression (and the 1D hack if needed)
4002            None => {
4003                let uvec_size = match *ctx.resolve_type(coordinate, &self.module.types) {
4004                    TypeInner::Scalar(crate::Scalar {
4005                        kind: crate::ScalarKind::Uint,
4006                        ..
4007                    }) => Some(None),
4008                    TypeInner::Vector {
4009                        size,
4010                        scalar:
4011                            crate::Scalar {
4012                                kind: crate::ScalarKind::Uint,
4013                                ..
4014                            },
4015                    } => Some(Some(size as u32)),
4016                    _ => None,
4017                };
4018                if tex_1d_hack {
4019                    write!(self.out, "ivec2(")?;
4020                } else if uvec_size.is_some() {
4021                    match uvec_size {
4022                        Some(None) => write!(self.out, "int(")?,
4023                        Some(Some(size)) => write!(self.out, "ivec{size}(")?,
4024                        _ => {}
4025                    }
4026                }
4027                self.write_expr(coordinate, ctx)?;
4028                if tex_1d_hack {
4029                    write!(self.out, ", 0)")?;
4030                } else if uvec_size.is_some() {
4031                    write!(self.out, ")")?;
4032                }
4033            }
4034        }
4035
4036        Ok(())
4037    }
4038
4039    /// Helper method to write the `ImageStore` statement
4040    fn write_image_store(
4041        &mut self,
4042        ctx: &back::FunctionCtx,
4043        image: Handle<crate::Expression>,
4044        coordinate: Handle<crate::Expression>,
4045        array_index: Option<Handle<crate::Expression>>,
4046        value: Handle<crate::Expression>,
4047    ) -> Result<(), Error> {
4048        use crate::ImageDimension as IDim;
4049
4050        // NOTE: openGL requires that `imageStore`s have no effects when the texel is invalid
4051        // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20)
4052
4053        // This will only panic if the module is invalid
4054        let dim = match *ctx.resolve_type(image, &self.module.types) {
4055            TypeInner::Image { dim, .. } => dim,
4056            _ => unreachable!(),
4057        };
4058
4059        // Begin our call to `imageStore`
4060        write!(self.out, "imageStore(")?;
4061        self.write_expr(image, ctx)?;
4062        // Separate the image argument from the coordinates
4063        write!(self.out, ", ")?;
4064
4065        // openGL es doesn't have 1D images so we need workaround it
4066        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4067        // Write the coordinate vector
4068        self.write_texture_coord(
4069            ctx,
4070            // Get the size of the coordinate vector
4071            self.get_coordinate_vector_size(dim, array_index.is_some()),
4072            coordinate,
4073            array_index,
4074            tex_1d_hack,
4075        )?;
4076
4077        // Separate the coordinate from the value to write and write the expression
4078        // of the value to write.
4079        write!(self.out, ", ")?;
4080        self.write_expr(value, ctx)?;
4081        // End the call to `imageStore` and the statement.
4082        writeln!(self.out, ");")?;
4083
4084        Ok(())
4085    }
4086
4087    /// Helper method to write the `ImageAtomic` statement
4088    fn write_image_atomic(
4089        &mut self,
4090        ctx: &back::FunctionCtx,
4091        image: Handle<crate::Expression>,
4092        coordinate: Handle<crate::Expression>,
4093        array_index: Option<Handle<crate::Expression>>,
4094        fun: crate::AtomicFunction,
4095        value: Handle<crate::Expression>,
4096    ) -> Result<(), Error> {
4097        use crate::ImageDimension as IDim;
4098
4099        // NOTE: openGL requires that `imageAtomic`s have no effects when the texel is invalid
4100        // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20)
4101
4102        // This will only panic if the module is invalid
4103        let dim = match *ctx.resolve_type(image, &self.module.types) {
4104            TypeInner::Image { dim, .. } => dim,
4105            _ => unreachable!(),
4106        };
4107
4108        // Begin our call to `imageAtomic`
4109        let fun_str = fun.to_glsl();
4110        write!(self.out, "imageAtomic{fun_str}(")?;
4111        self.write_expr(image, ctx)?;
4112        // Separate the image argument from the coordinates
4113        write!(self.out, ", ")?;
4114
4115        // openGL es doesn't have 1D images so we need workaround it
4116        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4117        // Write the coordinate vector
4118        self.write_texture_coord(
4119            ctx,
4120            // Get the size of the coordinate vector
4121            self.get_coordinate_vector_size(dim, false),
4122            coordinate,
4123            array_index,
4124            tex_1d_hack,
4125        )?;
4126
4127        // Separate the coordinate from the value to write and write the expression
4128        // of the value to write.
4129        write!(self.out, ", ")?;
4130        self.write_expr(value, ctx)?;
4131        // End the call to `imageAtomic` and the statement.
4132        writeln!(self.out, ");")?;
4133
4134        Ok(())
4135    }
4136
4137    /// Helper method for writing an `ImageLoad` expression.
4138    #[allow(clippy::too_many_arguments)]
4139    fn write_image_load(
4140        &mut self,
4141        handle: Handle<crate::Expression>,
4142        ctx: &back::FunctionCtx,
4143        image: Handle<crate::Expression>,
4144        coordinate: Handle<crate::Expression>,
4145        array_index: Option<Handle<crate::Expression>>,
4146        sample: Option<Handle<crate::Expression>>,
4147        level: Option<Handle<crate::Expression>>,
4148    ) -> Result<(), Error> {
4149        use crate::ImageDimension as IDim;
4150
4151        // `ImageLoad` is a bit complicated.
4152        // There are two functions one for sampled
4153        // images another for storage images, the former uses `texelFetch` and the
4154        // latter uses `imageLoad`.
4155        //
4156        // Furthermore we have `level` which is always `Some` for sampled images
4157        // and `None` for storage images, so we end up with two functions:
4158        // - `texelFetch(image, coordinate, level)` for sampled images
4159        // - `imageLoad(image, coordinate)` for storage images
4160        //
4161        // Finally we also have to consider bounds checking, for storage images
4162        // this is easy since openGL requires that invalid texels always return
4163        // 0, for sampled images we need to either verify that all arguments are
4164        // in bounds (`ReadZeroSkipWrite`) or make them a valid texel (`Restrict`).
4165
4166        // This will only panic if the module is invalid
4167        let (dim, class) = match *ctx.resolve_type(image, &self.module.types) {
4168            TypeInner::Image {
4169                dim,
4170                arrayed: _,
4171                class,
4172            } => (dim, class),
4173            _ => unreachable!(),
4174        };
4175
4176        // Get the name of the function to be used for the load operation
4177        // and the policy to be used with it.
4178        let (fun_name, policy) = match class {
4179            // Sampled images inherit the policy from the user passed policies
4180            crate::ImageClass::Sampled { .. } => ("texelFetch", self.policies.image_load),
4181            crate::ImageClass::Storage { .. } => {
4182                // OpenGL ES 3.1 mentions in Chapter "8.22 Texture Image Loads and Stores" that:
4183                // "Invalid image loads will return a vector where the value of R, G, and B components
4184                // is 0 and the value of the A component is undefined."
4185                //
4186                // OpenGL 4.2 Core mentions in Chapter "3.9.20 Texture Image Loads and Stores" that:
4187                // "Invalid image loads will return zero."
4188                //
4189                // So, we only inject bounds checks for ES
4190                let policy = if self.options.version.is_es() {
4191                    self.policies.image_load
4192                } else {
4193                    proc::BoundsCheckPolicy::Unchecked
4194                };
4195                ("imageLoad", policy)
4196            }
4197            // TODO: Is there even a function for this?
4198            crate::ImageClass::Depth { multi: _ } => {
4199                return Err(Error::Custom(
4200                    "WGSL `textureLoad` from depth textures is not supported in GLSL".to_string(),
4201                ))
4202            }
4203            crate::ImageClass::External => unimplemented!(),
4204        };
4205
4206        // openGL es doesn't have 1D images so we need workaround it
4207        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4208        // Get the size of the coordinate vector
4209        let vector_size = self.get_coordinate_vector_size(dim, array_index.is_some());
4210
4211        if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy {
4212            // To write the bounds checks for `ReadZeroSkipWrite` we will use a
4213            // ternary operator since we are in the middle of an expression and
4214            // need to return a value.
4215            //
4216            // NOTE: glsl does short circuit when evaluating logical
4217            // expressions so we can be sure that after we test a
4218            // condition it will be true for the next ones
4219
4220            // Write parentheses around the ternary operator to prevent problems with
4221            // expressions emitted before or after it having more precedence
4222            write!(self.out, "(",)?;
4223
4224            // The lod check needs to precede the size check since we need
4225            // to use the lod to get the size of the image at that level.
4226            if let Some(level_expr) = level {
4227                self.write_expr(level_expr, ctx)?;
4228                write!(self.out, " < textureQueryLevels(",)?;
4229                self.write_expr(image, ctx)?;
4230                // Chain the next check
4231                write!(self.out, ") && ")?;
4232            }
4233
4234            // Check that the sample arguments doesn't exceed the number of samples
4235            if let Some(sample_expr) = sample {
4236                self.write_expr(sample_expr, ctx)?;
4237                write!(self.out, " < textureSamples(",)?;
4238                self.write_expr(image, ctx)?;
4239                // Chain the next check
4240                write!(self.out, ") && ")?;
4241            }
4242
4243            // We now need to write the size checks for the coordinates and array index
4244            // first we write the comparison function in case the image is 1D non arrayed
4245            // (and no 1D to 2D hack was needed) we are comparing scalars so the less than
4246            // operator will suffice, but otherwise we'll be comparing two vectors so we'll
4247            // need to use the `lessThan` function but it returns a vector of booleans (one
4248            // for each comparison) so we need to fold it all in one scalar boolean, since
4249            // we want all comparisons to pass we use the `all` function which will only
4250            // return `true` if all the elements of the boolean vector are also `true`.
4251            //
4252            // So we'll end with one of the following forms
4253            // - `coord < textureSize(image, lod)` for 1D images
4254            // - `all(lessThan(coord, textureSize(image, lod)))` for normal images
4255            // - `all(lessThan(ivec(coord, array_index), textureSize(image, lod)))`
4256            //    for arrayed images
4257            // - `all(lessThan(coord, textureSize(image)))` for multi sampled images
4258
4259            if vector_size != 1 {
4260                write!(self.out, "all(lessThan(")?;
4261            }
4262
4263            // Write the coordinate vector
4264            self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?;
4265
4266            if vector_size != 1 {
4267                // If we used the `lessThan` function we need to separate the
4268                // coordinates from the image size.
4269                write!(self.out, ", ")?;
4270            } else {
4271                // If we didn't use it (ie. 1D images) we perform the comparison
4272                // using the less than operator.
4273                write!(self.out, " < ")?;
4274            }
4275
4276            // Call `textureSize` to get our image size
4277            write!(self.out, "textureSize(")?;
4278            self.write_expr(image, ctx)?;
4279            // `textureSize` uses the lod as a second argument for mipmapped images
4280            if let Some(level_expr) = level {
4281                // Separate the image from the lod
4282                write!(self.out, ", ")?;
4283                self.write_expr_as_int(level_expr, ctx)?;
4284            }
4285            // Close the `textureSize` call
4286            write!(self.out, ")")?;
4287
4288            if vector_size != 1 {
4289                // Close the `all` and `lessThan` calls
4290                write!(self.out, "))")?;
4291            }
4292
4293            // Finally end the condition part of the ternary operator
4294            write!(self.out, " ? ")?;
4295        }
4296
4297        // Begin the call to the function used to load the texel
4298        write!(self.out, "{fun_name}(")?;
4299        self.write_expr(image, ctx)?;
4300        write!(self.out, ", ")?;
4301
4302        // If we are using `Restrict` bounds checking we need to pass valid texel
4303        // coordinates, to do so we use the `clamp` function to get a value between
4304        // 0 and the image size - 1 (indexing begins at 0)
4305        if let proc::BoundsCheckPolicy::Restrict = policy {
4306            write!(self.out, "clamp(")?;
4307        }
4308
4309        // Write the coordinate vector
4310        self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?;
4311
4312        // If we are using `Restrict` bounds checking we need to write the rest of the
4313        // clamp we initiated before writing the coordinates.
4314        if let proc::BoundsCheckPolicy::Restrict = policy {
4315            // Write the min value 0
4316            if vector_size == 1 {
4317                write!(self.out, ", 0")?;
4318            } else {
4319                write!(self.out, ", ivec{vector_size}(0)")?;
4320            }
4321            // Start the `textureSize` call to use as the max value.
4322            write!(self.out, ", textureSize(")?;
4323            self.write_expr(image, ctx)?;
4324            // If the image is mipmapped we need to add the lod argument to the
4325            // `textureSize` call, but this needs to be the clamped lod, this should
4326            // have been generated earlier and put in a local.
4327            if class.is_mipmapped() {
4328                write!(self.out, ", {}{}", Baked(handle), CLAMPED_LOD_SUFFIX)?;
4329            }
4330            // Close the `textureSize` call
4331            write!(self.out, ")")?;
4332
4333            // Subtract 1 from the `textureSize` call since the coordinates are zero based.
4334            if vector_size == 1 {
4335                write!(self.out, " - 1")?;
4336            } else {
4337                write!(self.out, " - ivec{vector_size}(1)")?;
4338            }
4339
4340            // Close the `clamp` call
4341            write!(self.out, ")")?;
4342
4343            // Add the clamped lod (if present) as the second argument to the
4344            // image load function.
4345            if level.is_some() {
4346                write!(self.out, ", {}{}", Baked(handle), CLAMPED_LOD_SUFFIX)?;
4347            }
4348
4349            // If a sample argument is needed we need to clamp it between 0 and
4350            // the number of samples the image has.
4351            if let Some(sample_expr) = sample {
4352                write!(self.out, ", clamp(")?;
4353                self.write_expr_as_int(sample_expr, ctx)?;
4354                // Set the min value to 0 and start the call to `textureSamples`
4355                write!(self.out, ", 0, textureSamples(")?;
4356                self.write_expr(image, ctx)?;
4357                // Close the `textureSamples` call, subtract 1 from it since the sample
4358                // argument is zero based, and close the `clamp` call
4359                writeln!(self.out, ") - 1)")?;
4360            }
4361        } else if let Some(sample_or_level) = sample.or(level) {
4362            // If no bounds checking is need just add the sample or level argument
4363            // after the coordinates
4364            write!(self.out, ", ")?;
4365            self.write_expr_as_int(sample_or_level, ctx)?;
4366        }
4367
4368        // Close the image load function.
4369        write!(self.out, ")")?;
4370
4371        // If we were using the `ReadZeroSkipWrite` policy we need to end the first branch
4372        // (which is taken if the condition is `true`) with a colon (`:`) and write the
4373        // second branch which is just a 0 value.
4374        if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy {
4375            // Get the kind of the output value.
4376            let kind = match class {
4377                // Only sampled images can reach here since storage images
4378                // don't need bounds checks and depth images aren't implemented
4379                crate::ImageClass::Sampled { kind, .. } => kind,
4380                _ => unreachable!(),
4381            };
4382
4383            // End the first branch
4384            write!(self.out, " : ")?;
4385            // Write the 0 value
4386            write!(
4387                self.out,
4388                "{}vec4(",
4389                glsl_scalar(crate::Scalar { kind, width: 4 })?.prefix,
4390            )?;
4391            self.write_zero_init_scalar(kind)?;
4392            // Close the zero value constructor
4393            write!(self.out, ")")?;
4394            // Close the parentheses surrounding our ternary
4395            write!(self.out, ")")?;
4396        }
4397
4398        Ok(())
4399    }
4400
4401    fn write_named_expr(
4402        &mut self,
4403        handle: Handle<crate::Expression>,
4404        name: String,
4405        // The expression which is being named.
4406        // Generally, this is the same as handle, except in WorkGroupUniformLoad
4407        named: Handle<crate::Expression>,
4408        ctx: &back::FunctionCtx,
4409    ) -> BackendResult {
4410        match ctx.info[named].ty {
4411            proc::TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner {
4412                TypeInner::Struct { .. } => {
4413                    let ty_name = &self.names[&NameKey::Type(ty_handle)];
4414                    write!(self.out, "{ty_name}")?;
4415                }
4416                _ => {
4417                    self.write_type(ty_handle)?;
4418                }
4419            },
4420            proc::TypeResolution::Value(ref inner) => {
4421                self.write_value_type(inner)?;
4422            }
4423        }
4424
4425        let resolved = ctx.resolve_type(named, &self.module.types);
4426
4427        write!(self.out, " {name}")?;
4428        if let TypeInner::Array { base, size, .. } = *resolved {
4429            self.write_array_size(base, size)?;
4430        }
4431        write!(self.out, " = ")?;
4432        self.write_expr(handle, ctx)?;
4433        writeln!(self.out, ";")?;
4434        self.named_expressions.insert(named, name);
4435
4436        Ok(())
4437    }
4438
4439    /// Helper function that write string with default zero initialization for supported types
4440    fn write_zero_init_value(&mut self, ty: Handle<crate::Type>) -> BackendResult {
4441        let inner = &self.module.types[ty].inner;
4442        match *inner {
4443            TypeInner::Scalar(scalar) | TypeInner::Atomic(scalar) => {
4444                self.write_zero_init_scalar(scalar.kind)?;
4445            }
4446            TypeInner::Vector { scalar, .. } => {
4447                self.write_value_type(inner)?;
4448                write!(self.out, "(")?;
4449                self.write_zero_init_scalar(scalar.kind)?;
4450                write!(self.out, ")")?;
4451            }
4452            TypeInner::Matrix { .. } => {
4453                self.write_value_type(inner)?;
4454                write!(self.out, "(")?;
4455                self.write_zero_init_scalar(crate::ScalarKind::Float)?;
4456                write!(self.out, ")")?;
4457            }
4458            TypeInner::Array { base, size, .. } => {
4459                let count = match size.resolve(self.module.to_ctx())? {
4460                    proc::IndexableLength::Known(count) => count,
4461                    proc::IndexableLength::Dynamic => return Ok(()),
4462                };
4463                self.write_type(base)?;
4464                self.write_array_size(base, size)?;
4465                write!(self.out, "(")?;
4466                for _ in 1..count {
4467                    self.write_zero_init_value(base)?;
4468                    write!(self.out, ", ")?;
4469                }
4470                // write last parameter without comma and space
4471                self.write_zero_init_value(base)?;
4472                write!(self.out, ")")?;
4473            }
4474            TypeInner::Struct { ref members, .. } => {
4475                let name = &self.names[&NameKey::Type(ty)];
4476                write!(self.out, "{name}(")?;
4477                for (index, member) in members.iter().enumerate() {
4478                    if index != 0 {
4479                        write!(self.out, ", ")?;
4480                    }
4481                    self.write_zero_init_value(member.ty)?;
4482                }
4483                write!(self.out, ")")?;
4484            }
4485            _ => unreachable!(),
4486        }
4487
4488        Ok(())
4489    }
4490
4491    /// Helper function that write string with zero initialization for scalar
4492    fn write_zero_init_scalar(&mut self, kind: crate::ScalarKind) -> BackendResult {
4493        match kind {
4494            crate::ScalarKind::Bool => write!(self.out, "false")?,
4495            crate::ScalarKind::Uint => write!(self.out, "0u")?,
4496            crate::ScalarKind::Float => write!(self.out, "0.0")?,
4497            crate::ScalarKind::Sint => write!(self.out, "0")?,
4498            crate::ScalarKind::AbstractInt | crate::ScalarKind::AbstractFloat => {
4499                return Err(Error::Custom(
4500                    "Abstract types should not appear in IR presented to backends".to_string(),
4501                ))
4502            }
4503        }
4504
4505        Ok(())
4506    }
4507
4508    /// Issue a control barrier.
4509    fn write_control_barrier(
4510        &mut self,
4511        flags: crate::Barrier,
4512        level: back::Level,
4513    ) -> BackendResult {
4514        self.write_memory_barrier(flags, level)?;
4515        writeln!(self.out, "{level}barrier();")?;
4516        Ok(())
4517    }
4518
4519    /// Issue a memory barrier.
4520    fn write_memory_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult {
4521        if flags.contains(crate::Barrier::STORAGE) {
4522            writeln!(self.out, "{level}memoryBarrierBuffer();")?;
4523        }
4524        if flags.contains(crate::Barrier::WORK_GROUP) {
4525            writeln!(self.out, "{level}memoryBarrierShared();")?;
4526        }
4527        if flags.contains(crate::Barrier::SUB_GROUP) {
4528            writeln!(self.out, "{level}subgroupMemoryBarrier();")?;
4529        }
4530        if flags.contains(crate::Barrier::TEXTURE) {
4531            writeln!(self.out, "{level}memoryBarrierImage();")?;
4532        }
4533        Ok(())
4534    }
4535
4536    /// Helper function that return the glsl storage access string of [`StorageAccess`](crate::StorageAccess)
4537    ///
4538    /// glsl allows adding both `readonly` and `writeonly` but this means that
4539    /// they can only be used to query information about the resource which isn't what
4540    /// we want here so when storage access is both `LOAD` and `STORE` add no modifiers
4541    fn write_storage_access(&mut self, storage_access: crate::StorageAccess) -> BackendResult {
4542        if storage_access.contains(crate::StorageAccess::ATOMIC) {
4543            return Ok(());
4544        }
4545        if !storage_access.contains(crate::StorageAccess::STORE) {
4546            write!(self.out, "readonly ")?;
4547        }
4548        if !storage_access.contains(crate::StorageAccess::LOAD) {
4549            write!(self.out, "writeonly ")?;
4550        }
4551        Ok(())
4552    }
4553
4554    /// Helper method used to produce the reflection info that's returned to the user
4555    fn collect_reflection_info(&mut self) -> Result<ReflectionInfo, Error> {
4556        let info = self.info.get_entry_point(self.entry_point_idx as usize);
4557        let mut texture_mapping = crate::FastHashMap::default();
4558        let mut uniforms = crate::FastHashMap::default();
4559
4560        for sampling in info.sampling_set.iter() {
4561            let tex_name = self.reflection_names_globals[&sampling.image].clone();
4562
4563            match texture_mapping.entry(tex_name) {
4564                hash_map::Entry::Vacant(v) => {
4565                    v.insert(TextureMapping {
4566                        texture: sampling.image,
4567                        sampler: Some(sampling.sampler),
4568                    });
4569                }
4570                hash_map::Entry::Occupied(e) => {
4571                    if e.get().sampler != Some(sampling.sampler) {
4572                        log::error!("Conflicting samplers for {}", e.key());
4573                        return Err(Error::ImageMultipleSamplers);
4574                    }
4575                }
4576            }
4577        }
4578
4579        let mut immediates_info = None;
4580        for (handle, var) in self.module.global_variables.iter() {
4581            if info[handle].is_empty() {
4582                continue;
4583            }
4584            match self.module.types[var.ty].inner {
4585                TypeInner::Image { .. } => {
4586                    let tex_name = self.reflection_names_globals[&handle].clone();
4587                    match texture_mapping.entry(tex_name) {
4588                        hash_map::Entry::Vacant(v) => {
4589                            v.insert(TextureMapping {
4590                                texture: handle,
4591                                sampler: None,
4592                            });
4593                        }
4594                        hash_map::Entry::Occupied(_) => {
4595                            // already used with a sampler, do nothing
4596                        }
4597                    }
4598                }
4599                _ => match var.space {
4600                    crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => {
4601                        let name = self.reflection_names_globals[&handle].clone();
4602                        uniforms.insert(handle, name);
4603                    }
4604                    crate::AddressSpace::Immediate => {
4605                        let name = self.reflection_names_globals[&handle].clone();
4606                        immediates_info = Some((name, var.ty));
4607                    }
4608                    _ => (),
4609                },
4610            }
4611        }
4612
4613        let mut immediates_segments = Vec::new();
4614        let mut immediates_items = vec![];
4615
4616        if let Some((name, ty)) = immediates_info {
4617            // We don't have a layouter available to us, so we need to create one.
4618            //
4619            // This is potentially a bit wasteful, but the set of types in the program
4620            // shouldn't be too large.
4621            let mut layouter = proc::Layouter::default();
4622            layouter.update(self.module.to_ctx()).unwrap();
4623
4624            // We start with the name of the binding itself.
4625            immediates_segments.push(name);
4626
4627            // We then recursively collect all the uniform fields of the immediate data.
4628            self.collect_immediates_items(
4629                ty,
4630                &mut immediates_segments,
4631                &layouter,
4632                &mut 0,
4633                &mut immediates_items,
4634            );
4635        }
4636
4637        Ok(ReflectionInfo {
4638            texture_mapping,
4639            uniforms,
4640            varying: mem::take(&mut self.varying),
4641            immediates_items,
4642            clip_distance_count: self.clip_distance_count,
4643        })
4644    }
4645
4646    fn collect_immediates_items(
4647        &mut self,
4648        ty: Handle<crate::Type>,
4649        segments: &mut Vec<String>,
4650        layouter: &proc::Layouter,
4651        offset: &mut u32,
4652        items: &mut Vec<ImmediateItem>,
4653    ) {
4654        // At this point in the recursion, `segments` contains the path
4655        // needed to access `ty` from the root.
4656
4657        let layout = &layouter[ty];
4658        *offset = layout.alignment.round_up(*offset);
4659        match self.module.types[ty].inner {
4660            // All these types map directly to GL uniforms.
4661            TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => {
4662                // Build the full name, by combining all current segments.
4663                let name: String = segments.iter().map(String::as_str).collect();
4664                items.push(ImmediateItem {
4665                    access_path: name,
4666                    offset: *offset,
4667                    ty: (&self.module.types[ty].inner).try_into().unwrap(),
4668                    size_bytes: layout.size,
4669                });
4670                *offset += layout.size;
4671            }
4672            // Arrays are recursed into.
4673            TypeInner::Array { base, size, .. } => {
4674                let crate::ArraySize::Constant(count) = size else {
4675                    unreachable!("Cannot have dynamic arrays in immediates");
4676                };
4677
4678                for i in 0..count.get() {
4679                    // Add the array accessor and recurse.
4680                    segments.push(format!("[{i}]"));
4681                    self.collect_immediates_items(base, segments, layouter, offset, items);
4682                    segments.pop();
4683                }
4684
4685                // Ensure the stride is kept by rounding up to the alignment.
4686                *offset = layout.alignment.round_up(*offset)
4687            }
4688            TypeInner::Struct { ref members, .. } => {
4689                for (index, member) in members.iter().enumerate() {
4690                    // Add struct accessor and recurse.
4691                    segments.push(format!(
4692                        ".{}",
4693                        self.names[&NameKey::StructMember(ty, index as u32)]
4694                    ));
4695                    self.collect_immediates_items(member.ty, segments, layouter, offset, items);
4696                    segments.pop();
4697                }
4698
4699                // Ensure ending padding is kept by rounding up to the alignment.
4700                *offset = layout.alignment.round_up(*offset)
4701            }
4702            _ => unreachable!(),
4703        }
4704    }
4705}