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                            (
1100                                Version::Embedded {
1101                                    version: 300,
1102                                    is_webgl: true,
1103                                },
1104                                ShaderStage::Fragment,
1105                            ) => {
1106                                // `invariant gl_FragCoord` is not allowed in WebGL2 and possibly
1107                                // OpenGL ES in general (waiting on confirmation).
1108                                //
1109                                // See https://github.com/KhronosGroup/WebGL/issues/3518
1110                            }
1111                            _ => {
1112                                writeln!(
1113                                    self.out,
1114                                    "invariant {};",
1115                                    glsl_built_in(
1116                                        built_in,
1117                                        VaryingOptions::from_writer_options(self.options, output)
1118                                    )
1119                                )?;
1120                            }
1121                        }
1122                    }
1123                    crate::BuiltIn::ClipDistances => {
1124                        // Re-declare `gl_ClipDistance` with number of clip planes.
1125                        let TypeInner::Array { size, .. } = self.module.types[ty].inner else {
1126                            unreachable!();
1127                        };
1128                        let proc::IndexableLength::Known(size) =
1129                            size.resolve(self.module.to_ctx())?
1130                        else {
1131                            unreachable!();
1132                        };
1133                        self.clip_distance_count = size;
1134                        writeln!(self.out, "out float gl_ClipDistance[{size}];")?;
1135                    }
1136                    _ => {}
1137                }
1138                return Ok(());
1139            }
1140        };
1141
1142        // Write the interpolation modifier if needed
1143        //
1144        // We ignore all interpolation and auxiliary modifiers that aren't used in fragment
1145        // shaders' input globals or vertex shaders' output globals.
1146        let emit_interpolation_and_auxiliary = match self.entry_point.stage {
1147            ShaderStage::Vertex => output,
1148            ShaderStage::Fragment => !output,
1149            ShaderStage::Compute => false,
1150            ShaderStage::Task
1151            | ShaderStage::Mesh
1152            | ShaderStage::RayGeneration
1153            | ShaderStage::AnyHit
1154            | ShaderStage::ClosestHit
1155            | ShaderStage::Miss => unreachable!(),
1156        };
1157
1158        // Write the I/O locations, if allowed
1159        let io_location = if self.options.version.supports_explicit_locations()
1160            || !emit_interpolation_and_auxiliary
1161        {
1162            if self.options.version.supports_io_locations() {
1163                if let Some(blend_src) = blend_src {
1164                    write!(
1165                        self.out,
1166                        "layout(location = {location}, index = {blend_src}) "
1167                    )?;
1168                } else {
1169                    write!(self.out, "layout(location = {location}) ")?;
1170                }
1171                None
1172            } else {
1173                Some(VaryingLocation {
1174                    location,
1175                    index: blend_src.unwrap_or(0),
1176                })
1177            }
1178        } else {
1179            None
1180        };
1181
1182        // Write the interpolation qualifier.
1183        if let Some(interp) = interpolation {
1184            if emit_interpolation_and_auxiliary {
1185                write!(self.out, "{} ", glsl_interpolation(interp))?;
1186            }
1187        }
1188
1189        // Write the sampling auxiliary qualifier.
1190        //
1191        // Before GLSL 4.2, the `centroid` and `sample` qualifiers were required to appear
1192        // immediately before the `in` / `out` qualifier, so we'll just follow that rule
1193        // here, regardless of the version.
1194        if let Some(sampling) = sampling {
1195            if emit_interpolation_and_auxiliary {
1196                if let Some(qualifier) = glsl_sampling(sampling)? {
1197                    write!(self.out, "{qualifier} ")?;
1198                }
1199            }
1200        }
1201
1202        // Write the input/output qualifier.
1203        write!(self.out, "{} ", if output { "out" } else { "in" })?;
1204
1205        // Write the type
1206        // `write_type` adds no leading or trailing spaces
1207        self.write_type(ty)?;
1208
1209        // Finally write the global name and end the global with a `;` and a newline
1210        // Leading space is important
1211        let vname = VaryingName {
1212            binding: &crate::Binding::Location {
1213                location,
1214                interpolation: None,
1215                sampling: None,
1216                blend_src,
1217                per_primitive: false,
1218            },
1219            stage: self.entry_point.stage,
1220            options: VaryingOptions::from_writer_options(self.options, output),
1221        };
1222        writeln!(self.out, " {vname};")?;
1223
1224        if let Some(location) = io_location {
1225            self.varying.insert(vname.to_string(), location);
1226        }
1227
1228        Ok(())
1229    }
1230
1231    /// Helper method used to write functions (both entry points and regular functions)
1232    ///
1233    /// # Notes
1234    /// Adds a newline
1235    fn write_function(
1236        &mut self,
1237        ty: back::FunctionType,
1238        func: &crate::Function,
1239        info: &valid::FunctionInfo,
1240    ) -> BackendResult {
1241        // Create a function context for the function being written
1242        let ctx = back::FunctionCtx {
1243            ty,
1244            info,
1245            expressions: &func.expressions,
1246            named_expressions: &func.named_expressions,
1247        };
1248
1249        self.named_expressions.clear();
1250        self.update_expressions_to_bake(func, info);
1251
1252        // Write the function header
1253        //
1254        // glsl headers are the same as in c:
1255        // `ret_type name(args)`
1256        // `ret_type` is the return type
1257        // `name` is the function name
1258        // `args` is a comma separated list of `type name`
1259        //  | - `type` is the argument type
1260        //  | - `name` is the argument name
1261
1262        // Start by writing the return type if any otherwise write void
1263        // This is the only place where `void` is a valid type
1264        // (though it's more a keyword than a type)
1265        if let back::FunctionType::EntryPoint(_) = ctx.ty {
1266            write!(self.out, "void")?;
1267        } else if let Some(ref result) = func.result {
1268            self.write_type(result.ty)?;
1269            if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner {
1270                self.write_array_size(base, size)?
1271            }
1272        } else {
1273            write!(self.out, "void")?;
1274        }
1275
1276        // Write the function name and open parentheses for the argument list
1277        let function_name = match ctx.ty {
1278            back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)],
1279            back::FunctionType::EntryPoint(_) => "main",
1280        };
1281        write!(self.out, " {function_name}(")?;
1282
1283        // Write the comma separated argument list
1284        //
1285        // We need access to `Self` here so we use the reference passed to the closure as an
1286        // argument instead of capturing as that would cause a borrow checker error
1287        let arguments = match ctx.ty {
1288            back::FunctionType::EntryPoint(_) => &[][..],
1289            back::FunctionType::Function(_) => &func.arguments,
1290        };
1291        let arguments: Vec<_> = arguments
1292            .iter()
1293            .enumerate()
1294            .filter(|&(_, arg)| match self.module.types[arg.ty].inner {
1295                TypeInner::Sampler { .. } => false,
1296                _ => true,
1297            })
1298            .collect();
1299        self.write_slice(&arguments, |this, _, &(i, arg)| {
1300            // Write the argument type
1301            match this.module.types[arg.ty].inner {
1302                // We treat images separately because they might require
1303                // writing the storage format
1304                TypeInner::Image {
1305                    dim,
1306                    arrayed,
1307                    class,
1308                } => {
1309                    // Write the storage format if needed
1310                    if let TypeInner::Image {
1311                        class: crate::ImageClass::Storage { format, .. },
1312                        ..
1313                    } = this.module.types[arg.ty].inner
1314                    {
1315                        write!(this.out, "layout({}) ", glsl_storage_format(format)?)?;
1316                    }
1317
1318                    // write the type
1319                    //
1320                    // This is way we need the leading space because `write_image_type` doesn't add
1321                    // any spaces at the beginning or end
1322                    this.write_image_type(dim, arrayed, class)?;
1323                }
1324                TypeInner::Pointer { base, .. } => {
1325                    // write parameter qualifiers
1326                    write!(this.out, "inout ")?;
1327                    this.write_type(base)?;
1328                }
1329                // All other types are written by `write_type`
1330                _ => {
1331                    this.write_type(arg.ty)?;
1332                }
1333            }
1334
1335            // Write the argument name
1336            // The leading space is important
1337            write!(this.out, " {}", this.names[&ctx.argument_key(i as u32)])?;
1338
1339            // Write array size
1340            match this.module.types[arg.ty].inner {
1341                TypeInner::Array { base, size, .. } => {
1342                    this.write_array_size(base, size)?;
1343                }
1344                TypeInner::Pointer { base, .. } => {
1345                    if let TypeInner::Array { base, size, .. } = this.module.types[base].inner {
1346                        this.write_array_size(base, size)?;
1347                    }
1348                }
1349                _ => {}
1350            }
1351
1352            Ok(())
1353        })?;
1354
1355        // Close the parentheses and open braces to start the function body
1356        writeln!(self.out, ") {{")?;
1357
1358        if self.options.zero_initialize_workgroup_memory
1359            && ctx.ty.is_compute_like_entry_point(self.module)
1360        {
1361            self.write_workgroup_variables_initialization(&ctx)?;
1362        }
1363
1364        // Compose the function arguments from globals, in case of an entry point.
1365        if let back::FunctionType::EntryPoint(ep_index) = ctx.ty {
1366            let stage = self.module.entry_points[ep_index as usize].stage;
1367            for (index, arg) in func.arguments.iter().enumerate() {
1368                write!(self.out, "{}", back::INDENT)?;
1369                self.write_type(arg.ty)?;
1370                let name = &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)];
1371                write!(self.out, " {name}")?;
1372                write!(self.out, " = ")?;
1373                match self.module.types[arg.ty].inner {
1374                    TypeInner::Struct { ref members, .. } => {
1375                        self.write_type(arg.ty)?;
1376                        write!(self.out, "(")?;
1377                        for (index, member) in members.iter().enumerate() {
1378                            let varying_name = VaryingName {
1379                                binding: member.binding.as_ref().unwrap(),
1380                                stage,
1381                                options: VaryingOptions::from_writer_options(self.options, false),
1382                            };
1383                            if index != 0 {
1384                                write!(self.out, ", ")?;
1385                            }
1386                            write!(self.out, "{varying_name}")?;
1387                        }
1388                        writeln!(self.out, ");")?;
1389                    }
1390                    _ => {
1391                        let varying_name = VaryingName {
1392                            binding: arg.binding.as_ref().unwrap(),
1393                            stage,
1394                            options: VaryingOptions::from_writer_options(self.options, false),
1395                        };
1396                        writeln!(self.out, "{varying_name};")?;
1397                    }
1398                }
1399            }
1400        }
1401
1402        // Write all function locals
1403        // Locals are `type name (= init)?;` where the init part (including the =) are optional
1404        //
1405        // Always adds a newline
1406        for (handle, local) in func.local_variables.iter() {
1407            // Write indentation (only for readability) and the type
1408            // `write_type` adds no trailing space
1409            write!(self.out, "{}", back::INDENT)?;
1410            self.write_type(local.ty)?;
1411
1412            // Write the local name
1413            // The leading space is important
1414            write!(self.out, " {}", self.names[&ctx.name_key(handle)])?;
1415            // Write size for array type
1416            if let TypeInner::Array { base, size, .. } = self.module.types[local.ty].inner {
1417                self.write_array_size(base, size)?;
1418            }
1419            // Write the local initializer if needed
1420            if let Some(init) = local.init {
1421                // Put the equal signal only if there's a initializer
1422                // The leading and trailing spaces aren't needed but help with readability
1423                write!(self.out, " = ")?;
1424
1425                // Write the constant
1426                // `write_constant` adds no trailing or leading space/newline
1427                self.write_expr(init, &ctx)?;
1428            } else if is_value_init_supported(self.module, local.ty) {
1429                write!(self.out, " = ")?;
1430                self.write_zero_init_value(local.ty)?;
1431            }
1432
1433            // Finish the local with `;` and add a newline (only for readability)
1434            writeln!(self.out, ";")?
1435        }
1436
1437        // Write the function body (statement list)
1438        for sta in func.body.iter() {
1439            // Write a statement, the indentation should always be 1 when writing the function body
1440            // `write_stmt` adds a newline
1441            self.write_stmt(sta, &ctx, back::Level(1))?;
1442        }
1443
1444        // Close braces and add a newline
1445        writeln!(self.out, "}}")?;
1446
1447        Ok(())
1448    }
1449
1450    fn write_workgroup_variables_initialization(
1451        &mut self,
1452        ctx: &back::FunctionCtx,
1453    ) -> BackendResult {
1454        let mut vars = self
1455            .module
1456            .global_variables
1457            .iter()
1458            .filter(|&(handle, var)| {
1459                !ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
1460            })
1461            .peekable();
1462
1463        if vars.peek().is_some() {
1464            let level = back::Level(1);
1465
1466            writeln!(self.out, "{level}if (gl_LocalInvocationID == uvec3(0u)) {{")?;
1467
1468            for (handle, var) in vars {
1469                let name = &self.names[&NameKey::GlobalVariable(handle)];
1470                write!(self.out, "{}{} = ", level.next(), name)?;
1471                self.write_zero_init_value(var.ty)?;
1472                writeln!(self.out, ";")?;
1473            }
1474
1475            writeln!(self.out, "{level}}}")?;
1476            self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
1477        }
1478
1479        Ok(())
1480    }
1481
1482    /// Write a list of comma separated `T` values using a writer function `F`.
1483    ///
1484    /// The writer function `F` receives a mutable reference to `self` that if needed won't cause
1485    /// borrow checker issues (using for example a closure with `self` will cause issues), the
1486    /// second argument is the 0 based index of the element on the list, and the last element is
1487    /// a reference to the element `T` being written
1488    ///
1489    /// # Notes
1490    /// - Adds no newlines or leading/trailing whitespace
1491    /// - The last element won't have a trailing `,`
1492    fn write_slice<T, F: FnMut(&mut Self, u32, &T) -> BackendResult>(
1493        &mut self,
1494        data: &[T],
1495        mut f: F,
1496    ) -> BackendResult {
1497        // Loop through `data` invoking `f` for each element
1498        for (index, item) in data.iter().enumerate() {
1499            if index != 0 {
1500                write!(self.out, ", ")?;
1501            }
1502            f(self, index as u32, item)?;
1503        }
1504
1505        Ok(())
1506    }
1507
1508    /// Helper method used to write global constants
1509    fn write_global_constant(&mut self, handle: Handle<crate::Constant>) -> BackendResult {
1510        write!(self.out, "const ")?;
1511        let constant = &self.module.constants[handle];
1512        self.write_type(constant.ty)?;
1513        let name = &self.names[&NameKey::Constant(handle)];
1514        write!(self.out, " {name}")?;
1515        if let TypeInner::Array { base, size, .. } = self.module.types[constant.ty].inner {
1516            self.write_array_size(base, size)?;
1517        }
1518        write!(self.out, " = ")?;
1519        self.write_const_expr(constant.init, &self.module.global_expressions)?;
1520        writeln!(self.out, ";")?;
1521        Ok(())
1522    }
1523
1524    /// Helper method used to output a dot product as an arithmetic expression
1525    ///
1526    fn write_dot_product(
1527        &mut self,
1528        arg: Handle<crate::Expression>,
1529        arg1: Handle<crate::Expression>,
1530        size: usize,
1531        ctx: &back::FunctionCtx,
1532    ) -> BackendResult {
1533        // Write parentheses around the dot product expression to prevent operators
1534        // with different precedences from applying earlier.
1535        write!(self.out, "(")?;
1536
1537        // Cycle through all the components of the vector
1538        for index in 0..size {
1539            let component = back::COMPONENTS[index];
1540            // Write the addition to the previous product
1541            // This will print an extra '+' at the beginning but that is fine in glsl
1542            write!(self.out, " + ")?;
1543            // Write the first vector expression, this expression is marked to be
1544            // cached so unless it can't be cached (for example, it's a Constant)
1545            // it shouldn't produce large expressions.
1546            self.write_expr(arg, ctx)?;
1547            // Access the current component on the first vector
1548            write!(self.out, ".{component} * ")?;
1549            // Write the second vector expression, this expression is marked to be
1550            // cached so unless it can't be cached (for example, it's a Constant)
1551            // it shouldn't produce large expressions.
1552            self.write_expr(arg1, ctx)?;
1553            // Access the current component on the second vector
1554            write!(self.out, ".{component}")?;
1555        }
1556
1557        write!(self.out, ")")?;
1558        Ok(())
1559    }
1560
1561    /// Helper method used to write structs
1562    ///
1563    /// # Notes
1564    /// Ends in a newline
1565    fn write_struct_body(
1566        &mut self,
1567        handle: Handle<crate::Type>,
1568        members: &[crate::StructMember],
1569    ) -> BackendResult {
1570        // glsl structs are written as in C
1571        // `struct name() { members };`
1572        //  | `struct` is a keyword
1573        //  | `name` is the struct name
1574        //  | `members` is a semicolon separated list of `type name`
1575        //      | `type` is the member type
1576        //      | `name` is the member name
1577        writeln!(self.out, "{{")?;
1578
1579        for (idx, member) in members.iter().enumerate() {
1580            // The indentation is only for readability
1581            write!(self.out, "{}", back::INDENT)?;
1582
1583            match self.module.types[member.ty].inner {
1584                TypeInner::Array {
1585                    base,
1586                    size,
1587                    stride: _,
1588                } => {
1589                    self.write_type(base)?;
1590                    write!(
1591                        self.out,
1592                        " {}",
1593                        self.names[&NameKey::StructMember(handle, idx as u32)]
1594                    )?;
1595                    // Write [size]
1596                    self.write_array_size(base, size)?;
1597                    // Newline is important
1598                    writeln!(self.out, ";")?;
1599                }
1600                _ => {
1601                    // Write the member type
1602                    // Adds no trailing space
1603                    self.write_type(member.ty)?;
1604
1605                    // Write the member name and put a semicolon
1606                    // The leading space is important
1607                    // All members must have a semicolon even the last one
1608                    writeln!(
1609                        self.out,
1610                        " {};",
1611                        self.names[&NameKey::StructMember(handle, idx as u32)]
1612                    )?;
1613                }
1614            }
1615        }
1616
1617        write!(self.out, "}}")?;
1618        Ok(())
1619    }
1620
1621    /// Helper method used to write statements
1622    ///
1623    /// # Notes
1624    /// Always adds a newline
1625    fn write_stmt(
1626        &mut self,
1627        sta: &crate::Statement,
1628        ctx: &back::FunctionCtx,
1629        level: back::Level,
1630    ) -> BackendResult {
1631        use crate::Statement;
1632
1633        match *sta {
1634            // This is where we can generate intermediate constants for some expression types.
1635            Statement::Emit(ref range) => {
1636                for handle in range.clone() {
1637                    let ptr_class = ctx.resolve_type(handle, &self.module.types).pointer_space();
1638                    let expr_name = if ptr_class.is_some() {
1639                        // GLSL can't save a pointer-valued expression in a variable,
1640                        // but we shouldn't ever need to: they should never be named expressions,
1641                        // and none of the expression types flagged by bake_ref_count can be pointer-valued.
1642                        None
1643                    } else if let Some(name) = ctx.named_expressions.get(&handle) {
1644                        // Front end provides names for all variables at the start of writing.
1645                        // But we write them to step by step. We need to recache them
1646                        // Otherwise, we could accidentally write variable name instead of full expression.
1647                        // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords.
1648                        Some(self.namer.call(name))
1649                    } else if self.need_bake_expressions.contains(&handle) {
1650                        Some(Baked(handle).to_string())
1651                    } else {
1652                        None
1653                    };
1654
1655                    // If we are going to write an `ImageLoad` next and the target image
1656                    // is sampled and we are using the `Restrict` policy for bounds
1657                    // checking images we need to write a local holding the clamped lod.
1658                    if let crate::Expression::ImageLoad {
1659                        image,
1660                        level: Some(level_expr),
1661                        ..
1662                    } = ctx.expressions[handle]
1663                    {
1664                        if let TypeInner::Image {
1665                            class: crate::ImageClass::Sampled { .. },
1666                            ..
1667                        } = *ctx.resolve_type(image, &self.module.types)
1668                        {
1669                            if let proc::BoundsCheckPolicy::Restrict = self.policies.image_load {
1670                                write!(self.out, "{level}")?;
1671                                self.write_clamped_lod(ctx, handle, image, level_expr)?
1672                            }
1673                        }
1674                    }
1675
1676                    if let Some(name) = expr_name {
1677                        write!(self.out, "{level}")?;
1678                        self.write_named_expr(handle, name, handle, ctx)?;
1679                    }
1680                }
1681            }
1682            // Blocks are simple we just need to write the block statements between braces
1683            // We could also just print the statements but this is more readable and maps more
1684            // closely to the IR
1685            Statement::Block(ref block) => {
1686                write!(self.out, "{level}")?;
1687                writeln!(self.out, "{{")?;
1688                for sta in block.iter() {
1689                    // Increase the indentation to help with readability
1690                    self.write_stmt(sta, ctx, level.next())?
1691                }
1692                writeln!(self.out, "{level}}}")?
1693            }
1694            // Ifs are written as in C:
1695            // ```
1696            // if(condition) {
1697            //  accept
1698            // } else {
1699            //  reject
1700            // }
1701            // ```
1702            Statement::If {
1703                condition,
1704                ref accept,
1705                ref reject,
1706            } => {
1707                write!(self.out, "{level}")?;
1708                write!(self.out, "if (")?;
1709                self.write_expr(condition, ctx)?;
1710                writeln!(self.out, ") {{")?;
1711
1712                for sta in accept {
1713                    // Increase indentation to help with readability
1714                    self.write_stmt(sta, ctx, level.next())?;
1715                }
1716
1717                // If there are no statements in the reject block we skip writing it
1718                // This is only for readability
1719                if !reject.is_empty() {
1720                    writeln!(self.out, "{level}}} else {{")?;
1721
1722                    for sta in reject {
1723                        // Increase indentation to help with readability
1724                        self.write_stmt(sta, ctx, level.next())?;
1725                    }
1726                }
1727
1728                writeln!(self.out, "{level}}}")?
1729            }
1730            // Switch are written as in C:
1731            // ```
1732            // switch (selector) {
1733            //      // Fallthrough
1734            //      case label:
1735            //          block
1736            //      // Non fallthrough
1737            //      case label:
1738            //          block
1739            //          break;
1740            //      default:
1741            //          block
1742            //  }
1743            //  ```
1744            //  Where the `default` case happens isn't important but we put it last
1745            //  so that we don't need to print a `break` for it
1746            Statement::Switch {
1747                selector,
1748                ref cases,
1749            } => {
1750                let l2 = level.next();
1751                // Some GLSL consumers may not handle switches with a single
1752                // body correctly: See wgpu#4514. Write such switch statements
1753                // as a `do {} while(false);` loop instead.
1754                //
1755                // Since doing so may inadvertently capture `continue`
1756                // statements in the switch body, we must apply continue
1757                // forwarding. See the `naga::back::continue_forward` module
1758                // docs for details.
1759                let one_body = cases
1760                    .iter()
1761                    .rev()
1762                    .skip(1)
1763                    .all(|case| case.fall_through && case.body.is_empty());
1764                if one_body {
1765                    // Unlike HLSL, in GLSL `continue_ctx` only needs to know
1766                    // about [`Switch`] statements that are being rendered as
1767                    // `do-while` loops.
1768                    if let Some(variable) = self.continue_ctx.enter_switch(&mut self.namer) {
1769                        writeln!(self.out, "{level}bool {variable} = false;",)?;
1770                    };
1771                    writeln!(self.out, "{level}do {{")?;
1772                    // Note: Expressions have no side-effects so we don't need to emit selector expression.
1773
1774                    // Body
1775                    if let Some(case) = cases.last() {
1776                        for sta in case.body.iter() {
1777                            self.write_stmt(sta, ctx, l2)?;
1778                        }
1779                    }
1780                    // End do-while
1781                    writeln!(self.out, "{level}}} while(false);")?;
1782
1783                    // Handle any forwarded continue statements.
1784                    use back::continue_forward::ExitControlFlow;
1785                    let op = match self.continue_ctx.exit_switch() {
1786                        ExitControlFlow::None => None,
1787                        ExitControlFlow::Continue { variable } => Some(("continue", variable)),
1788                        ExitControlFlow::Break { variable } => Some(("break", variable)),
1789                    };
1790                    if let Some((control_flow, variable)) = op {
1791                        writeln!(self.out, "{level}if ({variable}) {{")?;
1792                        writeln!(self.out, "{l2}{control_flow};")?;
1793                        writeln!(self.out, "{level}}}")?;
1794                    }
1795                } else {
1796                    // Start the switch
1797                    write!(self.out, "{level}")?;
1798                    write!(self.out, "switch(")?;
1799                    self.write_expr(selector, ctx)?;
1800                    writeln!(self.out, ") {{")?;
1801
1802                    // Write all cases
1803                    for case in cases {
1804                        match case.value {
1805                            crate::SwitchValue::I32(value) => {
1806                                write!(self.out, "{l2}case {value}:")?
1807                            }
1808                            crate::SwitchValue::U32(value) => {
1809                                write!(self.out, "{l2}case {value}u:")?
1810                            }
1811                            crate::SwitchValue::Default => write!(self.out, "{l2}default:")?,
1812                        }
1813
1814                        let write_block_braces = !(case.fall_through && case.body.is_empty());
1815                        if write_block_braces {
1816                            writeln!(self.out, " {{")?;
1817                        } else {
1818                            writeln!(self.out)?;
1819                        }
1820
1821                        for sta in case.body.iter() {
1822                            self.write_stmt(sta, ctx, l2.next())?;
1823                        }
1824
1825                        if !case.fall_through && case.body.last().is_none_or(|s| !s.is_terminator())
1826                        {
1827                            writeln!(self.out, "{}break;", l2.next())?;
1828                        }
1829
1830                        if write_block_braces {
1831                            writeln!(self.out, "{l2}}}")?;
1832                        }
1833                    }
1834
1835                    writeln!(self.out, "{level}}}")?
1836                }
1837            }
1838            // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a
1839            // while true loop and appending the continuing block to the body resulting on:
1840            // ```
1841            // bool loop_init = true;
1842            // while(true) {
1843            //  if (!loop_init) { <continuing> }
1844            //  loop_init = false;
1845            //  <body>
1846            // }
1847            // ```
1848            Statement::Loop {
1849                ref body,
1850                ref continuing,
1851                break_if,
1852            } => {
1853                self.continue_ctx.enter_loop();
1854                if !continuing.is_empty() || break_if.is_some() {
1855                    let gate_name = self.namer.call("loop_init");
1856                    writeln!(self.out, "{level}bool {gate_name} = true;")?;
1857                    writeln!(self.out, "{level}while(true) {{")?;
1858                    let l2 = level.next();
1859                    let l3 = l2.next();
1860                    writeln!(self.out, "{l2}if (!{gate_name}) {{")?;
1861                    for sta in continuing {
1862                        self.write_stmt(sta, ctx, l3)?;
1863                    }
1864                    if let Some(condition) = break_if {
1865                        write!(self.out, "{l3}if (")?;
1866                        self.write_expr(condition, ctx)?;
1867                        writeln!(self.out, ") {{")?;
1868                        writeln!(self.out, "{}break;", l3.next())?;
1869                        writeln!(self.out, "{l3}}}")?;
1870                    }
1871                    writeln!(self.out, "{l2}}}")?;
1872                    writeln!(self.out, "{}{} = false;", level.next(), gate_name)?;
1873                } else {
1874                    writeln!(self.out, "{level}while(true) {{")?;
1875                }
1876                for sta in body {
1877                    self.write_stmt(sta, ctx, level.next())?;
1878                }
1879                writeln!(self.out, "{level}}}")?;
1880                self.continue_ctx.exit_loop();
1881            }
1882            // Break, continue and return as written as in C
1883            // `break;`
1884            Statement::Break => {
1885                write!(self.out, "{level}")?;
1886                writeln!(self.out, "break;")?
1887            }
1888            // `continue;`
1889            Statement::Continue => {
1890                // Sometimes we must render a `Continue` statement as a `break`.
1891                // See the docs for the `back::continue_forward` module.
1892                if let Some(variable) = self.continue_ctx.continue_encountered() {
1893                    writeln!(self.out, "{level}{variable} = true;",)?;
1894                    writeln!(self.out, "{level}break;")?
1895                } else {
1896                    writeln!(self.out, "{level}continue;")?
1897                }
1898            }
1899            // `return expr;`, `expr` is optional
1900            Statement::Return { value } => {
1901                write!(self.out, "{level}")?;
1902                match ctx.ty {
1903                    back::FunctionType::Function(_) => {
1904                        write!(self.out, "return")?;
1905                        // Write the expression to be returned if needed
1906                        if let Some(expr) = value {
1907                            write!(self.out, " ")?;
1908                            self.write_expr(expr, ctx)?;
1909                        }
1910                        writeln!(self.out, ";")?;
1911                    }
1912                    back::FunctionType::EntryPoint(ep_index) => {
1913                        let mut has_point_size = false;
1914                        let ep = &self.module.entry_points[ep_index as usize];
1915                        if let Some(ref result) = ep.function.result {
1916                            let value = value.unwrap();
1917                            match self.module.types[result.ty].inner {
1918                                TypeInner::Struct { ref members, .. } => {
1919                                    let temp_struct_name = match ctx.expressions[value] {
1920                                        crate::Expression::Compose { .. } => {
1921                                            let return_struct = "_tmp_return";
1922                                            write!(
1923                                                self.out,
1924                                                "{ty} {return_struct} = ",
1925                                                ty = self.names[&NameKey::Type(result.ty)],
1926                                            )?;
1927                                            self.write_expr(value, ctx)?;
1928                                            writeln!(self.out, ";")?;
1929                                            write!(self.out, "{level}")?;
1930                                            Some(return_struct)
1931                                        }
1932                                        _ => None,
1933                                    };
1934
1935                                    for (index, member) in members.iter().enumerate() {
1936                                        if let Some(crate::Binding::BuiltIn(
1937                                            crate::BuiltIn::PointSize,
1938                                        )) = member.binding
1939                                        {
1940                                            has_point_size = true;
1941                                        }
1942
1943                                        let varying_name = VaryingName {
1944                                            binding: member.binding.as_ref().unwrap(),
1945                                            stage: ep.stage,
1946                                            options: VaryingOptions::from_writer_options(
1947                                                self.options,
1948                                                true,
1949                                            ),
1950                                        };
1951                                        write!(self.out, "{varying_name} = ")?;
1952
1953                                        if let Some(struct_name) = temp_struct_name {
1954                                            write!(self.out, "{struct_name}")?;
1955                                        } else {
1956                                            self.write_expr(value, ctx)?;
1957                                        }
1958
1959                                        // Write field name
1960                                        writeln!(
1961                                            self.out,
1962                                            ".{};",
1963                                            self.names
1964                                                [&NameKey::StructMember(result.ty, index as u32)]
1965                                        )?;
1966                                        write!(self.out, "{level}")?;
1967                                    }
1968                                }
1969                                _ => {
1970                                    let name = VaryingName {
1971                                        binding: result.binding.as_ref().unwrap(),
1972                                        stage: ep.stage,
1973                                        options: VaryingOptions::from_writer_options(
1974                                            self.options,
1975                                            true,
1976                                        ),
1977                                    };
1978                                    write!(self.out, "{name} = ")?;
1979                                    self.write_expr(value, ctx)?;
1980                                    writeln!(self.out, ";")?;
1981                                    write!(self.out, "{level}")?;
1982                                }
1983                            }
1984                        }
1985
1986                        let is_vertex_stage = self.module.entry_points[ep_index as usize].stage
1987                            == ShaderStage::Vertex;
1988                        if is_vertex_stage
1989                            && self
1990                                .options
1991                                .writer_flags
1992                                .contains(WriterFlags::ADJUST_COORDINATE_SPACE)
1993                        {
1994                            writeln!(
1995                                self.out,
1996                                "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);",
1997                            )?;
1998                            write!(self.out, "{level}")?;
1999                        }
2000
2001                        if is_vertex_stage
2002                            && self
2003                                .options
2004                                .writer_flags
2005                                .contains(WriterFlags::FORCE_POINT_SIZE)
2006                            && !has_point_size
2007                        {
2008                            writeln!(self.out, "gl_PointSize = 1.0;")?;
2009                            write!(self.out, "{level}")?;
2010                        }
2011                        writeln!(self.out, "return;")?;
2012                    }
2013                }
2014            }
2015            // This is one of the places were glsl adds to the syntax of C in this case the discard
2016            // keyword which ceases all further processing in a fragment shader, it's called OpKill
2017            // in spir-v that's why it's called `Statement::Kill`
2018            Statement::Kill => writeln!(self.out, "{level}discard;")?,
2019            Statement::ControlBarrier(flags) => {
2020                self.write_control_barrier(flags, level)?;
2021            }
2022            Statement::MemoryBarrier(flags) => {
2023                self.write_memory_barrier(flags, level)?;
2024            }
2025            // Stores in glsl are just variable assignments written as `pointer = value;`
2026            Statement::Store { pointer, value } => {
2027                write!(self.out, "{level}")?;
2028                let is_atomic_pointer = ctx
2029                    .resolve_type(pointer, &self.module.types)
2030                    .is_atomic_pointer(&self.module.types);
2031                if is_atomic_pointer {
2032                    write!(self.out, "atomicExchange(")?;
2033                    self.write_expr(pointer, ctx)?;
2034                    write!(self.out, ", ")?;
2035                    self.write_expr(value, ctx)?;
2036                    writeln!(self.out, ");")?
2037                } else {
2038                    self.write_expr(pointer, ctx)?;
2039                    write!(self.out, " = ")?;
2040                    self.write_expr(value, ctx)?;
2041                    writeln!(self.out, ";")?
2042                }
2043            }
2044            Statement::WorkGroupUniformLoad { pointer, result } => {
2045                // GLSL doesn't have pointers, which means that this backend needs to ensure that
2046                // the actual "loading" is happening between the two barriers.
2047                // This is done in `Emit` by never emitting a variable name for pointer variables
2048                self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
2049
2050                let result_name = Baked(result).to_string();
2051                write!(self.out, "{level}")?;
2052                // Expressions cannot have side effects, so just writing the expression here is fine.
2053                self.write_named_expr(pointer, result_name, result, ctx)?;
2054
2055                self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
2056            }
2057            // Stores a value into an image.
2058            Statement::ImageStore {
2059                image,
2060                coordinate,
2061                array_index,
2062                value,
2063            } => {
2064                write!(self.out, "{level}")?;
2065                self.write_image_store(ctx, image, coordinate, array_index, value)?
2066            }
2067            // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list
2068            Statement::Call {
2069                function,
2070                ref arguments,
2071                result,
2072            } => {
2073                write!(self.out, "{level}")?;
2074                if let Some(expr) = result {
2075                    let name = Baked(expr).to_string();
2076                    let result = self.module.functions[function].result.as_ref().unwrap();
2077                    self.write_type(result.ty)?;
2078                    write!(self.out, " {name}")?;
2079                    if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner
2080                    {
2081                        self.write_array_size(base, size)?
2082                    }
2083                    write!(self.out, " = ")?;
2084                    self.named_expressions.insert(expr, name);
2085                }
2086                write!(self.out, "{}(", self.names[&NameKey::Function(function)])?;
2087                let arguments: Vec<_> = arguments
2088                    .iter()
2089                    .enumerate()
2090                    .filter_map(|(i, arg)| {
2091                        let arg_ty = self.module.functions[function].arguments[i].ty;
2092                        match self.module.types[arg_ty].inner {
2093                            TypeInner::Sampler { .. } => None,
2094                            _ => Some(*arg),
2095                        }
2096                    })
2097                    .collect();
2098                self.write_slice(&arguments, |this, _, arg| this.write_expr(*arg, ctx))?;
2099                writeln!(self.out, ");")?
2100            }
2101            Statement::Atomic {
2102                pointer,
2103                ref fun,
2104                value,
2105                result,
2106            } => {
2107                write!(self.out, "{level}")?;
2108
2109                match *fun {
2110                    crate::AtomicFunction::Exchange {
2111                        compare: Some(compare_expr),
2112                    } => {
2113                        let result_handle = result.expect("CompareExchange must have a result");
2114                        let res_name = Baked(result_handle).to_string();
2115                        self.write_type(ctx.info[result_handle].ty.handle().unwrap())?;
2116                        write!(self.out, " {res_name};")?;
2117                        write!(self.out, " {res_name}.old_value = atomicCompSwap(")?;
2118                        self.write_expr(pointer, ctx)?;
2119                        write!(self.out, ", ")?;
2120                        self.write_expr(compare_expr, ctx)?;
2121                        write!(self.out, ", ")?;
2122                        self.write_expr(value, ctx)?;
2123                        writeln!(self.out, ");")?;
2124
2125                        write!(
2126                            self.out,
2127                            "{level}{res_name}.exchanged = ({res_name}.old_value == "
2128                        )?;
2129                        self.write_expr(compare_expr, ctx)?;
2130                        writeln!(self.out, ");")?;
2131                        self.named_expressions.insert(result_handle, res_name);
2132                    }
2133                    _ => {
2134                        if let Some(result) = result {
2135                            let res_name = Baked(result).to_string();
2136                            self.write_type(ctx.info[result].ty.handle().unwrap())?;
2137                            write!(self.out, " {res_name} = ")?;
2138                            self.named_expressions.insert(result, res_name);
2139                        }
2140                        let fun_str = fun.to_glsl();
2141                        write!(self.out, "atomic{fun_str}(")?;
2142                        self.write_expr(pointer, ctx)?;
2143                        write!(self.out, ", ")?;
2144                        if let crate::AtomicFunction::Subtract = *fun {
2145                            // Emulate `atomicSub` with `atomicAdd` by negating the value.
2146                            //
2147                            // Use a space to avoid accidentally producing a prefix increment
2148                            // (`--`).
2149                            write!(self.out, "- ")?;
2150                        }
2151                        self.write_expr(value, ctx)?;
2152                        writeln!(self.out, ");")?;
2153                    }
2154                }
2155            }
2156            // Stores a value into an image.
2157            Statement::ImageAtomic {
2158                image,
2159                coordinate,
2160                array_index,
2161                fun,
2162                value,
2163            } => {
2164                write!(self.out, "{level}")?;
2165                self.write_image_atomic(ctx, image, coordinate, array_index, fun, value)?
2166            }
2167            Statement::RayQuery { .. } => unreachable!(),
2168            Statement::SubgroupBallot { result, predicate } => {
2169                write!(self.out, "{level}")?;
2170                let res_name = Baked(result).to_string();
2171                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2172                self.write_value_type(res_ty)?;
2173                write!(self.out, " {res_name} = ")?;
2174                self.named_expressions.insert(result, res_name);
2175
2176                write!(self.out, "subgroupBallot(")?;
2177                match predicate {
2178                    Some(predicate) => self.write_expr(predicate, ctx)?,
2179                    None => write!(self.out, "true")?,
2180                }
2181                writeln!(self.out, ");")?;
2182            }
2183            Statement::SubgroupCollectiveOperation {
2184                op,
2185                collective_op,
2186                argument,
2187                result,
2188            } => {
2189                write!(self.out, "{level}")?;
2190                let res_name = Baked(result).to_string();
2191                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2192                self.write_value_type(res_ty)?;
2193                write!(self.out, " {res_name} = ")?;
2194                self.named_expressions.insert(result, res_name);
2195
2196                match (collective_op, op) {
2197                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
2198                        write!(self.out, "subgroupAll(")?
2199                    }
2200                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
2201                        write!(self.out, "subgroupAny(")?
2202                    }
2203                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
2204                        write!(self.out, "subgroupAdd(")?
2205                    }
2206                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
2207                        write!(self.out, "subgroupMul(")?
2208                    }
2209                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
2210                        write!(self.out, "subgroupMax(")?
2211                    }
2212                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
2213                        write!(self.out, "subgroupMin(")?
2214                    }
2215                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
2216                        write!(self.out, "subgroupAnd(")?
2217                    }
2218                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
2219                        write!(self.out, "subgroupOr(")?
2220                    }
2221                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
2222                        write!(self.out, "subgroupXor(")?
2223                    }
2224                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Add) => {
2225                        write!(self.out, "subgroupExclusiveAdd(")?
2226                    }
2227                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Mul) => {
2228                        write!(self.out, "subgroupExclusiveMul(")?
2229                    }
2230                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Add) => {
2231                        write!(self.out, "subgroupInclusiveAdd(")?
2232                    }
2233                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Mul) => {
2234                        write!(self.out, "subgroupInclusiveMul(")?
2235                    }
2236                    _ => unimplemented!(),
2237                }
2238                self.write_expr(argument, ctx)?;
2239                writeln!(self.out, ");")?;
2240            }
2241            Statement::SubgroupGather {
2242                mode,
2243                argument,
2244                result,
2245            } => {
2246                write!(self.out, "{level}")?;
2247                let res_name = Baked(result).to_string();
2248                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2249                self.write_value_type(res_ty)?;
2250                write!(self.out, " {res_name} = ")?;
2251                self.named_expressions.insert(result, res_name);
2252
2253                match mode {
2254                    crate::GatherMode::BroadcastFirst => {
2255                        write!(self.out, "subgroupBroadcastFirst(")?;
2256                    }
2257                    crate::GatherMode::Broadcast(_) => {
2258                        write!(self.out, "subgroupBroadcast(")?;
2259                    }
2260                    crate::GatherMode::Shuffle(_) => {
2261                        write!(self.out, "subgroupShuffle(")?;
2262                    }
2263                    crate::GatherMode::ShuffleDown(_) => {
2264                        write!(self.out, "subgroupShuffleDown(")?;
2265                    }
2266                    crate::GatherMode::ShuffleUp(_) => {
2267                        write!(self.out, "subgroupShuffleUp(")?;
2268                    }
2269                    crate::GatherMode::ShuffleXor(_) => {
2270                        write!(self.out, "subgroupShuffleXor(")?;
2271                    }
2272                    crate::GatherMode::QuadBroadcast(_) => {
2273                        write!(self.out, "subgroupQuadBroadcast(")?;
2274                    }
2275                    crate::GatherMode::QuadSwap(direction) => match direction {
2276                        crate::Direction::X => {
2277                            write!(self.out, "subgroupQuadSwapHorizontal(")?;
2278                        }
2279                        crate::Direction::Y => {
2280                            write!(self.out, "subgroupQuadSwapVertical(")?;
2281                        }
2282                        crate::Direction::Diagonal => {
2283                            write!(self.out, "subgroupQuadSwapDiagonal(")?;
2284                        }
2285                    },
2286                }
2287                self.write_expr(argument, ctx)?;
2288                match mode {
2289                    crate::GatherMode::BroadcastFirst => {}
2290                    crate::GatherMode::Broadcast(index)
2291                    | crate::GatherMode::Shuffle(index)
2292                    | crate::GatherMode::ShuffleDown(index)
2293                    | crate::GatherMode::ShuffleUp(index)
2294                    | crate::GatherMode::ShuffleXor(index)
2295                    | crate::GatherMode::QuadBroadcast(index) => {
2296                        write!(self.out, ", ")?;
2297                        self.write_expr(index, ctx)?;
2298                    }
2299                    crate::GatherMode::QuadSwap(_) => {}
2300                }
2301                writeln!(self.out, ");")?;
2302            }
2303            Statement::SubgroupBallotFindBit {
2304                order,
2305                argument,
2306                result,
2307            } => {
2308                write!(self.out, "{level}")?;
2309                let res_name = Baked(result).to_string();
2310                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2311                self.write_value_type(res_ty)?;
2312                write!(self.out, " {res_name} = ")?;
2313                self.named_expressions.insert(result, res_name);
2314
2315                match order {
2316                    crate::BallotFindBitOrder::Lsb => {
2317                        write!(self.out, "subgroupBallotFindLSB(")?;
2318                    }
2319                    crate::BallotFindBitOrder::Msb => {
2320                        write!(self.out, "subgroupBallotFindMSB(")?;
2321                    }
2322                }
2323                self.write_expr(argument, ctx)?;
2324                writeln!(self.out, ");")?;
2325            }
2326            Statement::CooperativeStore { .. } => unimplemented!(),
2327            Statement::RayPipelineFunction(_) | Statement::HitObject { .. } => unimplemented!(),
2328            Statement::DebugPrintf { .. } => unimplemented!(),
2329        }
2330
2331        Ok(())
2332    }
2333
2334    /// Write a const expression.
2335    ///
2336    /// Write `expr`, a handle to an [`Expression`] in the current [`Module`]'s
2337    /// constant expression arena, as GLSL expression.
2338    ///
2339    /// # Notes
2340    /// Adds no newlines or leading/trailing whitespace
2341    ///
2342    /// [`Expression`]: crate::Expression
2343    /// [`Module`]: crate::Module
2344    fn write_const_expr(
2345        &mut self,
2346        expr: Handle<crate::Expression>,
2347        arena: &crate::Arena<crate::Expression>,
2348    ) -> BackendResult {
2349        self.write_possibly_const_expr(
2350            expr,
2351            arena,
2352            |expr| &self.info[expr],
2353            |writer, expr| writer.write_const_expr(expr, arena),
2354        )
2355    }
2356
2357    /// Write [`Expression`] variants that can occur in both runtime and const expressions.
2358    ///
2359    /// Write `expr`, a handle to an [`Expression`] in the arena `expressions`,
2360    /// as as GLSL expression. This must be one of the [`Expression`] variants
2361    /// that is allowed to occur in constant expressions.
2362    ///
2363    /// Use `write_expression` to write subexpressions.
2364    ///
2365    /// This is the common code for `write_expr`, which handles arbitrary
2366    /// runtime expressions, and `write_const_expr`, which only handles
2367    /// const-expressions. Each of those callers passes itself (essentially) as
2368    /// the `write_expression` callback, so that subexpressions are restricted
2369    /// to the appropriate variants.
2370    ///
2371    /// # Notes
2372    /// Adds no newlines or leading/trailing whitespace
2373    ///
2374    /// [`Expression`]: crate::Expression
2375    fn write_possibly_const_expr<'w, I, E>(
2376        &'w mut self,
2377        expr: Handle<crate::Expression>,
2378        expressions: &crate::Arena<crate::Expression>,
2379        info: I,
2380        write_expression: E,
2381    ) -> BackendResult
2382    where
2383        I: Fn(Handle<crate::Expression>) -> &'w proc::TypeResolution,
2384        E: Fn(&mut Self, Handle<crate::Expression>) -> BackendResult,
2385    {
2386        use crate::Expression;
2387
2388        match expressions[expr] {
2389            Expression::Literal(literal) => {
2390                match literal {
2391                    // Floats are written using `Debug` instead of `Display` because it always appends the
2392                    // decimal part even it's zero which is needed for a valid glsl float constant
2393                    crate::Literal::F64(value) => write!(self.out, "{value:?}LF")?,
2394                    crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
2395                    crate::Literal::F16(_) => {
2396                        return Err(Error::Custom("GLSL has no 16-bit float type".into()));
2397                    }
2398                    // Unsigned integers need a `u` at the end
2399                    //
2400                    // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we
2401                    // always write it as the extra branch wouldn't have any benefit in readability
2402                    crate::Literal::U16(value) => write!(self.out, "uint16_t({value})")?,
2403                    crate::Literal::I16(value) => write!(self.out, "int16_t({value})")?,
2404                    crate::Literal::U32(value) => write!(self.out, "{value}u")?,
2405                    crate::Literal::I32(value) => write!(self.out, "{value}")?,
2406                    crate::Literal::Bool(value) => write!(self.out, "{value}")?,
2407                    crate::Literal::I64(_) => {
2408                        return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
2409                    }
2410                    crate::Literal::U64(_) => {
2411                        return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
2412                    }
2413                    crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
2414                        return Err(Error::Custom(
2415                            "Abstract types should not appear in IR presented to backends".into(),
2416                        ));
2417                    }
2418                }
2419            }
2420            Expression::Constant(handle) => {
2421                let constant = &self.module.constants[handle];
2422                if constant.name.is_some() {
2423                    write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
2424                } else {
2425                    self.write_const_expr(constant.init, &self.module.global_expressions)?;
2426                }
2427            }
2428            Expression::ZeroValue(ty) => {
2429                self.write_zero_init_value(ty)?;
2430            }
2431            Expression::Compose { ty, ref components } => {
2432                self.write_type(ty)?;
2433
2434                if let TypeInner::Array { base, size, .. } = self.module.types[ty].inner {
2435                    self.write_array_size(base, size)?;
2436                }
2437
2438                write!(self.out, "(")?;
2439                for (index, component) in components.iter().enumerate() {
2440                    if index != 0 {
2441                        write!(self.out, ", ")?;
2442                    }
2443                    write_expression(self, *component)?;
2444                }
2445                write!(self.out, ")")?
2446            }
2447            // `Splat` needs to actually write down a vector, it's not always inferred in GLSL.
2448            Expression::Splat { size: _, value } => {
2449                let resolved = info(expr).inner_with(&self.module.types);
2450                self.write_value_type(resolved)?;
2451                write!(self.out, "(")?;
2452                write_expression(self, value)?;
2453                write!(self.out, ")")?
2454            }
2455            _ => {
2456                return Err(Error::Override);
2457            }
2458        }
2459
2460        Ok(())
2461    }
2462
2463    /// Helper method to write expressions
2464    ///
2465    /// # Notes
2466    /// Doesn't add any newlines or leading/trailing spaces
2467    #[allow(clippy::large_stack_frames)] // TODO(https://github.com/gfx-rs/wgpu/issues/9456)
2468    fn write_expr(
2469        &mut self,
2470        expr: Handle<crate::Expression>,
2471        ctx: &back::FunctionCtx,
2472    ) -> BackendResult {
2473        use crate::Expression;
2474
2475        if let Some(name) = self.named_expressions.get(&expr) {
2476            write!(self.out, "{name}")?;
2477            return Ok(());
2478        }
2479
2480        match ctx.expressions[expr] {
2481            Expression::Literal(_)
2482            | Expression::Constant(_)
2483            | Expression::ZeroValue(_)
2484            | Expression::Compose { .. }
2485            | Expression::Splat { .. } => {
2486                self.write_possibly_const_expr(
2487                    expr,
2488                    ctx.expressions,
2489                    |expr| &ctx.info[expr].ty,
2490                    |writer, expr| writer.write_expr(expr, ctx),
2491                )?;
2492            }
2493            Expression::Override(_) => return Err(Error::Override),
2494            // `Access` is applied to arrays, vectors and matrices and is written as indexing
2495            Expression::Access { base, index } => {
2496                self.write_expr(base, ctx)?;
2497                write!(self.out, "[")?;
2498                self.write_expr(index, ctx)?;
2499                write!(self.out, "]")?
2500            }
2501            // `AccessIndex` is the same as `Access` except that the index is a constant and it can
2502            // be applied to structs, in this case we need to find the name of the field at that
2503            // index and write `base.field_name`
2504            Expression::AccessIndex { base, index } => {
2505                self.write_expr(base, ctx)?;
2506
2507                let base_ty_res = &ctx.info[base].ty;
2508                let mut resolved = base_ty_res.inner_with(&self.module.types);
2509                let base_ty_handle = match *resolved {
2510                    TypeInner::Pointer { base, space: _ } => {
2511                        resolved = &self.module.types[base].inner;
2512                        Some(base)
2513                    }
2514                    _ => base_ty_res.handle(),
2515                };
2516
2517                match *resolved {
2518                    TypeInner::Vector { .. } => {
2519                        // Write vector access as a swizzle
2520                        write!(self.out, ".{}", back::COMPONENTS[index as usize])?
2521                    }
2522                    TypeInner::Matrix { .. }
2523                    | TypeInner::Array { .. }
2524                    | TypeInner::ValuePointer { .. } => write!(self.out, "[{index}]")?,
2525                    TypeInner::Struct { .. } => {
2526                        // This will never panic in case the type is a `Struct`, this is not true
2527                        // for other types so we can only check while inside this match arm
2528                        let ty = base_ty_handle.unwrap();
2529
2530                        write!(
2531                            self.out,
2532                            ".{}",
2533                            self.names[&NameKey::StructMember(ty, index)]
2534                        )?
2535                    }
2536                    ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))),
2537                }
2538            }
2539            // `Swizzle` adds a few letters behind the dot.
2540            Expression::Swizzle {
2541                size,
2542                vector,
2543                pattern,
2544            } => {
2545                self.write_expr(vector, ctx)?;
2546                write!(self.out, ".")?;
2547                for &sc in pattern[..size as usize].iter() {
2548                    self.out.write_char(back::COMPONENTS[sc as usize])?;
2549                }
2550            }
2551            // Function arguments are written as the argument name
2552            Expression::FunctionArgument(pos) => {
2553                write!(self.out, "{}", self.names[&ctx.argument_key(pos)])?
2554            }
2555            // Global variables need some special work for their name but
2556            // `get_global_name` does the work for us
2557            Expression::GlobalVariable(handle) => {
2558                let global = &self.module.global_variables[handle];
2559                self.write_global_name(handle, global)?
2560            }
2561            // A local is written as it's name
2562            Expression::LocalVariable(handle) => {
2563                write!(self.out, "{}", self.names[&ctx.name_key(handle)])?
2564            }
2565            // glsl has no pointers so there's no load operation, just write the pointer expression
2566            Expression::Load { pointer } => {
2567                let ty_inner = ctx.resolve_type(pointer, &self.module.types);
2568                if ty_inner.is_atomic_pointer(&self.module.types) {
2569                    let mut suffix = "";
2570                    if let TypeInner::Pointer { base, .. } = *ty_inner {
2571                        if let TypeInner::Atomic(scalar) = self.module.types[base].inner {
2572                            suffix = match (scalar.kind, scalar.width) {
2573                                (crate::ScalarKind::Uint, 8) => "ul",
2574                                (crate::ScalarKind::Sint, 8) => "l",
2575                                (crate::ScalarKind::Uint, _) => "u",
2576                                _ => "",
2577                            };
2578                        }
2579                    }
2580                    write!(self.out, "atomicOr(")?;
2581                    self.write_expr(pointer, ctx)?;
2582                    write!(self.out, ", 0{})", suffix)?
2583                } else {
2584                    self.write_expr(pointer, ctx)?
2585                }
2586            }
2587            // `ImageSample` is a bit complicated compared to the rest of the IR.
2588            //
2589            // First there are three variations depending whether the sample level is explicitly set,
2590            // if it's automatic or it it's bias:
2591            // `texture(image, coordinate)` - Automatic sample level
2592            // `texture(image, coordinate, bias)` - Bias sample level
2593            // `textureLod(image, coordinate, level)` - Zero or Exact sample level
2594            //
2595            // Furthermore if `depth_ref` is some we need to append it to the coordinate vector
2596            Expression::ImageSample {
2597                image,
2598                sampler: _, //TODO?
2599                gather,
2600                coordinate,
2601                array_index,
2602                offset,
2603                level,
2604                depth_ref,
2605                clamp_to_edge: _,
2606            } => {
2607                let (dim, class, arrayed) = match *ctx.resolve_type(image, &self.module.types) {
2608                    TypeInner::Image {
2609                        dim,
2610                        class,
2611                        arrayed,
2612                        ..
2613                    } => (dim, class, arrayed),
2614                    _ => unreachable!(),
2615                };
2616                let mut err = None;
2617                if dim == crate::ImageDimension::Cube {
2618                    if offset.is_some() {
2619                        err = Some("gsamplerCube[Array][Shadow] doesn't support texture sampling with offsets");
2620                    }
2621                    if arrayed
2622                        && matches!(class, crate::ImageClass::Depth { .. })
2623                        && matches!(level, crate::SampleLevel::Gradient { .. })
2624                    {
2625                        err = Some("samplerCubeArrayShadow don't support textureGrad");
2626                    }
2627                }
2628                if gather.is_some() && level != crate::SampleLevel::Zero {
2629                    err = Some("textureGather doesn't support LOD parameters");
2630                }
2631                if let Some(err) = err {
2632                    return Err(Error::Custom(String::from(err)));
2633                }
2634
2635                // `textureLod[Offset]` on `sampler2DArrayShadow` and `samplerCubeShadow` does not exist in GLSL,
2636                // unless `GL_EXT_texture_shadow_lod` is present.
2637                // But if the target LOD is zero, we can emulate that by using `textureGrad[Offset]` with a constant gradient of 0.
2638                let workaround_lod_with_grad = ((dim == crate::ImageDimension::Cube && !arrayed)
2639                    || (dim == crate::ImageDimension::D2 && arrayed))
2640                    && level == crate::SampleLevel::Zero
2641                    && matches!(class, crate::ImageClass::Depth { .. })
2642                    && !self.features.contains(Features::TEXTURE_SHADOW_LOD);
2643
2644                // Write the function to be used depending on the sample level
2645                let fun_name = match level {
2646                    crate::SampleLevel::Zero if gather.is_some() => "textureGather",
2647                    crate::SampleLevel::Zero if workaround_lod_with_grad => "textureGrad",
2648                    crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture",
2649                    crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod",
2650                    crate::SampleLevel::Gradient { .. } => "textureGrad",
2651                };
2652                let offset_name = match offset {
2653                    Some(_) => "Offset",
2654                    None => "",
2655                };
2656
2657                write!(self.out, "{fun_name}{offset_name}(")?;
2658
2659                // Write the image that will be used
2660                self.write_expr(image, ctx)?;
2661                // The space here isn't required but it helps with readability
2662                write!(self.out, ", ")?;
2663
2664                // TODO: handle clamp_to_edge
2665                // https://github.com/gfx-rs/wgpu/issues/7791
2666
2667                // We need to get the coordinates vector size to later build a vector that's `size + 1`
2668                // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression
2669                let mut coord_dim = match *ctx.resolve_type(coordinate, &self.module.types) {
2670                    TypeInner::Vector { size, .. } => size as u8,
2671                    TypeInner::Scalar { .. } => 1,
2672                    _ => unreachable!(),
2673                };
2674
2675                if array_index.is_some() {
2676                    coord_dim += 1;
2677                }
2678                let merge_depth_ref = depth_ref.is_some() && gather.is_none() && coord_dim < 4;
2679                if merge_depth_ref {
2680                    coord_dim += 1;
2681                }
2682
2683                let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es();
2684                let is_vec = tex_1d_hack || coord_dim != 1;
2685                // Compose a new texture coordinates vector
2686                if is_vec {
2687                    write!(self.out, "vec{}(", coord_dim + tex_1d_hack as u8)?;
2688                }
2689                self.write_expr(coordinate, ctx)?;
2690                if tex_1d_hack {
2691                    write!(self.out, ", 0.0")?;
2692                }
2693                if let Some(expr) = array_index {
2694                    write!(self.out, ", ")?;
2695                    self.write_expr(expr, ctx)?;
2696                }
2697                if merge_depth_ref {
2698                    write!(self.out, ", ")?;
2699                    self.write_expr(depth_ref.unwrap(), ctx)?;
2700                }
2701                if is_vec {
2702                    write!(self.out, ")")?;
2703                }
2704
2705                if let (Some(expr), false) = (depth_ref, merge_depth_ref) {
2706                    write!(self.out, ", ")?;
2707                    self.write_expr(expr, ctx)?;
2708                }
2709
2710                match level {
2711                    // Auto needs no more arguments
2712                    crate::SampleLevel::Auto => (),
2713                    // Zero needs level set to 0
2714                    crate::SampleLevel::Zero => {
2715                        if workaround_lod_with_grad {
2716                            let vec_dim = match dim {
2717                                crate::ImageDimension::Cube => 3,
2718                                _ => 2,
2719                            };
2720                            write!(self.out, ", vec{vec_dim}(0.0), vec{vec_dim}(0.0)")?;
2721                        } else if gather.is_none() {
2722                            write!(self.out, ", 0.0")?;
2723                        }
2724                    }
2725                    // Exact and bias require another argument
2726                    crate::SampleLevel::Exact(expr) => {
2727                        write!(self.out, ", ")?;
2728                        self.write_expr(expr, ctx)?;
2729                    }
2730                    crate::SampleLevel::Bias(_) => {
2731                        // This needs to be done after the offset writing
2732                    }
2733                    crate::SampleLevel::Gradient { x, y } => {
2734                        // If we are using sampler2D to replace sampler1D, we also
2735                        // need to make sure to use vec2 gradients
2736                        if tex_1d_hack {
2737                            write!(self.out, ", vec2(")?;
2738                            self.write_expr(x, ctx)?;
2739                            write!(self.out, ", 0.0)")?;
2740                            write!(self.out, ", vec2(")?;
2741                            self.write_expr(y, ctx)?;
2742                            write!(self.out, ", 0.0)")?;
2743                        } else {
2744                            write!(self.out, ", ")?;
2745                            self.write_expr(x, ctx)?;
2746                            write!(self.out, ", ")?;
2747                            self.write_expr(y, ctx)?;
2748                        }
2749                    }
2750                }
2751
2752                if let Some(constant) = offset {
2753                    write!(self.out, ", ")?;
2754                    if tex_1d_hack {
2755                        write!(self.out, "ivec2(")?;
2756                    }
2757                    self.write_const_expr(constant, ctx.expressions)?;
2758                    if tex_1d_hack {
2759                        write!(self.out, ", 0)")?;
2760                    }
2761                }
2762
2763                // Bias is always the last argument
2764                if let crate::SampleLevel::Bias(expr) = level {
2765                    write!(self.out, ", ")?;
2766                    self.write_expr(expr, ctx)?;
2767                }
2768
2769                if let (Some(component), None) = (gather, depth_ref) {
2770                    write!(self.out, ", {}", component as usize)?;
2771                }
2772
2773                // End the function
2774                write!(self.out, ")")?
2775            }
2776            Expression::ImageLoad {
2777                image,
2778                coordinate,
2779                array_index,
2780                sample,
2781                level,
2782            } => self.write_image_load(expr, ctx, image, coordinate, array_index, sample, level)?,
2783            // Query translates into one of the:
2784            // - textureSize/imageSize
2785            // - textureQueryLevels
2786            // - textureSamples/imageSamples
2787            Expression::ImageQuery { image, query } => {
2788                use crate::ImageClass;
2789
2790                // This will only panic if the module is invalid
2791                let (dim, class) = match *ctx.resolve_type(image, &self.module.types) {
2792                    TypeInner::Image {
2793                        dim,
2794                        arrayed: _,
2795                        class,
2796                    } => (dim, class),
2797                    _ => unreachable!(),
2798                };
2799                let components = match dim {
2800                    crate::ImageDimension::D1 => 1,
2801                    crate::ImageDimension::D2 => 2,
2802                    crate::ImageDimension::D3 => 3,
2803                    crate::ImageDimension::Cube => 2,
2804                };
2805
2806                if let crate::ImageQuery::Size { .. } = query {
2807                    match components {
2808                        1 => write!(self.out, "uint(")?,
2809                        _ => write!(self.out, "uvec{components}(")?,
2810                    }
2811                } else {
2812                    write!(self.out, "uint(")?;
2813                }
2814
2815                match query {
2816                    crate::ImageQuery::Size { level } => {
2817                        match class {
2818                            ImageClass::Sampled { multi, .. } | ImageClass::Depth { multi } => {
2819                                write!(self.out, "textureSize(")?;
2820                                self.write_expr(image, ctx)?;
2821                                if let Some(expr) = level {
2822                                    write!(self.out, ", ")?;
2823                                    self.write_expr_as_int(expr, ctx)?;
2824                                } else if !multi {
2825                                    // All textureSize calls requires an lod argument
2826                                    // except for multisampled samplers
2827                                    write!(self.out, ", 0")?;
2828                                }
2829                            }
2830                            ImageClass::Storage { .. } => {
2831                                write!(self.out, "imageSize(")?;
2832                                self.write_expr(image, ctx)?;
2833                            }
2834                            ImageClass::External => unimplemented!(),
2835                        }
2836                        write!(self.out, ")")?;
2837                        if components != 1 || self.options.version.is_es() {
2838                            write!(self.out, ".{}", &"xyz"[..components])?;
2839                        }
2840                    }
2841                    crate::ImageQuery::NumLevels => {
2842                        write!(self.out, "textureQueryLevels(",)?;
2843                        self.write_expr(image, ctx)?;
2844                        write!(self.out, ")",)?;
2845                    }
2846                    crate::ImageQuery::NumLayers => {
2847                        let fun_name = match class {
2848                            ImageClass::Sampled { .. } | ImageClass::Depth { .. } => "textureSize",
2849                            ImageClass::Storage { .. } => "imageSize",
2850                            ImageClass::External => unimplemented!(),
2851                        };
2852                        write!(self.out, "{fun_name}(")?;
2853                        self.write_expr(image, ctx)?;
2854                        // All textureSize calls requires an lod argument
2855                        // except for multisampled samplers
2856                        if !class.is_multisampled() {
2857                            write!(self.out, ", 0")?;
2858                        }
2859                        write!(self.out, ")")?;
2860                        if components != 1 || self.options.version.is_es() {
2861                            write!(self.out, ".{}", back::COMPONENTS[components])?;
2862                        }
2863                    }
2864                    crate::ImageQuery::NumSamples => {
2865                        let fun_name = match class {
2866                            ImageClass::Sampled { .. } | ImageClass::Depth { .. } => {
2867                                "textureSamples"
2868                            }
2869                            ImageClass::Storage { .. } => "imageSamples",
2870                            ImageClass::External => unimplemented!(),
2871                        };
2872                        write!(self.out, "{fun_name}(")?;
2873                        self.write_expr(image, ctx)?;
2874                        write!(self.out, ")",)?;
2875                    }
2876                }
2877
2878                write!(self.out, ")")?;
2879            }
2880            Expression::Unary { op, expr } => {
2881                let operator_or_fn = match op {
2882                    crate::UnaryOperator::Negate => "-",
2883                    crate::UnaryOperator::LogicalNot => {
2884                        match *ctx.resolve_type(expr, &self.module.types) {
2885                            TypeInner::Vector { .. } => "not",
2886                            _ => "!",
2887                        }
2888                    }
2889                    crate::UnaryOperator::BitwiseNot => "~",
2890                };
2891                write!(self.out, "{operator_or_fn}(")?;
2892
2893                self.write_expr(expr, ctx)?;
2894
2895                write!(self.out, ")")?
2896            }
2897            // `Binary` we just write `left op right`, except when dealing with
2898            // comparison operations on vectors as they are implemented with
2899            // builtin functions.
2900            // Once again we wrap everything in parentheses to avoid precedence issues
2901            Expression::Binary {
2902                mut op,
2903                left,
2904                right,
2905            } => {
2906                // Holds `Some(function_name)` if the binary operation is
2907                // implemented as a function call
2908                use crate::{BinaryOperator as Bo, ScalarKind as Sk, TypeInner as Ti};
2909
2910                let left_inner = ctx.resolve_type(left, &self.module.types);
2911                let right_inner = ctx.resolve_type(right, &self.module.types);
2912
2913                let function = match (left_inner, right_inner) {
2914                    (&Ti::Vector { scalar, .. }, &Ti::Vector { .. }) => match op {
2915                        Bo::Less
2916                        | Bo::LessEqual
2917                        | Bo::Greater
2918                        | Bo::GreaterEqual
2919                        | Bo::Equal
2920                        | Bo::NotEqual => BinaryOperation::VectorCompare,
2921                        Bo::Modulo if scalar.kind == Sk::Float => BinaryOperation::Modulo,
2922                        Bo::Modulo if scalar.kind == Sk::Sint || scalar.kind == Sk::Uint => {
2923                            BinaryOperation::ModuloInt
2924                        }
2925                        Bo::And if scalar.kind == Sk::Bool => {
2926                            op = crate::BinaryOperator::LogicalAnd;
2927                            BinaryOperation::VectorComponentWise
2928                        }
2929                        Bo::InclusiveOr if scalar.kind == Sk::Bool => {
2930                            op = crate::BinaryOperator::LogicalOr;
2931                            BinaryOperation::VectorComponentWise
2932                        }
2933                        _ => BinaryOperation::Other,
2934                    },
2935                    _ => match (left_inner.scalar_kind(), right_inner.scalar_kind()) {
2936                        (Some(Sk::Float), _) | (_, Some(Sk::Float)) => match op {
2937                            Bo::Modulo => BinaryOperation::Modulo,
2938                            _ => BinaryOperation::Other,
2939                        },
2940                        (Some(Sk::Sint | Sk::Uint), _) | (_, Some(Sk::Sint | Sk::Uint))
2941                            if op == Bo::Modulo =>
2942                        {
2943                            BinaryOperation::ModuloInt
2944                        }
2945                        (Some(Sk::Bool), Some(Sk::Bool)) => match op {
2946                            Bo::InclusiveOr => {
2947                                op = crate::BinaryOperator::LogicalOr;
2948                                BinaryOperation::Other
2949                            }
2950                            Bo::And => {
2951                                op = crate::BinaryOperator::LogicalAnd;
2952                                BinaryOperation::Other
2953                            }
2954                            _ => BinaryOperation::Other,
2955                        },
2956                        _ => BinaryOperation::Other,
2957                    },
2958                };
2959
2960                match function {
2961                    BinaryOperation::VectorCompare => {
2962                        let op_str = match op {
2963                            Bo::Less => "lessThan(",
2964                            Bo::LessEqual => "lessThanEqual(",
2965                            Bo::Greater => "greaterThan(",
2966                            Bo::GreaterEqual => "greaterThanEqual(",
2967                            Bo::Equal => "equal(",
2968                            Bo::NotEqual => "notEqual(",
2969                            _ => unreachable!(),
2970                        };
2971                        write!(self.out, "{op_str}")?;
2972                        self.write_expr(left, ctx)?;
2973                        write!(self.out, ", ")?;
2974                        self.write_expr(right, ctx)?;
2975                        write!(self.out, ")")?;
2976                    }
2977                    BinaryOperation::VectorComponentWise => {
2978                        self.write_value_type(left_inner)?;
2979                        write!(self.out, "(")?;
2980
2981                        let size = match *left_inner {
2982                            Ti::Vector { size, .. } => size,
2983                            _ => unreachable!(),
2984                        };
2985
2986                        for i in 0..size as usize {
2987                            if i != 0 {
2988                                write!(self.out, ", ")?;
2989                            }
2990
2991                            self.write_expr(left, ctx)?;
2992                            write!(self.out, ".{}", back::COMPONENTS[i])?;
2993
2994                            write!(self.out, " {} ", back::binary_operation_str(op))?;
2995
2996                            self.write_expr(right, ctx)?;
2997                            write!(self.out, ".{}", back::COMPONENTS[i])?;
2998                        }
2999
3000                        write!(self.out, ")")?;
3001                    }
3002                    // Signed/unsigned integer `%` with a negative operand is handled by
3003                    // `BinaryOperation::ModuloInt` below. Remaining TODO: the degenerate
3004                    // div-by-zero / `INT_MIN % -1` cases (this backend also leaves integer
3005                    // `/` unguarded), and float `% 0` (see
3006                    // https://github.com/gpuweb/gpuweb/issues/2798).
3007                    BinaryOperation::Modulo => {
3008                        write!(self.out, "(")?;
3009
3010                        // write `e1 - e2 * trunc(e1 / e2)`
3011                        self.write_expr(left, ctx)?;
3012                        write!(self.out, " - ")?;
3013                        self.write_expr(right, ctx)?;
3014                        write!(self.out, " * ")?;
3015                        write!(self.out, "trunc(")?;
3016                        self.write_expr(left, ctx)?;
3017                        write!(self.out, " / ")?;
3018                        self.write_expr(right, ctx)?;
3019                        write!(self.out, ")")?;
3020
3021                        write!(self.out, ")")?;
3022                    }
3023                    BinaryOperation::ModuloInt => {
3024                        // GLSL's `%` is undefined when either operand is negative.
3025                        // Integer division truncates toward zero (which is well
3026                        // defined), so reconstruct the remainder as `e1 - e2 * (e1 / e2)`.
3027                        // This matches WGSL's truncated `%` for all operands; the
3028                        // degenerate `x % 0` / `INT_MIN % -1` cases stay consistent
3029                        // with this backend's unguarded integer `/`.
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                        self.write_expr(left, ctx)?;
3036                        write!(self.out, " / ")?;
3037                        self.write_expr(right, ctx)?;
3038                        write!(self.out, "))")?;
3039                    }
3040                    BinaryOperation::Other => {
3041                        write!(self.out, "(")?;
3042
3043                        self.write_expr(left, ctx)?;
3044                        write!(self.out, " {} ", back::binary_operation_str(op))?;
3045                        self.write_expr(right, ctx)?;
3046
3047                        write!(self.out, ")")?;
3048                    }
3049                }
3050            }
3051            // `Select` is written as `condition ? accept : reject`
3052            // We wrap everything in parentheses to avoid precedence issues
3053            Expression::Select {
3054                condition,
3055                accept,
3056                reject,
3057            } => {
3058                let cond_ty = ctx.resolve_type(condition, &self.module.types);
3059                let vec_select = if let TypeInner::Vector { .. } = *cond_ty {
3060                    true
3061                } else {
3062                    false
3063                };
3064
3065                if vec_select {
3066                    let result_ty = ctx.resolve_type(accept, &self.module.types);
3067                    let size = match *result_ty {
3068                        TypeInner::Vector { size, .. } => size,
3069                        _ => unreachable!(),
3070                    };
3071                    let is_float =
3072                        matches!(result_ty.scalar_kind(), Some(crate::ScalarKind::Float));
3073
3074                    if is_float || self.options.version.supports_integer_mix() {
3075                        // Glsl defines that for mix when the condition is a boolean the first
3076                        // element is picked if condition is false and the second if condition
3077                        // is true
3078                        write!(self.out, "mix(")?;
3079                        self.write_expr(reject, ctx)?;
3080                        write!(self.out, ", ")?;
3081                        self.write_expr(accept, ctx)?;
3082                        write!(self.out, ", ")?;
3083                        self.write_expr(condition, ctx)?;
3084                        write!(self.out, ")")?;
3085                    } else {
3086                        // No integer `mix` before GLSL 4.50 / ES 3.10.
3087                        self.write_value_type(result_ty)?;
3088                        write!(self.out, "(")?;
3089
3090                        for i in 0..size as usize {
3091                            if i != 0 {
3092                                write!(self.out, ", ")?;
3093                            }
3094
3095                            self.write_expr(condition, ctx)?;
3096                            write!(self.out, ".{} ? ", back::COMPONENTS[i])?;
3097                            self.write_expr(accept, ctx)?;
3098                            write!(self.out, ".{} : ", back::COMPONENTS[i])?;
3099                            self.write_expr(reject, ctx)?;
3100                            write!(self.out, ".{}", back::COMPONENTS[i])?;
3101                        }
3102
3103                        write!(self.out, ")")?;
3104                    }
3105                } else {
3106                    write!(self.out, "(")?;
3107                    self.write_expr(condition, ctx)?;
3108                    write!(self.out, " ? ")?;
3109                    self.write_expr(accept, ctx)?;
3110                    write!(self.out, " : ")?;
3111                    self.write_expr(reject, ctx)?;
3112                    write!(self.out, ")")?;
3113                }
3114            }
3115            // `Derivative` is a function call to a glsl provided function
3116            Expression::Derivative { axis, ctrl, expr } => {
3117                use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
3118                let fun_name = if self.options.version.supports_derivative_control() {
3119                    match (axis, ctrl) {
3120                        (Axis::X, Ctrl::Coarse) => "dFdxCoarse",
3121                        (Axis::X, Ctrl::Fine) => "dFdxFine",
3122                        (Axis::X, Ctrl::None) => "dFdx",
3123                        (Axis::Y, Ctrl::Coarse) => "dFdyCoarse",
3124                        (Axis::Y, Ctrl::Fine) => "dFdyFine",
3125                        (Axis::Y, Ctrl::None) => "dFdy",
3126                        (Axis::Width, Ctrl::Coarse) => "fwidthCoarse",
3127                        (Axis::Width, Ctrl::Fine) => "fwidthFine",
3128                        (Axis::Width, Ctrl::None) => "fwidth",
3129                    }
3130                } else {
3131                    match axis {
3132                        Axis::X => "dFdx",
3133                        Axis::Y => "dFdy",
3134                        Axis::Width => "fwidth",
3135                    }
3136                };
3137                write!(self.out, "{fun_name}(")?;
3138                self.write_expr(expr, ctx)?;
3139                write!(self.out, ")")?
3140            }
3141            // `Relational` is a normal function call to some glsl provided functions
3142            Expression::Relational { fun, argument } => {
3143                use crate::RelationalFunction as Rf;
3144
3145                let fun_name = match fun {
3146                    Rf::IsInf => "isinf",
3147                    Rf::IsNan => "isnan",
3148                    Rf::All => "all",
3149                    Rf::Any => "any",
3150                };
3151                write!(self.out, "{fun_name}(")?;
3152
3153                self.write_expr(argument, ctx)?;
3154
3155                write!(self.out, ")")?
3156            }
3157            Expression::Math {
3158                fun,
3159                arg,
3160                arg1,
3161                arg2,
3162                arg3,
3163            } => {
3164                use crate::MathFunction as Mf;
3165
3166                let fun_name = match fun {
3167                    // comparison
3168                    Mf::Abs => "abs",
3169                    Mf::Min => "min",
3170                    Mf::Max => "max",
3171                    Mf::Clamp => {
3172                        let scalar_kind = ctx
3173                            .resolve_type(arg, &self.module.types)
3174                            .scalar_kind()
3175                            .unwrap();
3176                        match scalar_kind {
3177                            crate::ScalarKind::Float => "clamp",
3178                            // Clamp is undefined if min > max. In practice this means it can use a median-of-three
3179                            // instruction to determine the value. This is fine according to the WGSL spec for float
3180                            // clamp, but integer clamp _must_ use min-max. As such we write out min/max.
3181                            _ => {
3182                                write!(self.out, "min(max(")?;
3183                                self.write_expr(arg, ctx)?;
3184                                write!(self.out, ", ")?;
3185                                self.write_expr(arg1.unwrap(), ctx)?;
3186                                write!(self.out, "), ")?;
3187                                self.write_expr(arg2.unwrap(), ctx)?;
3188                                write!(self.out, ")")?;
3189
3190                                return Ok(());
3191                            }
3192                        }
3193                    }
3194                    Mf::Saturate => {
3195                        write!(self.out, "clamp(")?;
3196
3197                        self.write_expr(arg, ctx)?;
3198
3199                        match *ctx.resolve_type(arg, &self.module.types) {
3200                            TypeInner::Vector { size, .. } => write!(
3201                                self.out,
3202                                ", vec{}(0.0), vec{0}(1.0)",
3203                                common::vector_size_str(size)
3204                            )?,
3205                            _ => write!(self.out, ", 0.0, 1.0")?,
3206                        }
3207
3208                        write!(self.out, ")")?;
3209
3210                        return Ok(());
3211                    }
3212                    // trigonometry
3213                    Mf::Cos => "cos",
3214                    Mf::Cosh => "cosh",
3215                    Mf::Sin => "sin",
3216                    Mf::Sinh => "sinh",
3217                    Mf::Tan => "tan",
3218                    Mf::Tanh => "tanh",
3219                    Mf::Acos => "acos",
3220                    Mf::Asin => "asin",
3221                    Mf::Atan => "atan",
3222                    Mf::Asinh => "asinh",
3223                    Mf::Acosh => "acosh",
3224                    Mf::Atanh => "atanh",
3225                    Mf::Radians => "radians",
3226                    Mf::Degrees => "degrees",
3227                    // glsl doesn't have atan2 function
3228                    // use two-argument variation of the atan function
3229                    Mf::Atan2 => "atan",
3230                    // decomposition
3231                    Mf::Ceil => "ceil",
3232                    Mf::Floor => "floor",
3233                    Mf::Round => "roundEven",
3234                    Mf::Fract => "fract",
3235                    Mf::Trunc => "trunc",
3236                    Mf::Modf => MODF_FUNCTION,
3237                    Mf::Frexp => FREXP_FUNCTION,
3238                    Mf::Ldexp => "ldexp",
3239                    // exponent
3240                    Mf::Exp => "exp",
3241                    Mf::Exp2 => "exp2",
3242                    Mf::Log => "log",
3243                    Mf::Log2 => "log2",
3244                    Mf::Pow => "pow",
3245                    // geometry
3246                    Mf::Dot => match *ctx.resolve_type(arg, &self.module.types) {
3247                        TypeInner::Vector {
3248                            scalar:
3249                                crate::Scalar {
3250                                    kind: crate::ScalarKind::Float,
3251                                    ..
3252                                },
3253                            ..
3254                        } => "dot",
3255                        TypeInner::Vector { size, .. } => {
3256                            return self.write_dot_product(arg, arg1.unwrap(), size as usize, ctx)
3257                        }
3258                        _ => unreachable!(
3259                            "Correct TypeInner for dot product should be already validated"
3260                        ),
3261                    },
3262                    fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => {
3263                        let conversion = match fun {
3264                            Mf::Dot4I8Packed => "int",
3265                            Mf::Dot4U8Packed => "",
3266                            _ => unreachable!(),
3267                        };
3268
3269                        let arg1 = arg1.unwrap();
3270
3271                        // Write parentheses around the dot product expression to prevent operators
3272                        // with different precedences from applying earlier.
3273                        write!(self.out, "(")?;
3274                        for i in 0..4 {
3275                            // Since `bitfieldExtract` only sign extends if the value is signed, we
3276                            // need to convert the inputs to `int` in case of `Dot4I8Packed`. For
3277                            // `Dot4U8Packed`, the code below only introduces parenthesis around
3278                            // each factor, which aren't strictly needed because both operands are
3279                            // baked, but which don't hurt either.
3280                            write!(self.out, "bitfieldExtract({conversion}(")?;
3281                            self.write_expr(arg, ctx)?;
3282                            write!(self.out, "), {}, 8)", i * 8)?;
3283
3284                            write!(self.out, " * bitfieldExtract({conversion}(")?;
3285                            self.write_expr(arg1, ctx)?;
3286                            write!(self.out, "), {}, 8)", i * 8)?;
3287
3288                            if i != 3 {
3289                                write!(self.out, " + ")?;
3290                            }
3291                        }
3292                        write!(self.out, ")")?;
3293
3294                        return Ok(());
3295                    }
3296                    Mf::Outer => "outerProduct",
3297                    Mf::Cross => "cross",
3298                    Mf::Distance => "distance",
3299                    Mf::Length => "length",
3300                    Mf::Normalize => "normalize",
3301                    Mf::FaceForward => "faceforward",
3302                    Mf::Reflect => "reflect",
3303                    Mf::Refract => "refract",
3304                    // computational
3305                    Mf::Sign => "sign",
3306                    Mf::Fma => {
3307                        if self.options.version.supports_fma_function() {
3308                            // Use the fma function when available
3309                            "fma"
3310                        } else {
3311                            // No fma support. Transform the function call into an arithmetic expression
3312                            write!(self.out, "(")?;
3313
3314                            self.write_expr(arg, ctx)?;
3315                            write!(self.out, " * ")?;
3316
3317                            let arg1 =
3318                                arg1.ok_or_else(|| Error::Custom("Missing fma arg1".to_owned()))?;
3319                            self.write_expr(arg1, ctx)?;
3320                            write!(self.out, " + ")?;
3321
3322                            let arg2 =
3323                                arg2.ok_or_else(|| Error::Custom("Missing fma arg2".to_owned()))?;
3324                            self.write_expr(arg2, ctx)?;
3325                            write!(self.out, ")")?;
3326
3327                            return Ok(());
3328                        }
3329                    }
3330                    Mf::Mix => "mix",
3331                    Mf::Step => "step",
3332                    Mf::SmoothStep => "smoothstep",
3333                    Mf::Sqrt => "sqrt",
3334                    Mf::InverseSqrt => "inversesqrt",
3335                    Mf::Inverse => "inverse",
3336                    Mf::Transpose => "transpose",
3337                    Mf::Determinant => "determinant",
3338                    Mf::QuantizeToF16 => match *ctx.resolve_type(arg, &self.module.types) {
3339                        TypeInner::Scalar { .. } => {
3340                            write!(self.out, "unpackHalf2x16(packHalf2x16(vec2(")?;
3341                            self.write_expr(arg, ctx)?;
3342                            write!(self.out, "))).x")?;
3343                            return Ok(());
3344                        }
3345                        TypeInner::Vector {
3346                            size: crate::VectorSize::Bi,
3347                            ..
3348                        } => {
3349                            write!(self.out, "unpackHalf2x16(packHalf2x16(")?;
3350                            self.write_expr(arg, ctx)?;
3351                            write!(self.out, "))")?;
3352                            return Ok(());
3353                        }
3354                        TypeInner::Vector {
3355                            size: crate::VectorSize::Tri,
3356                            ..
3357                        } => {
3358                            write!(self.out, "vec3(unpackHalf2x16(packHalf2x16(")?;
3359                            self.write_expr(arg, ctx)?;
3360                            write!(self.out, ".xy)), unpackHalf2x16(packHalf2x16(")?;
3361                            self.write_expr(arg, ctx)?;
3362                            write!(self.out, ".zz)).x)")?;
3363                            return Ok(());
3364                        }
3365                        TypeInner::Vector {
3366                            size: crate::VectorSize::Quad,
3367                            ..
3368                        } => {
3369                            write!(self.out, "vec4(unpackHalf2x16(packHalf2x16(")?;
3370                            self.write_expr(arg, ctx)?;
3371                            write!(self.out, ".xy)), unpackHalf2x16(packHalf2x16(")?;
3372                            self.write_expr(arg, ctx)?;
3373                            write!(self.out, ".zw)))")?;
3374                            return Ok(());
3375                        }
3376                        _ => unreachable!(
3377                            "Correct TypeInner for QuantizeToF16 should be already validated"
3378                        ),
3379                    },
3380                    // bits
3381                    Mf::CountTrailingZeros => {
3382                        match *ctx.resolve_type(arg, &self.module.types) {
3383                            TypeInner::Vector { size, scalar, .. } => {
3384                                let s = common::vector_size_str(size);
3385                                if let crate::ScalarKind::Uint = scalar.kind {
3386                                    write!(self.out, "min(uvec{s}(findLSB(")?;
3387                                    self.write_expr(arg, ctx)?;
3388                                    write!(self.out, ")), uvec{s}(32u))")?;
3389                                } else {
3390                                    write!(self.out, "ivec{s}(min(uvec{s}(findLSB(")?;
3391                                    self.write_expr(arg, ctx)?;
3392                                    write!(self.out, ")), uvec{s}(32u)))")?;
3393                                }
3394                            }
3395                            TypeInner::Scalar(scalar) => {
3396                                if let crate::ScalarKind::Uint = scalar.kind {
3397                                    write!(self.out, "min(uint(findLSB(")?;
3398                                    self.write_expr(arg, ctx)?;
3399                                    write!(self.out, ")), 32u)")?;
3400                                } else {
3401                                    write!(self.out, "int(min(uint(findLSB(")?;
3402                                    self.write_expr(arg, ctx)?;
3403                                    write!(self.out, ")), 32u))")?;
3404                                }
3405                            }
3406                            _ => unreachable!(),
3407                        };
3408                        return Ok(());
3409                    }
3410                    Mf::CountLeadingZeros => {
3411                        if self.options.version.supports_integer_functions() {
3412                            match *ctx.resolve_type(arg, &self.module.types) {
3413                                TypeInner::Vector { size, scalar } => {
3414                                    let s = common::vector_size_str(size);
3415
3416                                    if let crate::ScalarKind::Uint = scalar.kind {
3417                                        write!(self.out, "uvec{s}(ivec{s}(31) - findMSB(")?;
3418                                        self.write_expr(arg, ctx)?;
3419                                        write!(self.out, "))")?;
3420                                    } else {
3421                                        write!(self.out, "mix(ivec{s}(31) - findMSB(")?;
3422                                        self.write_expr(arg, ctx)?;
3423                                        write!(self.out, "), ivec{s}(0), lessThan(")?;
3424                                        self.write_expr(arg, ctx)?;
3425                                        write!(self.out, ", ivec{s}(0)))")?;
3426                                    }
3427                                }
3428                                TypeInner::Scalar(scalar) => {
3429                                    if let crate::ScalarKind::Uint = scalar.kind {
3430                                        write!(self.out, "uint(31 - findMSB(")?;
3431                                    } else {
3432                                        write!(self.out, "(")?;
3433                                        self.write_expr(arg, ctx)?;
3434                                        write!(self.out, " < 0 ? 0 : 31 - findMSB(")?;
3435                                    }
3436
3437                                    self.write_expr(arg, ctx)?;
3438                                    write!(self.out, "))")?;
3439                                }
3440                                _ => unreachable!(),
3441                            };
3442                        } else {
3443                            match *ctx.resolve_type(arg, &self.module.types) {
3444                                TypeInner::Vector { size, scalar } => {
3445                                    let s = common::vector_size_str(size);
3446
3447                                    if let crate::ScalarKind::Uint = scalar.kind {
3448                                        write!(self.out, "uvec{s}(")?;
3449                                        write!(self.out, "vec{s}(31.0) - floor(log2(vec{s}(")?;
3450                                        self.write_expr(arg, ctx)?;
3451                                        write!(self.out, ") + 0.5)))")?;
3452                                    } else {
3453                                        write!(self.out, "ivec{s}(")?;
3454                                        write!(self.out, "mix(vec{s}(31.0) - floor(log2(vec{s}(")?;
3455                                        self.write_expr(arg, ctx)?;
3456                                        write!(self.out, ") + 0.5)), ")?;
3457                                        write!(self.out, "vec{s}(0.0), lessThan(")?;
3458                                        self.write_expr(arg, ctx)?;
3459                                        write!(self.out, ", ivec{s}(0u))))")?;
3460                                    }
3461                                }
3462                                TypeInner::Scalar(scalar) => {
3463                                    if let crate::ScalarKind::Uint = scalar.kind {
3464                                        write!(self.out, "uint(31.0 - floor(log2(float(")?;
3465                                        self.write_expr(arg, ctx)?;
3466                                        write!(self.out, ") + 0.5)))")?;
3467                                    } else {
3468                                        write!(self.out, "(")?;
3469                                        self.write_expr(arg, ctx)?;
3470                                        write!(self.out, " < 0 ? 0 : int(")?;
3471                                        write!(self.out, "31.0 - floor(log2(float(")?;
3472                                        self.write_expr(arg, ctx)?;
3473                                        write!(self.out, ") + 0.5))))")?;
3474                                    }
3475                                }
3476                                _ => unreachable!(),
3477                            };
3478                        }
3479
3480                        return Ok(());
3481                    }
3482                    Mf::CountOneBits => "bitCount",
3483                    Mf::ReverseBits => "bitfieldReverse",
3484                    Mf::ExtractBits => {
3485                        // The behavior of ExtractBits is undefined when offset + count > bit_width. We need
3486                        // to first sanitize the offset and count first. If we don't do this, AMD and Intel chips
3487                        // will return out-of-spec values if the extracted range is not within the bit width.
3488                        //
3489                        // This encodes the exact formula specified by the wgsl spec, without temporary values:
3490                        // https://gpuweb.github.io/gpuweb/wgsl/#extractBits-unsigned-builtin
3491                        //
3492                        // w = sizeof(x) * 8
3493                        // o = min(offset, w)
3494                        // c = min(count, w - o)
3495                        //
3496                        // bitfieldExtract(x, o, c)
3497                        //
3498                        // extract_bits(e, min(offset, w), min(count, w - min(offset, w))))
3499                        let scalar_bits = ctx
3500                            .resolve_type(arg, &self.module.types)
3501                            .scalar_width()
3502                            .unwrap()
3503                            * 8;
3504
3505                        write!(self.out, "bitfieldExtract(")?;
3506                        self.write_expr(arg, ctx)?;
3507                        write!(self.out, ", int(min(")?;
3508                        self.write_expr(arg1.unwrap(), ctx)?;
3509                        write!(self.out, ", {scalar_bits}u)), int(min(",)?;
3510                        self.write_expr(arg2.unwrap(), ctx)?;
3511                        write!(self.out, ", {scalar_bits}u - min(")?;
3512                        self.write_expr(arg1.unwrap(), ctx)?;
3513                        write!(self.out, ", {scalar_bits}u))))")?;
3514
3515                        return Ok(());
3516                    }
3517                    Mf::InsertBits => {
3518                        // InsertBits has the same considerations as ExtractBits above
3519                        let scalar_bits = ctx
3520                            .resolve_type(arg, &self.module.types)
3521                            .scalar_width()
3522                            .unwrap()
3523                            * 8;
3524
3525                        write!(self.out, "bitfieldInsert(")?;
3526                        self.write_expr(arg, ctx)?;
3527                        write!(self.out, ", ")?;
3528                        self.write_expr(arg1.unwrap(), ctx)?;
3529                        write!(self.out, ", int(min(")?;
3530                        self.write_expr(arg2.unwrap(), ctx)?;
3531                        write!(self.out, ", {scalar_bits}u)), int(min(",)?;
3532                        self.write_expr(arg3.unwrap(), ctx)?;
3533                        write!(self.out, ", {scalar_bits}u - min(")?;
3534                        self.write_expr(arg2.unwrap(), ctx)?;
3535                        write!(self.out, ", {scalar_bits}u))))")?;
3536
3537                        return Ok(());
3538                    }
3539                    Mf::FirstTrailingBit => "findLSB",
3540                    Mf::FirstLeadingBit => "findMSB",
3541                    // data packing
3542                    Mf::Pack4x8snorm => {
3543                        if self.options.version.supports_pack_unpack_4x8() {
3544                            "packSnorm4x8"
3545                        } else {
3546                            // polyfill should go here. Needs a corresponding entry in `need_bake_expression`
3547                            return Err(Error::UnsupportedExternal("packSnorm4x8".into()));
3548                        }
3549                    }
3550                    Mf::Pack4x8unorm => {
3551                        if self.options.version.supports_pack_unpack_4x8() {
3552                            "packUnorm4x8"
3553                        } else {
3554                            return Err(Error::UnsupportedExternal("packUnorm4x8".to_owned()));
3555                        }
3556                    }
3557                    Mf::Pack2x16snorm => {
3558                        if self.options.version.supports_pack_unpack_snorm_2x16() {
3559                            "packSnorm2x16"
3560                        } else {
3561                            return Err(Error::UnsupportedExternal("packSnorm2x16".to_owned()));
3562                        }
3563                    }
3564                    Mf::Pack2x16unorm => {
3565                        if self.options.version.supports_pack_unpack_unorm_2x16() {
3566                            "packUnorm2x16"
3567                        } else {
3568                            return Err(Error::UnsupportedExternal("packUnorm2x16".to_owned()));
3569                        }
3570                    }
3571                    Mf::Pack2x16float => {
3572                        if self.options.version.supports_pack_unpack_half_2x16() {
3573                            "packHalf2x16"
3574                        } else {
3575                            return Err(Error::UnsupportedExternal("packHalf2x16".to_owned()));
3576                        }
3577                    }
3578
3579                    fun @ (Mf::Pack4xI8 | Mf::Pack4xU8 | Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp) => {
3580                        let was_signed = matches!(fun, Mf::Pack4xI8 | Mf::Pack4xI8Clamp);
3581                        let clamp_bounds = match fun {
3582                            Mf::Pack4xI8Clamp => Some(("-128", "127")),
3583                            Mf::Pack4xU8Clamp => Some(("0", "255")),
3584                            _ => None,
3585                        };
3586                        let const_suffix = if was_signed { "" } else { "u" };
3587                        if was_signed {
3588                            write!(self.out, "uint(")?;
3589                        }
3590                        let write_arg = |this: &mut Self| -> BackendResult {
3591                            if let Some((min, max)) = clamp_bounds {
3592                                write!(this.out, "clamp(")?;
3593                                this.write_expr(arg, ctx)?;
3594                                write!(this.out, ", {min}{const_suffix}, {max}{const_suffix})")?;
3595                            } else {
3596                                this.write_expr(arg, ctx)?;
3597                            }
3598                            Ok(())
3599                        };
3600                        write!(self.out, "(")?;
3601                        write_arg(self)?;
3602                        write!(self.out, "[0] & 0xFF{const_suffix}) | ((")?;
3603                        write_arg(self)?;
3604                        write!(self.out, "[1] & 0xFF{const_suffix}) << 8) | ((")?;
3605                        write_arg(self)?;
3606                        write!(self.out, "[2] & 0xFF{const_suffix}) << 16) | ((")?;
3607                        write_arg(self)?;
3608                        write!(self.out, "[3] & 0xFF{const_suffix}) << 24)")?;
3609                        if was_signed {
3610                            write!(self.out, ")")?;
3611                        }
3612
3613                        return Ok(());
3614                    }
3615                    // data unpacking
3616                    Mf::Unpack2x16float => {
3617                        if self.options.version.supports_pack_unpack_half_2x16() {
3618                            "unpackHalf2x16"
3619                        } else {
3620                            return Err(Error::UnsupportedExternal("unpackHalf2x16".into()));
3621                        }
3622                    }
3623                    Mf::Unpack2x16snorm => {
3624                        if self.options.version.supports_pack_unpack_snorm_2x16() {
3625                            "unpackSnorm2x16"
3626                        } else {
3627                            let scale = 32767;
3628
3629                            write!(self.out, "(vec2(ivec2(")?;
3630                            self.write_expr(arg, ctx)?;
3631                            write!(self.out, " << 16, ")?;
3632                            self.write_expr(arg, ctx)?;
3633                            write!(self.out, ") >> 16) / {scale}.0)")?;
3634                            return Ok(());
3635                        }
3636                    }
3637                    Mf::Unpack2x16unorm => {
3638                        if self.options.version.supports_pack_unpack_unorm_2x16() {
3639                            "unpackUnorm2x16"
3640                        } else {
3641                            let scale = 65535;
3642
3643                            write!(self.out, "(vec2(")?;
3644                            self.write_expr(arg, ctx)?;
3645                            write!(self.out, " & 0xFFFFu, ")?;
3646                            self.write_expr(arg, ctx)?;
3647                            write!(self.out, " >> 16) / {scale}.0)")?;
3648                            return Ok(());
3649                        }
3650                    }
3651                    Mf::Unpack4x8snorm => {
3652                        if self.options.version.supports_pack_unpack_4x8() {
3653                            "unpackSnorm4x8"
3654                        } else {
3655                            let scale = 127;
3656
3657                            write!(self.out, "(vec4(ivec4(")?;
3658                            self.write_expr(arg, ctx)?;
3659                            write!(self.out, " << 24, ")?;
3660                            self.write_expr(arg, ctx)?;
3661                            write!(self.out, " << 16, ")?;
3662                            self.write_expr(arg, ctx)?;
3663                            write!(self.out, " << 8, ")?;
3664                            self.write_expr(arg, ctx)?;
3665                            write!(self.out, ") >> 24) / {scale}.0)")?;
3666                            return Ok(());
3667                        }
3668                    }
3669                    Mf::Unpack4x8unorm => {
3670                        if self.options.version.supports_pack_unpack_4x8() {
3671                            "unpackUnorm4x8"
3672                        } else {
3673                            let scale = 255;
3674
3675                            write!(self.out, "(vec4(")?;
3676                            self.write_expr(arg, ctx)?;
3677                            write!(self.out, " & 0xFFu, ")?;
3678                            self.write_expr(arg, ctx)?;
3679                            write!(self.out, " >> 8 & 0xFFu, ")?;
3680                            self.write_expr(arg, ctx)?;
3681                            write!(self.out, " >> 16 & 0xFFu, ")?;
3682                            self.write_expr(arg, ctx)?;
3683                            write!(self.out, " >> 24) / {scale}.0)")?;
3684                            return Ok(());
3685                        }
3686                    }
3687                    fun @ (Mf::Unpack4xI8 | Mf::Unpack4xU8) => {
3688                        let sign_prefix = match fun {
3689                            Mf::Unpack4xI8 => 'i',
3690                            Mf::Unpack4xU8 => 'u',
3691                            _ => unreachable!(),
3692                        };
3693                        write!(self.out, "{sign_prefix}vec4(")?;
3694                        for i in 0..4 {
3695                            write!(self.out, "bitfieldExtract(")?;
3696                            // Since bitfieldExtract only sign extends if the value is signed, this
3697                            // cast is needed
3698                            match fun {
3699                                Mf::Unpack4xI8 => {
3700                                    write!(self.out, "int(")?;
3701                                    self.write_expr(arg, ctx)?;
3702                                    write!(self.out, ")")?;
3703                                }
3704                                Mf::Unpack4xU8 => self.write_expr(arg, ctx)?,
3705                                _ => unreachable!(),
3706                            };
3707                            write!(self.out, ", {}, 8)", i * 8)?;
3708                            if i != 3 {
3709                                write!(self.out, ", ")?;
3710                            }
3711                        }
3712                        write!(self.out, ")")?;
3713
3714                        return Ok(());
3715                    }
3716                };
3717
3718                let extract_bits = fun == Mf::ExtractBits;
3719                let insert_bits = fun == Mf::InsertBits;
3720
3721                // Some GLSL functions always return signed integers (like findMSB),
3722                // so they need to be cast to uint if the argument is also an uint.
3723                let ret_might_need_int_to_uint = matches!(
3724                    fun,
3725                    Mf::FirstTrailingBit | Mf::FirstLeadingBit | Mf::CountOneBits | Mf::Abs
3726                );
3727
3728                // Some GLSL functions only accept signed integers (like abs),
3729                // so they need their argument cast from uint to int.
3730                let arg_might_need_uint_to_int = matches!(fun, Mf::Abs);
3731
3732                // Check if the argument is an unsigned integer and return the vector size
3733                // in case it's a vector
3734                let maybe_uint_size = match *ctx.resolve_type(arg, &self.module.types) {
3735                    TypeInner::Scalar(crate::Scalar {
3736                        kind: crate::ScalarKind::Uint,
3737                        ..
3738                    }) => Some(None),
3739                    TypeInner::Vector {
3740                        scalar:
3741                            crate::Scalar {
3742                                kind: crate::ScalarKind::Uint,
3743                                ..
3744                            },
3745                        size,
3746                    } => Some(Some(size)),
3747                    _ => None,
3748                };
3749
3750                // Cast to uint if the function needs it
3751                if ret_might_need_int_to_uint {
3752                    if let Some(maybe_size) = maybe_uint_size {
3753                        match maybe_size {
3754                            Some(size) => write!(self.out, "uvec{}(", size as u8)?,
3755                            None => write!(self.out, "uint(")?,
3756                        }
3757                    }
3758                }
3759
3760                write!(self.out, "{fun_name}(")?;
3761
3762                // Cast to int if the function needs it
3763                if arg_might_need_uint_to_int {
3764                    if let Some(maybe_size) = maybe_uint_size {
3765                        match maybe_size {
3766                            Some(size) => write!(self.out, "ivec{}(", size as u8)?,
3767                            None => write!(self.out, "int(")?,
3768                        }
3769                    }
3770                }
3771
3772                self.write_expr(arg, ctx)?;
3773
3774                // Close the cast from uint to int
3775                if arg_might_need_uint_to_int && maybe_uint_size.is_some() {
3776                    write!(self.out, ")")?
3777                }
3778
3779                if let Some(arg) = arg1 {
3780                    write!(self.out, ", ")?;
3781                    if extract_bits {
3782                        write!(self.out, "int(")?;
3783                        self.write_expr(arg, ctx)?;
3784                        write!(self.out, ")")?;
3785                    } else {
3786                        self.write_expr(arg, ctx)?;
3787                    }
3788                }
3789                if let Some(arg) = arg2 {
3790                    write!(self.out, ", ")?;
3791                    if extract_bits || insert_bits {
3792                        write!(self.out, "int(")?;
3793                        self.write_expr(arg, ctx)?;
3794                        write!(self.out, ")")?;
3795                    } else {
3796                        self.write_expr(arg, ctx)?;
3797                    }
3798                }
3799                if let Some(arg) = arg3 {
3800                    write!(self.out, ", ")?;
3801                    if insert_bits {
3802                        write!(self.out, "int(")?;
3803                        self.write_expr(arg, ctx)?;
3804                        write!(self.out, ")")?;
3805                    } else {
3806                        self.write_expr(arg, ctx)?;
3807                    }
3808                }
3809                write!(self.out, ")")?;
3810
3811                // Close the cast from int to uint
3812                if ret_might_need_int_to_uint && maybe_uint_size.is_some() {
3813                    write!(self.out, ")")?
3814                }
3815            }
3816            // `As` is always a call, whose name is the target type.
3817            Expression::As { expr, target } => {
3818                let inner = ctx.resolve_type(expr, &self.module.types);
3819                // this is similar to `write_type`, but with the target scalar
3820                let scalar = glsl_scalar(target)?;
3821                match *inner {
3822                    TypeInner::Matrix { columns, rows, .. } => write!(
3823                        self.out,
3824                        "{}mat{}x{}",
3825                        scalar.prefix, columns as u8, rows as u8
3826                    )?,
3827                    TypeInner::Vector { size, .. } => {
3828                        write!(self.out, "{}vec{}", scalar.prefix, size as u8)?
3829                    }
3830                    _ => write!(self.out, "{}", scalar.full)?,
3831                }
3832
3833                write!(self.out, "(")?;
3834                self.write_expr(expr, ctx)?;
3835                write!(self.out, ")")?
3836            }
3837            // `Bitcast` is a call to one of the glsl provided bitcast functions,
3838            // or to a constructor when only the signedness of an integer changes.
3839            Expression::Bitcast { expr, ty } => {
3840                use crate::ScalarKind as Sk;
3841
3842                let inner = ctx.resolve_type(expr, &self.module.types);
3843                let target = &self.module.types[ty].inner;
3844
3845                if inner == target {
3846                    return self.write_expr(expr, ctx);
3847                }
3848
3849                let unsupported =
3850                    || Error::Custom(format!("GLSL cannot bitcast from {inner:?} to {target:?}"));
3851                let (Some((src_size, src)), Some((dst_size, dst))) = (
3852                    inner.vector_size_and_scalar(),
3853                    target.vector_size_and_scalar(),
3854                ) else {
3855                    return Err(unsupported());
3856                };
3857                if src_size != dst_size {
3858                    return Err(unsupported());
3859                }
3860
3861                match (src.kind, dst.kind) {
3862                    (Sk::Float, Sk::Sint) if src.width == 4 => write!(self.out, "floatBitsToInt")?,
3863                    (Sk::Float, Sk::Uint) if src.width == 4 => write!(self.out, "floatBitsToUint")?,
3864                    (Sk::Sint, Sk::Float) if src.width == 4 => write!(self.out, "intBitsToFloat")?,
3865                    (Sk::Uint, Sk::Float) if src.width == 4 => write!(self.out, "uintBitsToFloat")?,
3866                    // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion
3867                    (Sk::Uint, Sk::Sint) | (Sk::Sint, Sk::Uint) => {
3868                        self.write_value_type(target)?;
3869                    }
3870                    _ => return Err(unsupported()),
3871                };
3872
3873                write!(self.out, "(")?;
3874                self.write_expr(expr, ctx)?;
3875                write!(self.out, ")")?;
3876            }
3877            // These expressions never show up in `Emit`.
3878            Expression::CallResult(_)
3879            | Expression::AtomicResult { .. }
3880            | Expression::RayQueryProceedResult
3881            | Expression::WorkGroupUniformLoadResult { .. }
3882            | Expression::SubgroupOperationResult { .. }
3883            | Expression::SubgroupBallotResult => unreachable!(),
3884            // `ArrayLength` is written as `expr.length()` and we convert it to a uint
3885            Expression::ArrayLength(expr) => {
3886                write!(self.out, "uint(")?;
3887                self.write_expr(expr, ctx)?;
3888                write!(self.out, ".length())")?
3889            }
3890            // not supported yet
3891            Expression::RayQueryGetIntersection { .. }
3892            | Expression::RayQueryVertexPositions { .. }
3893            | Expression::HitObjectQuery { .. }
3894            | Expression::CooperativeLoad { .. }
3895            | Expression::CooperativeMultiplyAdd { .. } => unreachable!(),
3896        }
3897
3898        Ok(())
3899    }
3900
3901    /// Writes `expr`, wrapped in `int(...)` if it is an unsigned scalar.
3902    ///
3903    /// GLSL image functions only take `int` levels and sample indices, while WGSL also
3904    /// allows `u32`.
3905    fn write_expr_as_int(
3906        &mut self,
3907        expr: Handle<crate::Expression>,
3908        ctx: &back::FunctionCtx,
3909    ) -> BackendResult {
3910        let cast_to_int = matches!(
3911            *ctx.resolve_type(expr, &self.module.types),
3912            TypeInner::Scalar(crate::Scalar {
3913                kind: crate::ScalarKind::Uint,
3914                ..
3915            })
3916        );
3917
3918        if cast_to_int {
3919            write!(self.out, "int(")?;
3920        }
3921
3922        self.write_expr(expr, ctx)?;
3923
3924        if cast_to_int {
3925            write!(self.out, ")")?;
3926        }
3927
3928        Ok(())
3929    }
3930
3931    /// Helper function to write the local holding the clamped lod
3932    fn write_clamped_lod(
3933        &mut self,
3934        ctx: &back::FunctionCtx,
3935        expr: Handle<crate::Expression>,
3936        image: Handle<crate::Expression>,
3937        level_expr: Handle<crate::Expression>,
3938    ) -> Result<(), Error> {
3939        // Define our local and start a call to `clamp`
3940        write!(
3941            self.out,
3942            "int {}{} = clamp(",
3943            Baked(expr),
3944            CLAMPED_LOD_SUFFIX
3945        )?;
3946        // Write the lod that will be clamped
3947        self.write_expr_as_int(level_expr, ctx)?;
3948        // Set the min value to 0 and start a call to `textureQueryLevels` to get
3949        // the maximum value
3950        write!(self.out, ", 0, textureQueryLevels(")?;
3951        // Write the target image as an argument to `textureQueryLevels`
3952        self.write_expr(image, ctx)?;
3953        // Close the call to `textureQueryLevels` subtract 1 from it since
3954        // the lod argument is 0 based, close the `clamp` call and end the
3955        // local declaration statement.
3956        writeln!(self.out, ") - 1);")?;
3957
3958        Ok(())
3959    }
3960
3961    // Helper method used to retrieve how many elements a coordinate vector
3962    // for the images operations need.
3963    fn get_coordinate_vector_size(&self, dim: crate::ImageDimension, arrayed: bool) -> u8 {
3964        // openGL es doesn't have 1D images so we need workaround it
3965        let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es();
3966        // Get how many components the coordinate vector needs for the dimensions only
3967        let tex_coord_size = match dim {
3968            crate::ImageDimension::D1 => 1,
3969            crate::ImageDimension::D2 => 2,
3970            crate::ImageDimension::D3 => 3,
3971            crate::ImageDimension::Cube => 2,
3972        };
3973        // Calculate the true size of the coordinate vector by adding 1 for arrayed images
3974        // and another 1 if we need to workaround 1D images by making them 2D
3975        tex_coord_size + tex_1d_hack as u8 + arrayed as u8
3976    }
3977
3978    /// Helper method to write the coordinate vector for image operations
3979    fn write_texture_coord(
3980        &mut self,
3981        ctx: &back::FunctionCtx,
3982        vector_size: u8,
3983        coordinate: Handle<crate::Expression>,
3984        array_index: Option<Handle<crate::Expression>>,
3985        // Emulate 1D images as 2D for profiles that don't support it (glsl es)
3986        tex_1d_hack: bool,
3987    ) -> Result<(), Error> {
3988        match array_index {
3989            // If the image needs an array indice we need to add it to the end of our
3990            // coordinate vector, to do so we will use the `ivec(ivec, scalar)`
3991            // constructor notation (NOTE: the inner `ivec` can also be a scalar, this
3992            // is important for 1D arrayed images).
3993            Some(layer_expr) => {
3994                write!(self.out, "ivec{vector_size}(")?;
3995                self.write_expr(coordinate, ctx)?;
3996                write!(self.out, ", ")?;
3997                // If we are replacing sampler1D with sampler2D we also need
3998                // to add another zero to the coordinates vector for the y component
3999                if tex_1d_hack {
4000                    write!(self.out, "0, ")?;
4001                }
4002                self.write_expr(layer_expr, ctx)?;
4003                write!(self.out, ")")?;
4004            }
4005            // Otherwise write just the expression (and the 1D hack if needed)
4006            None => {
4007                let uvec_size = match *ctx.resolve_type(coordinate, &self.module.types) {
4008                    TypeInner::Scalar(crate::Scalar {
4009                        kind: crate::ScalarKind::Uint,
4010                        ..
4011                    }) => Some(None),
4012                    TypeInner::Vector {
4013                        size,
4014                        scalar:
4015                            crate::Scalar {
4016                                kind: crate::ScalarKind::Uint,
4017                                ..
4018                            },
4019                    } => Some(Some(size as u32)),
4020                    _ => None,
4021                };
4022                if tex_1d_hack {
4023                    write!(self.out, "ivec2(")?;
4024                } else if uvec_size.is_some() {
4025                    match uvec_size {
4026                        Some(None) => write!(self.out, "int(")?,
4027                        Some(Some(size)) => write!(self.out, "ivec{size}(")?,
4028                        _ => {}
4029                    }
4030                }
4031                self.write_expr(coordinate, ctx)?;
4032                if tex_1d_hack {
4033                    write!(self.out, ", 0)")?;
4034                } else if uvec_size.is_some() {
4035                    write!(self.out, ")")?;
4036                }
4037            }
4038        }
4039
4040        Ok(())
4041    }
4042
4043    /// Helper method to write the `ImageStore` statement
4044    fn write_image_store(
4045        &mut self,
4046        ctx: &back::FunctionCtx,
4047        image: Handle<crate::Expression>,
4048        coordinate: Handle<crate::Expression>,
4049        array_index: Option<Handle<crate::Expression>>,
4050        value: Handle<crate::Expression>,
4051    ) -> Result<(), Error> {
4052        use crate::ImageDimension as IDim;
4053
4054        // NOTE: openGL requires that `imageStore`s have no effects when the texel is invalid
4055        // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20)
4056
4057        // This will only panic if the module is invalid
4058        let dim = match *ctx.resolve_type(image, &self.module.types) {
4059            TypeInner::Image { dim, .. } => dim,
4060            _ => unreachable!(),
4061        };
4062
4063        // Begin our call to `imageStore`
4064        write!(self.out, "imageStore(")?;
4065        self.write_expr(image, ctx)?;
4066        // Separate the image argument from the coordinates
4067        write!(self.out, ", ")?;
4068
4069        // openGL es doesn't have 1D images so we need workaround it
4070        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4071        // Write the coordinate vector
4072        self.write_texture_coord(
4073            ctx,
4074            // Get the size of the coordinate vector
4075            self.get_coordinate_vector_size(dim, array_index.is_some()),
4076            coordinate,
4077            array_index,
4078            tex_1d_hack,
4079        )?;
4080
4081        // Separate the coordinate from the value to write and write the expression
4082        // of the value to write.
4083        write!(self.out, ", ")?;
4084        self.write_expr(value, ctx)?;
4085        // End the call to `imageStore` and the statement.
4086        writeln!(self.out, ");")?;
4087
4088        Ok(())
4089    }
4090
4091    /// Helper method to write the `ImageAtomic` statement
4092    fn write_image_atomic(
4093        &mut self,
4094        ctx: &back::FunctionCtx,
4095        image: Handle<crate::Expression>,
4096        coordinate: Handle<crate::Expression>,
4097        array_index: Option<Handle<crate::Expression>>,
4098        fun: crate::AtomicFunction,
4099        value: Handle<crate::Expression>,
4100    ) -> Result<(), Error> {
4101        use crate::ImageDimension as IDim;
4102
4103        // NOTE: openGL requires that `imageAtomic`s have no effects when the texel is invalid
4104        // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20)
4105
4106        // This will only panic if the module is invalid
4107        let dim = match *ctx.resolve_type(image, &self.module.types) {
4108            TypeInner::Image { dim, .. } => dim,
4109            _ => unreachable!(),
4110        };
4111
4112        // Begin our call to `imageAtomic`
4113        let fun_str = fun.to_glsl();
4114        write!(self.out, "imageAtomic{fun_str}(")?;
4115        self.write_expr(image, ctx)?;
4116        // Separate the image argument from the coordinates
4117        write!(self.out, ", ")?;
4118
4119        // openGL es doesn't have 1D images so we need workaround it
4120        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4121        // Write the coordinate vector
4122        self.write_texture_coord(
4123            ctx,
4124            // Get the size of the coordinate vector
4125            self.get_coordinate_vector_size(dim, false),
4126            coordinate,
4127            array_index,
4128            tex_1d_hack,
4129        )?;
4130
4131        // Separate the coordinate from the value to write and write the expression
4132        // of the value to write.
4133        write!(self.out, ", ")?;
4134        self.write_expr(value, ctx)?;
4135        // End the call to `imageAtomic` and the statement.
4136        writeln!(self.out, ");")?;
4137
4138        Ok(())
4139    }
4140
4141    /// Helper method for writing an `ImageLoad` expression.
4142    #[allow(clippy::too_many_arguments)]
4143    fn write_image_load(
4144        &mut self,
4145        handle: Handle<crate::Expression>,
4146        ctx: &back::FunctionCtx,
4147        image: Handle<crate::Expression>,
4148        coordinate: Handle<crate::Expression>,
4149        array_index: Option<Handle<crate::Expression>>,
4150        sample: Option<Handle<crate::Expression>>,
4151        level: Option<Handle<crate::Expression>>,
4152    ) -> Result<(), Error> {
4153        use crate::ImageDimension as IDim;
4154
4155        // `ImageLoad` is a bit complicated.
4156        // There are two functions one for sampled
4157        // images another for storage images, the former uses `texelFetch` and the
4158        // latter uses `imageLoad`.
4159        //
4160        // Furthermore we have `level` which is always `Some` for sampled images
4161        // and `None` for storage images, so we end up with two functions:
4162        // - `texelFetch(image, coordinate, level)` for sampled images
4163        // - `imageLoad(image, coordinate)` for storage images
4164        //
4165        // Finally we also have to consider bounds checking, for storage images
4166        // this is easy since openGL requires that invalid texels always return
4167        // 0, for sampled images we need to either verify that all arguments are
4168        // in bounds (`ReadZeroSkipWrite`) or make them a valid texel (`Restrict`).
4169
4170        // This will only panic if the module is invalid
4171        let (dim, class) = match *ctx.resolve_type(image, &self.module.types) {
4172            TypeInner::Image {
4173                dim,
4174                arrayed: _,
4175                class,
4176            } => (dim, class),
4177            _ => unreachable!(),
4178        };
4179
4180        // Get the name of the function to be used for the load operation
4181        // and the policy to be used with it.
4182        let (fun_name, policy) = match class {
4183            // Sampled images inherit the policy from the user passed policies
4184            crate::ImageClass::Sampled { .. } => ("texelFetch", self.policies.image_load),
4185            crate::ImageClass::Storage { .. } => {
4186                // OpenGL ES 3.1 mentions in Chapter "8.22 Texture Image Loads and Stores" that:
4187                // "Invalid image loads will return a vector where the value of R, G, and B components
4188                // is 0 and the value of the A component is undefined."
4189                //
4190                // OpenGL 4.2 Core mentions in Chapter "3.9.20 Texture Image Loads and Stores" that:
4191                // "Invalid image loads will return zero."
4192                //
4193                // So, we only inject bounds checks for ES
4194                let policy = if self.options.version.is_es() {
4195                    self.policies.image_load
4196                } else {
4197                    proc::BoundsCheckPolicy::Unchecked
4198                };
4199                ("imageLoad", policy)
4200            }
4201            // TODO: Is there even a function for this?
4202            crate::ImageClass::Depth { multi: _ } => {
4203                return Err(Error::Custom(
4204                    "WGSL `textureLoad` from depth textures is not supported in GLSL".to_string(),
4205                ))
4206            }
4207            crate::ImageClass::External => unimplemented!(),
4208        };
4209
4210        // openGL es doesn't have 1D images so we need workaround it
4211        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4212        // Get the size of the coordinate vector
4213        let vector_size = self.get_coordinate_vector_size(dim, array_index.is_some());
4214
4215        if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy {
4216            // To write the bounds checks for `ReadZeroSkipWrite` we will use a
4217            // ternary operator since we are in the middle of an expression and
4218            // need to return a value.
4219            //
4220            // NOTE: glsl does short circuit when evaluating logical
4221            // expressions so we can be sure that after we test a
4222            // condition it will be true for the next ones
4223
4224            // Write parentheses around the ternary operator to prevent problems with
4225            // expressions emitted before or after it having more precedence
4226            write!(self.out, "(",)?;
4227
4228            // The lod check needs to precede the size check since we need
4229            // to use the lod to get the size of the image at that level.
4230            if let Some(level_expr) = level {
4231                self.write_expr(level_expr, ctx)?;
4232                write!(self.out, " < textureQueryLevels(",)?;
4233                self.write_expr(image, ctx)?;
4234                // Chain the next check
4235                write!(self.out, ") && ")?;
4236            }
4237
4238            // Check that the sample arguments doesn't exceed the number of samples
4239            if let Some(sample_expr) = sample {
4240                self.write_expr(sample_expr, ctx)?;
4241                write!(self.out, " < textureSamples(",)?;
4242                self.write_expr(image, ctx)?;
4243                // Chain the next check
4244                write!(self.out, ") && ")?;
4245            }
4246
4247            // We now need to write the size checks for the coordinates and array index
4248            // first we write the comparison function in case the image is 1D non arrayed
4249            // (and no 1D to 2D hack was needed) we are comparing scalars so the less than
4250            // operator will suffice, but otherwise we'll be comparing two vectors so we'll
4251            // need to use the `lessThan` function but it returns a vector of booleans (one
4252            // for each comparison) so we need to fold it all in one scalar boolean, since
4253            // we want all comparisons to pass we use the `all` function which will only
4254            // return `true` if all the elements of the boolean vector are also `true`.
4255            //
4256            // So we'll end with one of the following forms
4257            // - `coord < textureSize(image, lod)` for 1D images
4258            // - `all(lessThan(coord, textureSize(image, lod)))` for normal images
4259            // - `all(lessThan(ivec(coord, array_index), textureSize(image, lod)))`
4260            //    for arrayed images
4261            // - `all(lessThan(coord, textureSize(image)))` for multi sampled images
4262
4263            if vector_size != 1 {
4264                write!(self.out, "all(lessThan(")?;
4265            }
4266
4267            // Write the coordinate vector
4268            self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?;
4269
4270            if vector_size != 1 {
4271                // If we used the `lessThan` function we need to separate the
4272                // coordinates from the image size.
4273                write!(self.out, ", ")?;
4274            } else {
4275                // If we didn't use it (ie. 1D images) we perform the comparison
4276                // using the less than operator.
4277                write!(self.out, " < ")?;
4278            }
4279
4280            // Call `textureSize` to get our image size
4281            write!(self.out, "textureSize(")?;
4282            self.write_expr(image, ctx)?;
4283            // `textureSize` uses the lod as a second argument for mipmapped images
4284            if let Some(level_expr) = level {
4285                // Separate the image from the lod
4286                write!(self.out, ", ")?;
4287                self.write_expr_as_int(level_expr, ctx)?;
4288            }
4289            // Close the `textureSize` call
4290            write!(self.out, ")")?;
4291
4292            if vector_size != 1 {
4293                // Close the `all` and `lessThan` calls
4294                write!(self.out, "))")?;
4295            }
4296
4297            // Finally end the condition part of the ternary operator
4298            write!(self.out, " ? ")?;
4299        }
4300
4301        // Begin the call to the function used to load the texel
4302        write!(self.out, "{fun_name}(")?;
4303        self.write_expr(image, ctx)?;
4304        write!(self.out, ", ")?;
4305
4306        // If we are using `Restrict` bounds checking we need to pass valid texel
4307        // coordinates, to do so we use the `clamp` function to get a value between
4308        // 0 and the image size - 1 (indexing begins at 0)
4309        if let proc::BoundsCheckPolicy::Restrict = policy {
4310            write!(self.out, "clamp(")?;
4311        }
4312
4313        // Write the coordinate vector
4314        self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?;
4315
4316        // If we are using `Restrict` bounds checking we need to write the rest of the
4317        // clamp we initiated before writing the coordinates.
4318        if let proc::BoundsCheckPolicy::Restrict = policy {
4319            // Write the min value 0
4320            if vector_size == 1 {
4321                write!(self.out, ", 0")?;
4322            } else {
4323                write!(self.out, ", ivec{vector_size}(0)")?;
4324            }
4325            // Start the `textureSize` call to use as the max value.
4326            write!(self.out, ", textureSize(")?;
4327            self.write_expr(image, ctx)?;
4328            // If the image is mipmapped we need to add the lod argument to the
4329            // `textureSize` call, but this needs to be the clamped lod, this should
4330            // have been generated earlier and put in a local.
4331            if class.is_mipmapped() {
4332                write!(self.out, ", {}{}", Baked(handle), CLAMPED_LOD_SUFFIX)?;
4333            }
4334            // Close the `textureSize` call
4335            write!(self.out, ")")?;
4336
4337            // Subtract 1 from the `textureSize` call since the coordinates are zero based.
4338            if vector_size == 1 {
4339                write!(self.out, " - 1")?;
4340            } else {
4341                write!(self.out, " - ivec{vector_size}(1)")?;
4342            }
4343
4344            // Close the `clamp` call
4345            write!(self.out, ")")?;
4346
4347            // Add the clamped lod (if present) as the second argument to the
4348            // image load function.
4349            if level.is_some() {
4350                write!(self.out, ", {}{}", Baked(handle), CLAMPED_LOD_SUFFIX)?;
4351            }
4352
4353            // If a sample argument is needed we need to clamp it between 0 and
4354            // the number of samples the image has.
4355            if let Some(sample_expr) = sample {
4356                write!(self.out, ", clamp(")?;
4357                self.write_expr_as_int(sample_expr, ctx)?;
4358                // Set the min value to 0 and start the call to `textureSamples`
4359                write!(self.out, ", 0, textureSamples(")?;
4360                self.write_expr(image, ctx)?;
4361                // Close the `textureSamples` call, subtract 1 from it since the sample
4362                // argument is zero based, and close the `clamp` call
4363                writeln!(self.out, ") - 1)")?;
4364            }
4365        } else if let Some(sample_or_level) = sample.or(level) {
4366            // If no bounds checking is need just add the sample or level argument
4367            // after the coordinates
4368            write!(self.out, ", ")?;
4369            self.write_expr_as_int(sample_or_level, ctx)?;
4370        }
4371
4372        // Close the image load function.
4373        write!(self.out, ")")?;
4374
4375        // If we were using the `ReadZeroSkipWrite` policy we need to end the first branch
4376        // (which is taken if the condition is `true`) with a colon (`:`) and write the
4377        // second branch which is just a 0 value.
4378        if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy {
4379            // Get the kind of the output value.
4380            let kind = match class {
4381                // Only sampled images can reach here since storage images
4382                // don't need bounds checks and depth images aren't implemented
4383                crate::ImageClass::Sampled { kind, .. } => kind,
4384                _ => unreachable!(),
4385            };
4386
4387            // End the first branch
4388            write!(self.out, " : ")?;
4389            // Write the 0 value
4390            write!(
4391                self.out,
4392                "{}vec4(",
4393                glsl_scalar(crate::Scalar { kind, width: 4 })?.prefix,
4394            )?;
4395            self.write_zero_init_scalar(kind)?;
4396            // Close the zero value constructor
4397            write!(self.out, ")")?;
4398            // Close the parentheses surrounding our ternary
4399            write!(self.out, ")")?;
4400        }
4401
4402        Ok(())
4403    }
4404
4405    fn write_named_expr(
4406        &mut self,
4407        handle: Handle<crate::Expression>,
4408        name: String,
4409        // The expression which is being named.
4410        // Generally, this is the same as handle, except in WorkGroupUniformLoad
4411        named: Handle<crate::Expression>,
4412        ctx: &back::FunctionCtx,
4413    ) -> BackendResult {
4414        match ctx.info[named].ty {
4415            proc::TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner {
4416                TypeInner::Struct { .. } => {
4417                    let ty_name = &self.names[&NameKey::Type(ty_handle)];
4418                    write!(self.out, "{ty_name}")?;
4419                }
4420                _ => {
4421                    self.write_type(ty_handle)?;
4422                }
4423            },
4424            proc::TypeResolution::Value(ref inner) => {
4425                self.write_value_type(inner)?;
4426            }
4427        }
4428
4429        let resolved = ctx.resolve_type(named, &self.module.types);
4430
4431        write!(self.out, " {name}")?;
4432        if let TypeInner::Array { base, size, .. } = *resolved {
4433            self.write_array_size(base, size)?;
4434        }
4435        write!(self.out, " = ")?;
4436        self.write_expr(handle, ctx)?;
4437        writeln!(self.out, ";")?;
4438        self.named_expressions.insert(named, name);
4439
4440        Ok(())
4441    }
4442
4443    /// Helper function that write string with default zero initialization for supported types
4444    fn write_zero_init_value(&mut self, ty: Handle<crate::Type>) -> BackendResult {
4445        let inner = &self.module.types[ty].inner;
4446        match *inner {
4447            TypeInner::Scalar(scalar) | TypeInner::Atomic(scalar) => {
4448                self.write_zero_init_scalar(scalar.kind)?;
4449            }
4450            TypeInner::Vector { scalar, .. } => {
4451                self.write_value_type(inner)?;
4452                write!(self.out, "(")?;
4453                self.write_zero_init_scalar(scalar.kind)?;
4454                write!(self.out, ")")?;
4455            }
4456            TypeInner::Matrix { .. } => {
4457                self.write_value_type(inner)?;
4458                write!(self.out, "(")?;
4459                self.write_zero_init_scalar(crate::ScalarKind::Float)?;
4460                write!(self.out, ")")?;
4461            }
4462            TypeInner::Array { base, size, .. } => {
4463                let count = match size.resolve(self.module.to_ctx())? {
4464                    proc::IndexableLength::Known(count) => count,
4465                    proc::IndexableLength::Dynamic => return Ok(()),
4466                };
4467                self.write_type(base)?;
4468                self.write_array_size(base, size)?;
4469                write!(self.out, "(")?;
4470                for _ in 1..count {
4471                    self.write_zero_init_value(base)?;
4472                    write!(self.out, ", ")?;
4473                }
4474                // write last parameter without comma and space
4475                self.write_zero_init_value(base)?;
4476                write!(self.out, ")")?;
4477            }
4478            TypeInner::Struct { ref members, .. } => {
4479                let name = &self.names[&NameKey::Type(ty)];
4480                write!(self.out, "{name}(")?;
4481                for (index, member) in members.iter().enumerate() {
4482                    if index != 0 {
4483                        write!(self.out, ", ")?;
4484                    }
4485                    self.write_zero_init_value(member.ty)?;
4486                }
4487                write!(self.out, ")")?;
4488            }
4489            _ => unreachable!(),
4490        }
4491
4492        Ok(())
4493    }
4494
4495    /// Helper function that write string with zero initialization for scalar
4496    fn write_zero_init_scalar(&mut self, kind: crate::ScalarKind) -> BackendResult {
4497        match kind {
4498            crate::ScalarKind::Bool => write!(self.out, "false")?,
4499            crate::ScalarKind::Uint => write!(self.out, "0u")?,
4500            crate::ScalarKind::Float => write!(self.out, "0.0")?,
4501            crate::ScalarKind::Sint => write!(self.out, "0")?,
4502            crate::ScalarKind::AbstractInt | crate::ScalarKind::AbstractFloat => {
4503                return Err(Error::Custom(
4504                    "Abstract types should not appear in IR presented to backends".to_string(),
4505                ))
4506            }
4507        }
4508
4509        Ok(())
4510    }
4511
4512    /// Issue a control barrier.
4513    fn write_control_barrier(
4514        &mut self,
4515        flags: crate::Barrier,
4516        level: back::Level,
4517    ) -> BackendResult {
4518        self.write_memory_barrier(flags, level)?;
4519        writeln!(self.out, "{level}barrier();")?;
4520        Ok(())
4521    }
4522
4523    /// Issue a memory barrier.
4524    fn write_memory_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult {
4525        if flags.contains(crate::Barrier::STORAGE) {
4526            writeln!(self.out, "{level}memoryBarrierBuffer();")?;
4527        }
4528        if flags.contains(crate::Barrier::WORK_GROUP) {
4529            writeln!(self.out, "{level}memoryBarrierShared();")?;
4530        }
4531        if flags.contains(crate::Barrier::SUB_GROUP) {
4532            writeln!(self.out, "{level}subgroupMemoryBarrier();")?;
4533        }
4534        if flags.contains(crate::Barrier::TEXTURE) {
4535            writeln!(self.out, "{level}memoryBarrierImage();")?;
4536        }
4537        Ok(())
4538    }
4539
4540    /// Helper function that return the glsl storage access string of [`StorageAccess`](crate::StorageAccess)
4541    ///
4542    /// glsl allows adding both `readonly` and `writeonly` but this means that
4543    /// they can only be used to query information about the resource which isn't what
4544    /// we want here so when storage access is both `LOAD` and `STORE` add no modifiers
4545    fn write_storage_access(&mut self, storage_access: crate::StorageAccess) -> BackendResult {
4546        if storage_access.contains(crate::StorageAccess::ATOMIC) {
4547            return Ok(());
4548        }
4549        if !storage_access.contains(crate::StorageAccess::STORE) {
4550            write!(self.out, "readonly ")?;
4551        }
4552        if !storage_access.contains(crate::StorageAccess::LOAD) {
4553            write!(self.out, "writeonly ")?;
4554        }
4555        Ok(())
4556    }
4557
4558    /// Helper method used to produce the reflection info that's returned to the user
4559    fn collect_reflection_info(&mut self) -> Result<ReflectionInfo, Error> {
4560        let info = self.info.get_entry_point(self.entry_point_idx as usize);
4561        let mut texture_mapping = crate::FastHashMap::default();
4562        let mut uniforms = crate::FastHashMap::default();
4563
4564        for sampling in info.sampling_set.iter() {
4565            let tex_name = self.reflection_names_globals[&sampling.image].clone();
4566
4567            match texture_mapping.entry(tex_name) {
4568                hash_map::Entry::Vacant(v) => {
4569                    v.insert(TextureMapping {
4570                        texture: sampling.image,
4571                        sampler: Some(sampling.sampler),
4572                    });
4573                }
4574                hash_map::Entry::Occupied(e) => {
4575                    if e.get().sampler != Some(sampling.sampler) {
4576                        log::error!("Conflicting samplers for {}", e.key());
4577                        return Err(Error::ImageMultipleSamplers);
4578                    }
4579                }
4580            }
4581        }
4582
4583        let mut immediates_info = None;
4584        for (handle, var) in self.module.global_variables.iter() {
4585            if info[handle].is_empty() {
4586                continue;
4587            }
4588            match self.module.types[var.ty].inner {
4589                TypeInner::Image { .. } => {
4590                    let tex_name = self.reflection_names_globals[&handle].clone();
4591                    match texture_mapping.entry(tex_name) {
4592                        hash_map::Entry::Vacant(v) => {
4593                            v.insert(TextureMapping {
4594                                texture: handle,
4595                                sampler: None,
4596                            });
4597                        }
4598                        hash_map::Entry::Occupied(_) => {
4599                            // already used with a sampler, do nothing
4600                        }
4601                    }
4602                }
4603                _ => match var.space {
4604                    crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => {
4605                        let name = self.reflection_names_globals[&handle].clone();
4606                        uniforms.insert(handle, name);
4607                    }
4608                    crate::AddressSpace::Immediate => {
4609                        let name = self.reflection_names_globals[&handle].clone();
4610                        immediates_info = Some((name, var.ty));
4611                    }
4612                    _ => (),
4613                },
4614            }
4615        }
4616
4617        let mut immediates_segments = Vec::new();
4618        let mut immediates_items = vec![];
4619
4620        if let Some((name, ty)) = immediates_info {
4621            // We don't have a layouter available to us, so we need to create one.
4622            //
4623            // This is potentially a bit wasteful, but the set of types in the program
4624            // shouldn't be too large.
4625            let mut layouter = proc::Layouter::default();
4626            layouter.update(self.module.to_ctx()).unwrap();
4627
4628            // We start with the name of the binding itself.
4629            immediates_segments.push(name);
4630
4631            // We then recursively collect all the uniform fields of the immediate data.
4632            self.collect_immediates_items(
4633                ty,
4634                &mut immediates_segments,
4635                &layouter,
4636                &mut 0,
4637                &mut immediates_items,
4638            );
4639        }
4640
4641        Ok(ReflectionInfo {
4642            texture_mapping,
4643            uniforms,
4644            varying: mem::take(&mut self.varying),
4645            immediates_items,
4646            clip_distance_count: self.clip_distance_count,
4647        })
4648    }
4649
4650    fn collect_immediates_items(
4651        &mut self,
4652        ty: Handle<crate::Type>,
4653        segments: &mut Vec<String>,
4654        layouter: &proc::Layouter,
4655        offset: &mut u32,
4656        items: &mut Vec<ImmediateItem>,
4657    ) {
4658        // At this point in the recursion, `segments` contains the path
4659        // needed to access `ty` from the root.
4660
4661        let layout = &layouter[ty];
4662        *offset = layout.alignment.round_up(*offset);
4663        match self.module.types[ty].inner {
4664            // All these types map directly to GL uniforms.
4665            TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => {
4666                // Build the full name, by combining all current segments.
4667                let name: String = segments.iter().map(String::as_str).collect();
4668                items.push(ImmediateItem {
4669                    access_path: name,
4670                    offset: *offset,
4671                    ty: (&self.module.types[ty].inner).try_into().unwrap(),
4672                    size_bytes: layout.size,
4673                });
4674                *offset += layout.size;
4675            }
4676            // Arrays are recursed into.
4677            TypeInner::Array { base, size, .. } => {
4678                let crate::ArraySize::Constant(count) = size else {
4679                    unreachable!("Cannot have dynamic arrays in immediates");
4680                };
4681
4682                for i in 0..count.get() {
4683                    // Add the array accessor and recurse.
4684                    segments.push(format!("[{i}]"));
4685                    self.collect_immediates_items(base, segments, layouter, offset, items);
4686                    segments.pop();
4687                }
4688
4689                // Ensure the stride is kept by rounding up to the alignment.
4690                *offset = layout.alignment.round_up(*offset)
4691            }
4692            TypeInner::Struct { ref members, .. } => {
4693                for (index, member) in members.iter().enumerate() {
4694                    // Add struct accessor and recurse.
4695                    segments.push(format!(
4696                        ".{}",
4697                        self.names[&NameKey::StructMember(ty, index as u32)]
4698                    ));
4699                    self.collect_immediates_items(member.ty, segments, layouter, offset, items);
4700                    segments.pop();
4701                }
4702
4703                // Ensure ending padding is kept by rounding up to the alignment.
4704                *offset = layout.alignment.round_up(*offset)
4705            }
4706            _ => unreachable!(),
4707        }
4708    }
4709}