Debian Codegraph @

third_party/rust/naga/src/back/wgsl/writer.rs

raw
1 use alloc::{
2 format,
3 string::{String, ToString},
4 vec,
5 vec::Vec,
6 };
7 use core::fmt::Write;
8 use hashbrown::HashSet;
9
10 use super::Error;
11 use super::ToWgslIfImplemented as _;
12 use crate::{back::wgsl::polyfill::InversePolyfill, common::wgsl::TypeContext};
13 use crate::{
14 back::{self, Baked},
15 common::{
16 self,
17 wgsl::{address_space_str, ToWgsl, TryToWgsl},
18 },
19 proc::{self, NameKey},
20 valid, Handle, Module, ShaderStage, TypeInner,
21 };
22
23 /// Shorthand result used internally by the backend
24 type BackendResult = Result<(), Error>;
25
26 /// WGSL [attribute](https://gpuweb.github.io/gpuweb/wgsl/#attributes)
27 enum Attribute {
28 Binding(u32),
29 BuiltIn(crate::BuiltIn),
30 Group(u32),
31 Invariant,
32 Interpolate(Option<crate::Interpolation>, Option<crate::Sampling>),
33 Location(u32),
34 BlendSrc(u32),
35 Stage(ShaderStage),
36 WorkGroupSize([u32; 3]),
37 }
38
39 /// The WGSL form that `write_expr_with_indirection` should use to render a Naga
40 /// expression.
41 ///
42 /// Sometimes a Naga `Expression` alone doesn't provide enough information to
43 /// choose the right rendering for it in WGSL. For example, one natural WGSL
44 /// rendering of a Naga `LocalVariable(x)` expression might be `&x`, since
45 /// `LocalVariable` produces a pointer to the local variable's storage. But when
46 /// rendering a `Store` statement, the `pointer` operand must be the left hand
47 /// side of a WGSL assignment, so the proper rendering is `x`.
48 ///
49 /// The caller of `write_expr_with_indirection` must provide an `Expected` value
50 /// to indicate how ambiguous expressions should be rendered.
51 #[derive(Clone, Copy, Debug)]
52 enum Indirection {
53 /// Render pointer-construction expressions as WGSL `ptr`-typed expressions.
54 ///
55 /// This is the right choice for most cases. Whenever a Naga pointer
56 /// expression is not the `pointer` operand of a `Load` or `Store`, it
57 /// must be a WGSL pointer expression.
58 Ordinary,
59
60 /// Render pointer-construction expressions as WGSL reference-typed
61 /// expressions.
62 ///
63 /// For example, this is the right choice for the `pointer` operand when
64 /// rendering a `Store` statement as a WGSL assignment.
65 Reference,
66 }
67
68 bitflags::bitflags! {
69 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
70 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
71 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
72 pub struct WriterFlags: u32 {
73 /// Always annotate the type information instead of inferring.
74 const EXPLICIT_TYPES = 0x1;
75 }
76 }
77
78 pub struct Writer<W> {
79 out: W,
80 flags: WriterFlags,
81 names: crate::FastHashMap<NameKey, String>,
82 namer: proc::Namer,
83 named_expressions: crate::NamedExpressions,
84 required_polyfills: crate::FastIndexSet<InversePolyfill>,
85 }
86
87 impl<W: Write> Writer<W> {
88 pub fn new(out: W, flags: WriterFlags) -> Self {
89 Writer {
90 out,
91 flags,
92 names: crate::FastHashMap::default(),
93 namer: proc::Namer::default(),
94 named_expressions: crate::NamedExpressions::default(),
95 required_polyfills: crate::FastIndexSet::default(),
96 }
97 }
98
99 fn reset(&mut self, module: &Module) {
100 self.names.clear();
101 self.namer.reset(
102 module,
103 &crate::keywords::wgsl::RESERVED_SET,
104 // an identifier must not start with two underscore
105 &[],
106 &["__", "_naga"],
107 &mut self.names,
108 );
109 self.named_expressions.clear();
110 self.required_polyfills.clear();
111 }
112
113 fn is_builtin_wgsl_struct(&self, module: &Module, handle: Handle<crate::Type>) -> bool {
114 module
115 .special_types
116 .predeclared_types
117 .values()
118 .any(|t| *t == handle)
119 }
120
121 pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult {
122 if !module.overrides.is_empty() {
123 return Err(Error::Unimplemented(
124 "Pipeline constants are not yet supported for this back-end".to_string(),
125 ));
126 }
127
128 self.reset(module);
129
130 // Write all needed directives.
131 self.write_enable_dual_source_blending_if_needed(module)?;
132
133 // Write all `enable` declarations
134 self.write_enable_declarations(module)?;
135
136 // Write all structs
137 for (handle, ty) in module.types.iter() {
138 if let TypeInner::Struct { ref members, .. } = ty.inner {
139 {
140 if !self.is_builtin_wgsl_struct(module, handle) {
141 self.write_struct(module, handle, members)?;
142 writeln!(self.out)?;
143 }
144 }
145 }
146 }
147
148 // Write all named constants
149 let mut constants = module
150 .constants
151 .iter()
152 .filter(|&(_, c)| c.name.is_some())
153 .peekable();
154 while let Some((handle, _)) = constants.next() {
155 self.write_global_constant(module, handle)?;
156 // Add extra newline for readability on last iteration
157 if constants.peek().is_none() {
158 writeln!(self.out)?;
159 }
160 }
161
162 // Write all globals
163 for (ty, global) in module.global_variables.iter() {
164 self.write_global(module, global, ty)?;
165 }
166
167 if !module.global_variables.is_empty() {
168 // Add extra newline for readability
169 writeln!(self.out)?;
170 }
171
172 // Write all regular functions
173 for (handle, function) in module.functions.iter() {
174 let fun_info = &info[handle];
175
176 let func_ctx = back::FunctionCtx {
177 ty: back::FunctionType::Function(handle),
178 info: fun_info,
179 expressions: &function.expressions,
180 named_expressions: &function.named_expressions,
181 };
182
183 // Write the function
184 self.write_function(module, function, &func_ctx)?;
185
186 writeln!(self.out)?;
187 }
188
189 // Write all entry points
190 for (index, ep) in module.entry_points.iter().enumerate() {
191 let attributes = match ep.stage {
192 ShaderStage::Vertex | ShaderStage::Fragment => vec![Attribute::Stage(ep.stage)],
193 ShaderStage::Compute => vec![
194 Attribute::Stage(ShaderStage::Compute),
195 Attribute::WorkGroupSize(ep.workgroup_size),
196 ],
197 ShaderStage::Task | ShaderStage::Mesh => unreachable!(),
198 };
199
200 self.write_attributes(&attributes)?;
201 // Add a newline after attribute
202 writeln!(self.out)?;
203
204 let func_ctx = back::FunctionCtx {
205 ty: back::FunctionType::EntryPoint(index as u16),
206 info: info.get_entry_point(index),
207 expressions: &ep.function.expressions,
208 named_expressions: &ep.function.named_expressions,
209 };
210 self.write_function(module, &ep.function, &func_ctx)?;
211
212 if index < module.entry_points.len() - 1 {
213 writeln!(self.out)?;
214 }
215 }
216
217 // Write any polyfills that were required.
218 for polyfill in &self.required_polyfills {
219 writeln!(self.out)?;
220 write!(self.out, "{}", polyfill.source)?;
221 writeln!(self.out)?;
222 }
223
224 Ok(())
225 }
226
227 /// Helper method which writes all the `enable` declarations
228 /// needed for a module.
229 fn write_enable_declarations(&mut self, module: &Module) -> BackendResult {
230 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231 enum WrittenDeclarations {
232 F16,
233 }
234
235 let mut written_declarations = HashSet::new();
236
237 // Write all the `enable` declarations
238 for (_, ty) in module.types.iter() {
239 match ty.inner {
240 TypeInner::Scalar(scalar)
241 | TypeInner::Vector { scalar, .. }
242 | TypeInner::Matrix { scalar, .. } => {
243 if scalar == crate::Scalar::F16
244 && !written_declarations.contains(&WrittenDeclarations::F16)
245 {
246 writeln!(self.out, "enable f16;")?;
247 written_declarations.insert(WrittenDeclarations::F16);
248 }
249 }
250 _ => {}
251 }
252 }
253
254 if !written_declarations.is_empty() {
255 // Empty line for readability
256 writeln!(self.out)?;
257 }
258
259 Ok(())
260 }
261
262 /// Helper method used to write
263 /// [functions](https://gpuweb.github.io/gpuweb/wgsl/#functions)
264 ///
265 /// # Notes
266 /// Ends in a newline
267 fn write_function(
268 &mut self,
269 module: &Module,
270 func: &crate::Function,
271 func_ctx: &back::FunctionCtx<'_>,
272 ) -> BackendResult {
273 let func_name = match func_ctx.ty {
274 back::FunctionType::EntryPoint(index) => &self.names[&NameKey::EntryPoint(index)],
275 back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)],
276 };
277
278 // Write function name
279 write!(self.out, "fn {func_name}(")?;
280
281 // Write function arguments
282 for (index, arg) in func.arguments.iter().enumerate() {
283 // Write argument attribute if a binding is present
284 if let Some(ref binding) = arg.binding {
285 self.write_attributes(&map_binding_to_attribute(binding))?;
286 }
287 // Write argument name
288 let argument_name = &self.names[&func_ctx.argument_key(index as u32)];
289
290 write!(self.out, "{argument_name}: ")?;
291 // Write argument type
292 self.write_type(module, arg.ty)?;
293 if index < func.arguments.len() - 1 {
294 // Add a separator between args
295 write!(self.out, ", ")?;
296 }
297 }
298
299 write!(self.out, ")")?;
300
301 // Write function return type
302 if let Some(ref result) = func.result {
303 write!(self.out, " -> ")?;
304 if let Some(ref binding) = result.binding {
305 self.write_attributes(&map_binding_to_attribute(binding))?;
306 }
307 self.write_type(module, result.ty)?;
308 }
309
310 write!(self.out, " {{")?;
311 writeln!(self.out)?;
312
313 // Write function local variables
314 for (handle, local) in func.local_variables.iter() {
315 // Write indentation (only for readability)
316 write!(self.out, "{}", back::INDENT)?;
317
318 // Write the local name
319 // The leading space is important
320 write!(self.out, "var {}: ", self.names[&func_ctx.name_key(handle)])?;
321
322 // Write the local type
323 self.write_type(module, local.ty)?;
324
325 // Write the local initializer if needed
326 if let Some(init) = local.init {
327 // Put the equal signal only if there's a initializer
328 // The leading and trailing spaces aren't needed but help with readability
329 write!(self.out, " = ")?;
330
331 // Write the constant
332 // `write_constant` adds no trailing or leading space/newline
333 self.write_expr(module, init, func_ctx)?;
334 }
335
336 // Finish the local with `;` and add a newline (only for readability)
337 writeln!(self.out, ";")?
338 }
339
340 if !func.local_variables.is_empty() {
341 writeln!(self.out)?;
342 }
343
344 // Write the function body (statement list)
345 for sta in func.body.iter() {
346 // The indentation should always be 1 when writing the function body
347 self.write_stmt(module, sta, func_ctx, back::Level(1))?;
348 }
349
350 writeln!(self.out, "}}")?;
351
352 self.named_expressions.clear();
353
354 Ok(())
355 }
356
357 /// Helper method to write a attribute
358 fn write_attributes(&mut self, attributes: &[Attribute]) -> BackendResult {
359 for attribute in attributes {
360 match *attribute {
361 Attribute::Location(id) => write!(self.out, "@location({id}) ")?,
362 Attribute::BlendSrc(blend_src) => write!(self.out, "@blend_src({blend_src}) ")?,
363 Attribute::BuiltIn(builtin_attrib) => {
364 let builtin = builtin_attrib.to_wgsl_if_implemented()?;
365 write!(self.out, "@builtin({builtin}) ")?;
366 }
367 Attribute::Stage(shader_stage) => {
368 let stage_str = match shader_stage {
369 ShaderStage::Vertex => "vertex",
370 ShaderStage::Fragment => "fragment",
371 ShaderStage::Compute => "compute",
372 ShaderStage::Task | ShaderStage::Mesh => unreachable!(),
373 };
374 write!(self.out, "@{stage_str} ")?;
375 }
376 Attribute::WorkGroupSize(size) => {
377 write!(
378 self.out,
379 "@workgroup_size({}, {}, {}) ",
380 size[0], size[1], size[2]
381 )?;
382 }
383 Attribute::Binding(id) => write!(self.out, "@binding({id}) ")?,
384 Attribute::Group(id) => write!(self.out, "@group({id}) ")?,
385 Attribute::Invariant => write!(self.out, "@invariant ")?,
386 Attribute::Interpolate(interpolation, sampling) => {
387 if sampling.is_some() && sampling != Some(crate::Sampling::Center) {
388 let interpolation = interpolation
389 .unwrap_or(crate::Interpolation::Perspective)
390 .to_wgsl();
391 let sampling = sampling.unwrap_or(crate::Sampling::Center).to_wgsl();
392 write!(self.out, "@interpolate({interpolation}, {sampling}) ")?;
393 } else if interpolation.is_some()
394 && interpolation != Some(crate::Interpolation::Perspective)
395 {
396 let interpolation = interpolation
397 .unwrap_or(crate::Interpolation::Perspective)
398 .to_wgsl();
399 write!(self.out, "@interpolate({interpolation}) ")?;
400 }
401 }
402 };
403 }
404 Ok(())
405 }
406
407 /// Writes all the necessary directives out
408 fn write_enable_dual_source_blending_if_needed(&mut self, module: &Module) -> BackendResult {
409 // Check for dual source blending.
410 if module.types.iter().any(|(_handle, ty)| {
411 if let TypeInner::Struct { ref members, .. } = ty.inner {
412 members.iter().any(|member| {
413 member.binding.as_ref().is_some_and(|binding| {
414 matches!(
415 binding,
416 &crate::Binding::Location {
417 blend_src: Some(_),
418 ..
419 }
420 )
421 })
422 })
423 } else {
424 false
425 }
426 }) {
427 writeln!(self.out, "enable dual_source_blending;")?;
428 }
429
430 Ok(())
431 }
432
433 /// Helper method used to write structs
434 /// Write the full declaration of a struct type.
435 ///
436 /// Write out a definition of the struct type referred to by
437 /// `handle` in `module`. The output will be an instance of the
438 /// `struct_decl` production in the WGSL grammar.
439 ///
440 /// Use `members` as the list of `handle`'s members. (This
441 /// function is usually called after matching a `TypeInner`, so
442 /// the callers already have the members at hand.)
443 fn write_struct(
444 &mut self,
445 module: &Module,
446 handle: Handle<crate::Type>,
447 members: &[crate::StructMember],
448 ) -> BackendResult {
449 write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?;
450 write!(self.out, " {{")?;
451 writeln!(self.out)?;
452 for (index, member) in members.iter().enumerate() {
453 // The indentation is only for readability
454 write!(self.out, "{}", back::INDENT)?;
455 if let Some(ref binding) = member.binding {
456 self.write_attributes(&map_binding_to_attribute(binding))?;
457 }
458 // Write struct member name and type
459 let member_name = &self.names[&NameKey::StructMember(handle, index as u32)];
460 write!(self.out, "{member_name}: ")?;
461 self.write_type(module, member.ty)?;
462 write!(self.out, ",")?;
463 writeln!(self.out)?;
464 }
465
466 writeln!(self.out, "}}")?;
467
468 Ok(())
469 }
470
471 fn write_type(&mut self, module: &Module, ty: Handle<crate::Type>) -> BackendResult {
472 // This actually can't be factored out into a nice constructor method,
473 // because the borrow checker needs to be able to see that the borrows
474 // of `self.names` and `self.out` are disjoint.
475 let type_context = WriterTypeContext {
476 module,
477 names: &self.names,
478 };
479 type_context.write_type(ty, &mut self.out)?;
480
481 Ok(())
482 }
483
484 fn write_type_resolution(
485 &mut self,
486 module: &Module,
487 resolution: &proc::TypeResolution,
488 ) -> BackendResult {
489 // This actually can't be factored out into a nice constructor method,
490 // because the borrow checker needs to be able to see that the borrows
491 // of `self.names` and `self.out` are disjoint.
492 let type_context = WriterTypeContext {
493 module,
494 names: &self.names,
495 };
496 type_context.write_type_resolution(resolution, &mut self.out)?;
497
498 Ok(())
499 }
500
501 /// Helper method used to write statements
502 ///
503 /// # Notes
504 /// Always adds a newline
505 fn write_stmt(
506 &mut self,
507 module: &Module,
508 stmt: &crate::Statement,
509 func_ctx: &back::FunctionCtx<'_>,
510 level: back::Level,
511 ) -> BackendResult {
512 use crate::{Expression, Statement};
513
514 match *stmt {
515 Statement::Emit(ref range) => {
516 for handle in range.clone() {
517 let info = &func_ctx.info[handle];
518 let expr_name = if let Some(name) = func_ctx.named_expressions.get(&handle) {
519 // Front end provides names for all variables at the start of writing.
520 // But we write them to step by step. We need to recache them
521 // Otherwise, we could accidentally write variable name instead of full expression.
522 // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords.
523 Some(self.namer.call(name))
524 } else {
525 let expr = &func_ctx.expressions[handle];
526 let min_ref_count = expr.bake_ref_count();
527 // Forcefully creating baking expressions in some cases to help with readability
528 let required_baking_expr = match *expr {
529 Expression::ImageLoad { .. }
530 | Expression::ImageQuery { .. }
531 | Expression::ImageSample { .. } => true,
532 _ => false,
533 };
534 if min_ref_count <= info.ref_count || required_baking_expr {
535 Some(Baked(handle).to_string())
536 } else {
537 None
538 }
539 };
540
541 if let Some(name) = expr_name {
542 write!(self.out, "{level}")?;
543 self.start_named_expr(module, handle, func_ctx, &name)?;
544 self.write_expr(module, handle, func_ctx)?;
545 self.named_expressions.insert(handle, name);
546 writeln!(self.out, ";")?;
547 }
548 }
549 }
550 // TODO: copy-paste from glsl-out
551 Statement::If {
552 condition,
553 ref accept,
554 ref reject,
555 } => {
556 write!(self.out, "{level}")?;
557 write!(self.out, "if ")?;
558 self.write_expr(module, condition, func_ctx)?;
559 writeln!(self.out, " {{")?;
560
561 let l2 = level.next();
562 for sta in accept {
563 // Increase indentation to help with readability
564 self.write_stmt(module, sta, func_ctx, l2)?;
565 }
566
567 // If there are no statements in the reject block we skip writing it
568 // This is only for readability
569 if !reject.is_empty() {
570 writeln!(self.out, "{level}}} else {{")?;
571
572 for sta in reject {
573 // Increase indentation to help with readability
574 self.write_stmt(module, sta, func_ctx, l2)?;
575 }
576 }
577
578 writeln!(self.out, "{level}}}")?
579 }
580 Statement::Return { value } => {
581 write!(self.out, "{level}")?;
582 write!(self.out, "return")?;
583 if let Some(return_value) = value {
584 // The leading space is important
585 write!(self.out, " ")?;
586 self.write_expr(module, return_value, func_ctx)?;
587 }
588 writeln!(self.out, ";")?;
589 }
590 // TODO: copy-paste from glsl-out
591 Statement::Kill => {
592 write!(self.out, "{level}")?;
593 writeln!(self.out, "discard;")?
594 }
595 Statement::Store { pointer, value } => {
596 write!(self.out, "{level}")?;
597
598 let is_atomic_pointer = func_ctx
599 .resolve_type(pointer, &module.types)
600 .is_atomic_pointer(&module.types);
601
602 if is_atomic_pointer {
603 write!(self.out, "atomicStore(")?;
604 self.write_expr(module, pointer, func_ctx)?;
605 write!(self.out, ", ")?;
606 self.write_expr(module, value, func_ctx)?;
607 write!(self.out, ")")?;
608 } else {
609 self.write_expr_with_indirection(
610 module,
611 pointer,
612 func_ctx,
613 Indirection::Reference,
614 )?;
615 write!(self.out, " = ")?;
616 self.write_expr(module, value, func_ctx)?;
617 }
618 writeln!(self.out, ";")?
619 }
620 Statement::Call {
621 function,
622 ref arguments,
623 result,
624 } => {
625 write!(self.out, "{level}")?;
626 if let Some(expr) = result {
627 let name = Baked(expr).to_string();
628 self.start_named_expr(module, expr, func_ctx, &name)?;
629 self.named_expressions.insert(expr, name);
630 }
631 let func_name = &self.names[&NameKey::Function(function)];
632 write!(self.out, "{func_name}(")?;
633 for (index, &argument) in arguments.iter().enumerate() {
634 if index != 0 {
635 write!(self.out, ", ")?;
636 }
637 self.write_expr(module, argument, func_ctx)?;
638 }
639 writeln!(self.out, ");")?
640 }
641 Statement::Atomic {
642 pointer,
643 ref fun,
644 value,
645 result,
646 } => {
647 write!(self.out, "{level}")?;
648 if let Some(result) = result {
649 let res_name = Baked(result).to_string();
650 self.start_named_expr(module, result, func_ctx, &res_name)?;
651 self.named_expressions.insert(result, res_name);
652 }
653
654 let fun_str = fun.to_wgsl();
655 write!(self.out, "atomic{fun_str}(")?;
656 self.write_expr(module, pointer, func_ctx)?;
657 if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
658 write!(self.out, ", ")?;
659 self.write_expr(module, cmp, func_ctx)?;
660 }
661 write!(self.out, ", ")?;
662 self.write_expr(module, value, func_ctx)?;
663 writeln!(self.out, ");")?
664 }
665 Statement::ImageAtomic {
666 image,
667 coordinate,
668 array_index,
669 ref fun,
670 value,
671 } => {
672 write!(self.out, "{level}")?;
673 let fun_str = fun.to_wgsl();
674 write!(self.out, "textureAtomic{fun_str}(")?;
675 self.write_expr(module, image, func_ctx)?;
676 write!(self.out, ", ")?;
677 self.write_expr(module, coordinate, func_ctx)?;
678 if let Some(array_index_expr) = array_index {
679 write!(self.out, ", ")?;
680 self.write_expr(module, array_index_expr, func_ctx)?;
681 }
682 write!(self.out, ", ")?;
683 self.write_expr(module, value, func_ctx)?;
684 writeln!(self.out, ");")?;
685 }
686 Statement::WorkGroupUniformLoad { pointer, result } => {
687 write!(self.out, "{level}")?;
688 // TODO: Obey named expressions here.
689 let res_name = Baked(result).to_string();
690 self.start_named_expr(module, result, func_ctx, &res_name)?;
691 self.named_expressions.insert(result, res_name);
692 write!(self.out, "workgroupUniformLoad(")?;
693 self.write_expr(module, pointer, func_ctx)?;
694 writeln!(self.out, ");")?;
695 }
696 Statement::ImageStore {
697 image,
698 coordinate,
699 array_index,
700 value,
701 } => {
702 write!(self.out, "{level}")?;
703 write!(self.out, "textureStore(")?;
704 self.write_expr(module, image, func_ctx)?;
705 write!(self.out, ", ")?;
706 self.write_expr(module, coordinate, func_ctx)?;
707 if let Some(array_index_expr) = array_index {
708 write!(self.out, ", ")?;
709 self.write_expr(module, array_index_expr, func_ctx)?;
710 }
711 write!(self.out, ", ")?;
712 self.write_expr(module, value, func_ctx)?;
713 writeln!(self.out, ");")?;
714 }
715 // TODO: copy-paste from glsl-out
716 Statement::Block(ref block) => {
717 write!(self.out, "{level}")?;
718 writeln!(self.out, "{{")?;
719 for sta in block.iter() {
720 // Increase the indentation to help with readability
721 self.write_stmt(module, sta, func_ctx, level.next())?
722 }
723 writeln!(self.out, "{level}}}")?
724 }
725 Statement::Switch {
726 selector,
727 ref cases,
728 } => {
729 // Start the switch
730 write!(self.out, "{level}")?;
731 write!(self.out, "switch ")?;
732 self.write_expr(module, selector, func_ctx)?;
733 writeln!(self.out, " {{")?;
734
735 let l2 = level.next();
736 let mut new_case = true;
737 for case in cases {
738 if case.fall_through && !case.body.is_empty() {
739 // TODO: we could do the same workaround as we did for the HLSL backend
740 return Err(Error::Unimplemented(
741 "fall-through switch case block".into(),
742 ));
743 }
744
745 match case.value {
746 crate::SwitchValue::I32(value) => {
747 if new_case {
748 write!(self.out, "{l2}case ")?;
749 }
750 write!(self.out, "{value}")?;
751 }
752 crate::SwitchValue::U32(value) => {
753 if new_case {
754 write!(self.out, "{l2}case ")?;
755 }
756 write!(self.out, "{value}u")?;
757 }
758 crate::SwitchValue::Default => {
759 if new_case {
760 if case.fall_through {
761 write!(self.out, "{l2}case ")?;
762 } else {
763 write!(self.out, "{l2}")?;
764 }
765 }
766 write!(self.out, "default")?;
767 }
768 }
769
770 new_case = !case.fall_through;
771
772 if case.fall_through {
773 write!(self.out, ", ")?;
774 } else {
775 writeln!(self.out, ": {{")?;
776 }
777
778 for sta in case.body.iter() {
779 self.write_stmt(module, sta, func_ctx, l2.next())?;
780 }
781
782 if !case.fall_through {
783 writeln!(self.out, "{l2}}}")?;
784 }
785 }
786
787 writeln!(self.out, "{level}}}")?
788 }
789 Statement::Loop {
790 ref body,
791 ref continuing,
792 break_if,
793 } => {
794 write!(self.out, "{level}")?;
795 writeln!(self.out, "loop {{")?;
796
797 let l2 = level.next();
798 for sta in body.iter() {
799 self.write_stmt(module, sta, func_ctx, l2)?;
800 }
801
802 // The continuing is optional so we don't need to write it if
803 // it is empty, but the `break if` counts as a continuing statement
804 // so even if `continuing` is empty we must generate it if a
805 // `break if` exists
806 if !continuing.is_empty() || break_if.is_some() {
807 writeln!(self.out, "{l2}continuing {{")?;
808 for sta in continuing.iter() {
809 self.write_stmt(module, sta, func_ctx, l2.next())?;
810 }
811
812 // The `break if` is always the last
813 // statement of the `continuing` block
814 if let Some(condition) = break_if {
815 // The trailing space is important
816 write!(self.out, "{}break if ", l2.next())?;
817 self.write_expr(module, condition, func_ctx)?;
818 // Close the `break if` statement
819 writeln!(self.out, ";")?;
820 }
821
822 writeln!(self.out, "{l2}}}")?;
823 }
824
825 writeln!(self.out, "{level}}}")?
826 }
827 Statement::Break => {
828 writeln!(self.out, "{level}break;")?;
829 }
830 Statement::Continue => {
831 writeln!(self.out, "{level}continue;")?;
832 }
833 Statement::Barrier(barrier) => {
834 if barrier.contains(crate::Barrier::STORAGE) {
835 writeln!(self.out, "{level}storageBarrier();")?;
836 }
837
838 if barrier.contains(crate::Barrier::WORK_GROUP) {
839 writeln!(self.out, "{level}workgroupBarrier();")?;
840 }
841
842 if barrier.contains(crate::Barrier::SUB_GROUP) {
843 writeln!(self.out, "{level}subgroupBarrier();")?;
844 }
845
846 if barrier.contains(crate::Barrier::TEXTURE) {
847 writeln!(self.out, "{level}textureBarrier();")?;
848 }
849 }
850 Statement::RayQuery { .. } => unreachable!(),
851 Statement::SubgroupBallot { result, predicate } => {
852 write!(self.out, "{level}")?;
853 let res_name = Baked(result).to_string();
854 self.start_named_expr(module, result, func_ctx, &res_name)?;
855 self.named_expressions.insert(result, res_name);
856
857 write!(self.out, "subgroupBallot(")?;
858 if let Some(predicate) = predicate {
859 self.write_expr(module, predicate, func_ctx)?;
860 }
861 writeln!(self.out, ");")?;
862 }
863 Statement::SubgroupCollectiveOperation {
864 op,
865 collective_op,
866 argument,
867 result,
868 } => {
869 write!(self.out, "{level}")?;
870 let res_name = Baked(result).to_string();
871 self.start_named_expr(module, result, func_ctx, &res_name)?;
872 self.named_expressions.insert(result, res_name);
873
874 match (collective_op, op) {
875 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
876 write!(self.out, "subgroupAll(")?
877 }
878 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
879 write!(self.out, "subgroupAny(")?
880 }
881 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
882 write!(self.out, "subgroupAdd(")?
883 }
884 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
885 write!(self.out, "subgroupMul(")?
886 }
887 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
888 write!(self.out, "subgroupMax(")?
889 }
890 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
891 write!(self.out, "subgroupMin(")?
892 }
893 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
894 write!(self.out, "subgroupAnd(")?
895 }
896 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
897 write!(self.out, "subgroupOr(")?
898 }
899 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
900 write!(self.out, "subgroupXor(")?
901 }
902 (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Add) => {
903 write!(self.out, "subgroupExclusiveAdd(")?
904 }
905 (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Mul) => {
906 write!(self.out, "subgroupExclusiveMul(")?
907 }
908 (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Add) => {
909 write!(self.out, "subgroupInclusiveAdd(")?
910 }
911 (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Mul) => {
912 write!(self.out, "subgroupInclusiveMul(")?
913 }
914 _ => unimplemented!(),
915 }
916 self.write_expr(module, argument, func_ctx)?;
917 writeln!(self.out, ");")?;
918 }
919 Statement::SubgroupGather {
920 mode,
921 argument,
922 result,
923 } => {
924 write!(self.out, "{level}")?;
925 let res_name = Baked(result).to_string();
926 self.start_named_expr(module, result, func_ctx, &res_name)?;
927 self.named_expressions.insert(result, res_name);
928
929 match mode {
930 crate::GatherMode::BroadcastFirst => {
931 write!(self.out, "subgroupBroadcastFirst(")?;
932 }
933 crate::GatherMode::Broadcast(_) => {
934 write!(self.out, "subgroupBroadcast(")?;
935 }
936 crate::GatherMode::Shuffle(_) => {
937 write!(self.out, "subgroupShuffle(")?;
938 }
939 crate::GatherMode::ShuffleDown(_) => {
940 write!(self.out, "subgroupShuffleDown(")?;
941 }
942 crate::GatherMode::ShuffleUp(_) => {
943 write!(self.out, "subgroupShuffleUp(")?;
944 }
945 crate::GatherMode::ShuffleXor(_) => {
946 write!(self.out, "subgroupShuffleXor(")?;
947 }
948 }
949 self.write_expr(module, argument, func_ctx)?;
950 match mode {
951 crate::GatherMode::BroadcastFirst => {}
952 crate::GatherMode::Broadcast(index)
953 | crate::GatherMode::Shuffle(index)
954 | crate::GatherMode::ShuffleDown(index)
955 | crate::GatherMode::ShuffleUp(index)
956 | crate::GatherMode::ShuffleXor(index) => {
957 write!(self.out, ", ")?;
958 self.write_expr(module, index, func_ctx)?;
959 }
960 }
961 writeln!(self.out, ");")?;
962 }
963 }
964
965 Ok(())
966 }
967
968 /// Return the sort of indirection that `expr`'s plain form evaluates to.
969 ///
970 /// An expression's 'plain form' is the most general rendition of that
971 /// expression into WGSL, lacking `&` or `*` operators:
972 ///
973 /// - The plain form of `LocalVariable(x)` is simply `x`, which is a reference
974 /// to the local variable's storage.
975 ///
976 /// - The plain form of `GlobalVariable(g)` is simply `g`, which is usually a
977 /// reference to the global variable's storage. However, globals in the
978 /// `Handle` address space are immutable, and `GlobalVariable` expressions for
979 /// those produce the value directly, not a pointer to it. Such
980 /// `GlobalVariable` expressions are `Ordinary`.
981 ///
982 /// - `Access` and `AccessIndex` are `Reference` when their `base` operand is a
983 /// pointer. If they are applied directly to a composite value, they are
984 /// `Ordinary`.
985 ///
986 /// Note that `FunctionArgument` expressions are never `Reference`, even when
987 /// the argument's type is `Pointer`. `FunctionArgument` always evaluates to the
988 /// argument's value directly, so any pointer it produces is merely the value
989 /// passed by the caller.
990 fn plain_form_indirection(
991 &self,
992 expr: Handle<crate::Expression>,
993 module: &Module,
994 func_ctx: &back::FunctionCtx<'_>,
995 ) -> Indirection {
996 use crate::Expression as Ex;
997
998 // Named expressions are `let` expressions, which apply the Load Rule,
999 // so if their type is a Naga pointer, then that must be a WGSL pointer
1000 // as well.
1001 if self.named_expressions.contains_key(&expr) {
1002 return Indirection::Ordinary;
1003 }
1004
1005 match func_ctx.expressions[expr] {
1006 Ex::LocalVariable(_) => Indirection::Reference,
1007 Ex::GlobalVariable(handle) => {
1008 let global = &module.global_variables[handle];
1009 match global.space {
1010 crate::AddressSpace::Handle => Indirection::Ordinary,
1011 _ => Indirection::Reference,
1012 }
1013 }
1014 Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => {
1015 let base_ty = func_ctx.resolve_type(base, &module.types);
1016 match *base_ty {
1017 TypeInner::Pointer { .. } | TypeInner::ValuePointer { .. } => {
1018 Indirection::Reference
1019 }
1020 _ => Indirection::Ordinary,
1021 }
1022 }
1023 _ => Indirection::Ordinary,
1024 }
1025 }
1026
1027 fn start_named_expr(
1028 &mut self,
1029 module: &Module,
1030 handle: Handle<crate::Expression>,
1031 func_ctx: &back::FunctionCtx,
1032 name: &str,
1033 ) -> BackendResult {
1034 // Write variable name
1035 write!(self.out, "let {name}")?;
1036 if self.flags.contains(WriterFlags::EXPLICIT_TYPES) {
1037 write!(self.out, ": ")?;
1038 // Write variable type
1039 self.write_type_resolution(module, &func_ctx.info[handle].ty)?;
1040 }
1041
1042 write!(self.out, " = ")?;
1043 Ok(())
1044 }
1045
1046 /// Write the ordinary WGSL form of `expr`.
1047 ///
1048 /// See `write_expr_with_indirection` for details.
1049 fn write_expr(
1050 &mut self,
1051 module: &Module,
1052 expr: Handle<crate::Expression>,
1053 func_ctx: &back::FunctionCtx<'_>,
1054 ) -> BackendResult {
1055 self.write_expr_with_indirection(module, expr, func_ctx, Indirection::Ordinary)
1056 }
1057
1058 /// Write `expr` as a WGSL expression with the requested indirection.
1059 ///
1060 /// In terms of the WGSL grammar, the resulting expression is a
1061 /// `singular_expression`. It may be parenthesized. This makes it suitable
1062 /// for use as the operand of a unary or binary operator without worrying
1063 /// about precedence.
1064 ///
1065 /// This does not produce newlines or indentation.
1066 ///
1067 /// The `requested` argument indicates (roughly) whether Naga
1068 /// `Pointer`-valued expressions represent WGSL references or pointers. See
1069 /// `Indirection` for details.
1070 fn write_expr_with_indirection(
1071 &mut self,
1072 module: &Module,
1073 expr: Handle<crate::Expression>,
1074 func_ctx: &back::FunctionCtx<'_>,
1075 requested: Indirection,
1076 ) -> BackendResult {
1077 // If the plain form of the expression is not what we need, emit the
1078 // operator necessary to correct that.
1079 let plain = self.plain_form_indirection(expr, module, func_ctx);
1080 match (requested, plain) {
1081 (Indirection::Ordinary, Indirection::Reference) => {
1082 write!(self.out, "(&")?;
1083 self.write_expr_plain_form(module, expr, func_ctx, plain)?;
1084 write!(self.out, ")")?;
1085 }
1086 (Indirection::Reference, Indirection::Ordinary) => {
1087 write!(self.out, "(*")?;
1088 self.write_expr_plain_form(module, expr, func_ctx, plain)?;
1089 write!(self.out, ")")?;
1090 }
1091 (_, _) => self.write_expr_plain_form(module, expr, func_ctx, plain)?,
1092 }
1093
1094 Ok(())
1095 }
1096
1097 fn write_const_expression(
1098 &mut self,
1099 module: &Module,
1100 expr: Handle<crate::Expression>,
1101 arena: &crate::Arena<crate::Expression>,
1102 ) -> BackendResult {
1103 self.write_possibly_const_expression(module, expr, arena, |writer, expr| {
1104 writer.write_const_expression(module, expr, arena)
1105 })
1106 }
1107
1108 fn write_possibly_const_expression<E>(
1109 &mut self,
1110 module: &Module,
1111 expr: Handle<crate::Expression>,
1112 expressions: &crate::Arena<crate::Expression>,
1113 write_expression: E,
1114 ) -> BackendResult
1115 where
1116 E: Fn(&mut Self, Handle<crate::Expression>) -> BackendResult,
1117 {
1118 use crate::Expression;
1119
1120 match expressions[expr] {
1121 Expression::Literal(literal) => match literal {
1122 crate::Literal::F16(value) => write!(self.out, "{value}h")?,
1123 crate::Literal::F32(value) => write!(self.out, "{value}f")?,
1124 crate::Literal::U32(value) => write!(self.out, "{value}u")?,
1125 crate::Literal::I32(value) => {
1126 // `-2147483648i` is not valid WGSL. The most negative `i32`
1127 // value can only be expressed in WGSL using AbstractInt and
1128 // a unary negation operator.
1129 if value == i32::MIN {
1130 write!(self.out, "i32({value})")?;
1131 } else {
1132 write!(self.out, "{value}i")?;
1133 }
1134 }
1135 crate::Literal::Bool(value) => write!(self.out, "{value}")?,
1136 crate::Literal::F64(value) => write!(self.out, "{value:?}lf")?,
1137 crate::Literal::I64(value) => {
1138 // `-9223372036854775808li` is not valid WGSL. Nor can we simply use the
1139 // AbstractInt trick above, as AbstractInt also cannot represent
1140 // `9223372036854775808`. Instead construct the second most negative
1141 // AbstractInt, subtract one from it, then cast to i64.
1142 if value == i64::MIN {
1143 write!(self.out, "i64({} - 1)", value + 1)?;
1144 } else {
1145 write!(self.out, "{value}li")?;
1146 }
1147 }
1148 crate::Literal::U64(value) => write!(self.out, "{value:?}lu")?,
1149 crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
1150 return Err(Error::Custom(
1151 "Abstract types should not appear in IR presented to backends".into(),
1152 ));
1153 }
1154 },
1155 Expression::Constant(handle) => {
1156 let constant = &module.constants[handle];
1157 if constant.name.is_some() {
1158 write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
1159 } else {
1160 self.write_const_expression(module, constant.init, &module.global_expressions)?;
1161 }
1162 }
1163 Expression::ZeroValue(ty) => {
1164 self.write_type(module, ty)?;
1165 write!(self.out, "()")?;
1166 }
1167 Expression::Compose { ty, ref components } => {
1168 self.write_type(module, ty)?;
1169 write!(self.out, "(")?;
1170 for (index, component) in components.iter().enumerate() {
1171 if index != 0 {
1172 write!(self.out, ", ")?;
1173 }
1174 write_expression(self, *component)?;
1175 }
1176 write!(self.out, ")")?
1177 }
1178 Expression::Splat { size, value } => {
1179 let size = common::vector_size_str(size);
1180 write!(self.out, "vec{size}(")?;
1181 write_expression(self, value)?;
1182 write!(self.out, ")")?;
1183 }
1184 _ => unreachable!(),
1185 }
1186
1187 Ok(())
1188 }
1189
1190 /// Write the 'plain form' of `expr`.
1191 ///
1192 /// An expression's 'plain form' is the most general rendition of that
1193 /// expression into WGSL, lacking `&` or `*` operators. The plain forms of
1194 /// `LocalVariable(x)` and `GlobalVariable(g)` are simply `x` and `g`. Such
1195 /// Naga expressions represent both WGSL pointers and references; it's the
1196 /// caller's responsibility to distinguish those cases appropriately.
1197 fn write_expr_plain_form(
1198 &mut self,
1199 module: &Module,
1200 expr: Handle<crate::Expression>,
1201 func_ctx: &back::FunctionCtx<'_>,
1202 indirection: Indirection,
1203 ) -> BackendResult {
1204 use crate::Expression;
1205
1206 if let Some(name) = self.named_expressions.get(&expr) {
1207 write!(self.out, "{name}")?;
1208 return Ok(());
1209 }
1210
1211 let expression = &func_ctx.expressions[expr];
1212
1213 // Write the plain WGSL form of a Naga expression.
1214 //
1215 // The plain form of `LocalVariable` and `GlobalVariable` expressions is
1216 // simply the variable name; `*` and `&` operators are never emitted.
1217 //
1218 // The plain form of `Access` and `AccessIndex` expressions are WGSL
1219 // `postfix_expression` forms for member/component access and
1220 // subscripting.
1221 match *expression {
1222 Expression::Literal(_)
1223 | Expression::Constant(_)
1224 | Expression::ZeroValue(_)
1225 | Expression::Compose { .. }
1226 | Expression::Splat { .. } => {
1227 self.write_possibly_const_expression(
1228 module,
1229 expr,
1230 func_ctx.expressions,
1231 |writer, expr| writer.write_expr(module, expr, func_ctx),
1232 )?;
1233 }
1234 Expression::Override(_) => unreachable!(),
1235 Expression::FunctionArgument(pos) => {
1236 let name_key = func_ctx.argument_key(pos);
1237 let name = &self.names[&name_key];
1238 write!(self.out, "{name}")?;
1239 }
1240 Expression::Binary { op, left, right } => {
1241 write!(self.out, "(")?;
1242 self.write_expr(module, left, func_ctx)?;
1243 write!(self.out, " {} ", back::binary_operation_str(op))?;
1244 self.write_expr(module, right, func_ctx)?;
1245 write!(self.out, ")")?;
1246 }
1247 Expression::Access { base, index } => {
1248 self.write_expr_with_indirection(module, base, func_ctx, indirection)?;
1249 write!(self.out, "[")?;
1250 self.write_expr(module, index, func_ctx)?;
1251 write!(self.out, "]")?
1252 }
1253 Expression::AccessIndex { base, index } => {
1254 let base_ty_res = &func_ctx.info[base].ty;
1255 let mut resolved = base_ty_res.inner_with(&module.types);
1256
1257 self.write_expr_with_indirection(module, base, func_ctx, indirection)?;
1258
1259 let base_ty_handle = match *resolved {
1260 TypeInner::Pointer { base, space: _ } => {
1261 resolved = &module.types[base].inner;
1262 Some(base)
1263 }
1264 _ => base_ty_res.handle(),
1265 };
1266
1267 match *resolved {
1268 TypeInner::Vector { .. } => {
1269 // Write vector access as a swizzle
1270 write!(self.out, ".{}", back::COMPONENTS[index as usize])?
1271 }
1272 TypeInner::Matrix { .. }
1273 | TypeInner::Array { .. }
1274 | TypeInner::BindingArray { .. }
1275 | TypeInner::ValuePointer { .. } => write!(self.out, "[{index}]")?,
1276 TypeInner::Struct { .. } => {
1277 // This will never panic in case the type is a `Struct`, this is not true
1278 // for other types so we can only check while inside this match arm
1279 let ty = base_ty_handle.unwrap();
1280
1281 write!(
1282 self.out,
1283 ".{}",
1284 &self.names[&NameKey::StructMember(ty, index)]
1285 )?
1286 }
1287 ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))),
1288 }
1289 }
1290 Expression::ImageSample {
1291 image,
1292 sampler,
1293 gather: None,
1294 coordinate,
1295 array_index,
1296 offset,
1297 level,
1298 depth_ref,
1299 } => {
1300 use crate::SampleLevel as Sl;
1301
1302 let suffix_cmp = match depth_ref {
1303 Some(_) => "Compare",
1304 None => "",
1305 };
1306 let suffix_level = match level {
1307 Sl::Auto => "",
1308 Sl::Zero | Sl::Exact(_) => "Level",
1309 Sl::Bias(_) => "Bias",
1310 Sl::Gradient { .. } => "Grad",
1311 };
1312
1313 write!(self.out, "textureSample{suffix_cmp}{suffix_level}(")?;
1314 self.write_expr(module, image, func_ctx)?;
1315 write!(self.out, ", ")?;
1316 self.write_expr(module, sampler, func_ctx)?;
1317 write!(self.out, ", ")?;
1318 self.write_expr(module, coordinate, func_ctx)?;
1319
1320 if let Some(array_index) = array_index {
1321 write!(self.out, ", ")?;
1322 self.write_expr(module, array_index, func_ctx)?;
1323 }
1324
1325 if let Some(depth_ref) = depth_ref {
1326 write!(self.out, ", ")?;
1327 self.write_expr(module, depth_ref, func_ctx)?;
1328 }
1329
1330 match level {
1331 Sl::Auto => {}
1332 Sl::Zero => {
1333 // Level 0 is implied for depth comparison
1334 if depth_ref.is_none() {
1335 write!(self.out, ", 0.0")?;
1336 }
1337 }
1338 Sl::Exact(expr) => {
1339 write!(self.out, ", ")?;
1340 self.write_expr(module, expr, func_ctx)?;
1341 }
1342 Sl::Bias(expr) => {
1343 write!(self.out, ", ")?;
1344 self.write_expr(module, expr, func_ctx)?;
1345 }
1346 Sl::Gradient { x, y } => {
1347 write!(self.out, ", ")?;
1348 self.write_expr(module, x, func_ctx)?;
1349 write!(self.out, ", ")?;
1350 self.write_expr(module, y, func_ctx)?;
1351 }
1352 }
1353
1354 if let Some(offset) = offset {
1355 write!(self.out, ", ")?;
1356 self.write_const_expression(module, offset, func_ctx.expressions)?;
1357 }
1358
1359 write!(self.out, ")")?;
1360 }
1361
1362 Expression::ImageSample {
1363 image,
1364 sampler,
1365 gather: Some(component),
1366 coordinate,
1367 array_index,
1368 offset,
1369 level: _,
1370 depth_ref,
1371 } => {
1372 let suffix_cmp = match depth_ref {
1373 Some(_) => "Compare",
1374 None => "",
1375 };
1376
1377 write!(self.out, "textureGather{suffix_cmp}(")?;
1378 match *func_ctx.resolve_type(image, &module.types) {
1379 TypeInner::Image {
1380 class: crate::ImageClass::Depth { multi: _ },
1381 ..
1382 } => {}
1383 _ => {
1384 write!(self.out, "{}, ", component as u8)?;
1385 }
1386 }
1387 self.write_expr(module, image, func_ctx)?;
1388 write!(self.out, ", ")?;
1389 self.write_expr(module, sampler, func_ctx)?;
1390 write!(self.out, ", ")?;
1391 self.write_expr(module, coordinate, func_ctx)?;
1392
1393 if let Some(array_index) = array_index {
1394 write!(self.out, ", ")?;
1395 self.write_expr(module, array_index, func_ctx)?;
1396 }
1397
1398 if let Some(depth_ref) = depth_ref {
1399 write!(self.out, ", ")?;
1400 self.write_expr(module, depth_ref, func_ctx)?;
1401 }
1402
1403 if let Some(offset) = offset {
1404 write!(self.out, ", ")?;
1405 self.write_const_expression(module, offset, func_ctx.expressions)?;
1406 }
1407
1408 write!(self.out, ")")?;
1409 }
1410 Expression::ImageQuery { image, query } => {
1411 use crate::ImageQuery as Iq;
1412
1413 let texture_function = match query {
1414 Iq::Size { .. } => "textureDimensions",
1415 Iq::NumLevels => "textureNumLevels",
1416 Iq::NumLayers => "textureNumLayers",
1417 Iq::NumSamples => "textureNumSamples",
1418 };
1419
1420 write!(self.out, "{texture_function}(")?;
1421 self.write_expr(module, image, func_ctx)?;
1422 if let Iq::Size { level: Some(level) } = query {
1423 write!(self.out, ", ")?;
1424 self.write_expr(module, level, func_ctx)?;
1425 };
1426 write!(self.out, ")")?;
1427 }
1428
1429 Expression::ImageLoad {
1430 image,
1431 coordinate,
1432 array_index,
1433 sample,
1434 level,
1435 } => {
1436 write!(self.out, "textureLoad(")?;
1437 self.write_expr(module, image, func_ctx)?;
1438 write!(self.out, ", ")?;
1439 self.write_expr(module, coordinate, func_ctx)?;
1440 if let Some(array_index) = array_index {
1441 write!(self.out, ", ")?;
1442 self.write_expr(module, array_index, func_ctx)?;
1443 }
1444 if let Some(index) = sample.or(level) {
1445 write!(self.out, ", ")?;
1446 self.write_expr(module, index, func_ctx)?;
1447 }
1448 write!(self.out, ")")?;
1449 }
1450 Expression::GlobalVariable(handle) => {
1451 let name = &self.names[&NameKey::GlobalVariable(handle)];
1452 write!(self.out, "{name}")?;
1453 }
1454
1455 Expression::As {
1456 expr,
1457 kind,
1458 convert,
1459 } => {
1460 let inner = func_ctx.resolve_type(expr, &module.types);
1461 match *inner {
1462 TypeInner::Matrix {
1463 columns,
1464 rows,
1465 scalar,
1466 } => {
1467 let scalar = crate::Scalar {
1468 kind,
1469 width: convert.unwrap_or(scalar.width),
1470 };
1471 let scalar_kind_str = scalar.to_wgsl_if_implemented()?;
1472 write!(
1473 self.out,
1474 "mat{}x{}<{}>",
1475 common::vector_size_str(columns),
1476 common::vector_size_str(rows),
1477 scalar_kind_str
1478 )?;
1479 }
1480 TypeInner::Vector {
1481 size,
1482 scalar: crate::Scalar { width, .. },
1483 } => {
1484 let scalar = crate::Scalar {
1485 kind,
1486 width: convert.unwrap_or(width),
1487 };
1488 let vector_size_str = common::vector_size_str(size);
1489 let scalar_kind_str = scalar.to_wgsl_if_implemented()?;
1490 if convert.is_some() {
1491 write!(self.out, "vec{vector_size_str}<{scalar_kind_str}>")?;
1492 } else {
1493 write!(self.out, "bitcast<vec{vector_size_str}<{scalar_kind_str}>>")?;
1494 }
1495 }
1496 TypeInner::Scalar(crate::Scalar { width, .. }) => {
1497 let scalar = crate::Scalar {
1498 kind,
1499 width: convert.unwrap_or(width),
1500 };
1501 let scalar_kind_str = scalar.to_wgsl_if_implemented()?;
1502 if convert.is_some() {
1503 write!(self.out, "{scalar_kind_str}")?
1504 } else {
1505 write!(self.out, "bitcast<{scalar_kind_str}>")?
1506 }
1507 }
1508 _ => {
1509 return Err(Error::Unimplemented(format!(
1510 "write_expr expression::as {inner:?}"
1511 )));
1512 }
1513 };
1514 write!(self.out, "(")?;
1515 self.write_expr(module, expr, func_ctx)?;
1516 write!(self.out, ")")?;
1517 }
1518 Expression::Load { pointer } => {
1519 let is_atomic_pointer = func_ctx
1520 .resolve_type(pointer, &module.types)
1521 .is_atomic_pointer(&module.types);
1522
1523 if is_atomic_pointer {
1524 write!(self.out, "atomicLoad(")?;
1525 self.write_expr(module, pointer, func_ctx)?;
1526 write!(self.out, ")")?;
1527 } else {
1528 self.write_expr_with_indirection(
1529 module,
1530 pointer,
1531 func_ctx,
1532 Indirection::Reference,
1533 )?;
1534 }
1535 }
1536 Expression::LocalVariable(handle) => {
1537 write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])?
1538 }
1539 Expression::ArrayLength(expr) => {
1540 write!(self.out, "arrayLength(")?;
1541 self.write_expr(module, expr, func_ctx)?;
1542 write!(self.out, ")")?;
1543 }
1544
1545 Expression::Math {
1546 fun,
1547 arg,
1548 arg1,
1549 arg2,
1550 arg3,
1551 } => {
1552 use crate::MathFunction as Mf;
1553
1554 enum Function {
1555 Regular(&'static str),
1556 InversePolyfill(InversePolyfill),
1557 }
1558
1559 let function = match fun.try_to_wgsl() {
1560 Some(name) => Function::Regular(name),
1561 None => match fun {
1562 Mf::Inverse => {
1563 let ty = func_ctx.resolve_type(arg, &module.types);
1564 let Some(overload) = InversePolyfill::find_overload(ty) else {
1565 return Err(Error::unsupported("math function", fun));
1566 };
1567
1568 Function::InversePolyfill(overload)
1569 }
1570 _ => return Err(Error::unsupported("math function", fun)),
1571 },
1572 };
1573
1574 match function {
1575 Function::Regular(fun_name) => {
1576 write!(self.out, "{fun_name}(")?;
1577 self.write_expr(module, arg, func_ctx)?;
1578 for arg in IntoIterator::into_iter([arg1, arg2, arg3]).flatten() {
1579 write!(self.out, ", ")?;
1580 self.write_expr(module, arg, func_ctx)?;
1581 }
1582 write!(self.out, ")")?
1583 }
1584 Function::InversePolyfill(inverse) => {
1585 write!(self.out, "{}(", inverse.fun_name)?;
1586 self.write_expr(module, arg, func_ctx)?;
1587 write!(self.out, ")")?;
1588 self.required_polyfills.insert(inverse);
1589 }
1590 }
1591 }
1592
1593 Expression::Swizzle {
1594 size,
1595 vector,
1596 pattern,
1597 } => {
1598 self.write_expr(module, vector, func_ctx)?;
1599 write!(self.out, ".")?;
1600 for &sc in pattern[..size as usize].iter() {
1601 self.out.write_char(back::COMPONENTS[sc as usize])?;
1602 }
1603 }
1604 Expression::Unary { op, expr } => {
1605 let unary = match op {
1606 crate::UnaryOperator::Negate => "-",
1607 crate::UnaryOperator::LogicalNot => "!",
1608 crate::UnaryOperator::BitwiseNot => "~",
1609 };
1610
1611 write!(self.out, "{unary}(")?;
1612 self.write_expr(module, expr, func_ctx)?;
1613
1614 write!(self.out, ")")?
1615 }
1616
1617 Expression::Select {
1618 condition,
1619 accept,
1620 reject,
1621 } => {
1622 write!(self.out, "select(")?;
1623 self.write_expr(module, reject, func_ctx)?;
1624 write!(self.out, ", ")?;
1625 self.write_expr(module, accept, func_ctx)?;
1626 write!(self.out, ", ")?;
1627 self.write_expr(module, condition, func_ctx)?;
1628 write!(self.out, ")")?
1629 }
1630 Expression::Derivative { axis, ctrl, expr } => {
1631 use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
1632 let op = match (axis, ctrl) {
1633 (Axis::X, Ctrl::Coarse) => "dpdxCoarse",
1634 (Axis::X, Ctrl::Fine) => "dpdxFine",
1635 (Axis::X, Ctrl::None) => "dpdx",
1636 (Axis::Y, Ctrl::Coarse) => "dpdyCoarse",
1637 (Axis::Y, Ctrl::Fine) => "dpdyFine",
1638 (Axis::Y, Ctrl::None) => "dpdy",
1639 (Axis::Width, Ctrl::Coarse) => "fwidthCoarse",
1640 (Axis::Width, Ctrl::Fine) => "fwidthFine",
1641 (Axis::Width, Ctrl::None) => "fwidth",
1642 };
1643 write!(self.out, "{op}(")?;
1644 self.write_expr(module, expr, func_ctx)?;
1645 write!(self.out, ")")?
1646 }
1647 Expression::Relational { fun, argument } => {
1648 use crate::RelationalFunction as Rf;
1649
1650 let fun_name = match fun {
1651 Rf::All => "all",
1652 Rf::Any => "any",
1653 _ => return Err(Error::UnsupportedRelationalFunction(fun)),
1654 };
1655 write!(self.out, "{fun_name}(")?;
1656
1657 self.write_expr(module, argument, func_ctx)?;
1658
1659 write!(self.out, ")")?
1660 }
1661 // Not supported yet
1662 Expression::RayQueryGetIntersection { .. }
1663 | Expression::RayQueryVertexPositions { .. } => unreachable!(),
1664 // Nothing to do here, since call expression already cached
1665 Expression::CallResult(_)
1666 | Expression::AtomicResult { .. }
1667 | Expression::RayQueryProceedResult
1668 | Expression::SubgroupBallotResult
1669 | Expression::SubgroupOperationResult { .. }
1670 | Expression::WorkGroupUniformLoadResult { .. } => {}
1671 }
1672
1673 Ok(())
1674 }
1675
1676 /// Helper method used to write global variables
1677 /// # Notes
1678 /// Always adds a newline
1679 fn write_global(
1680 &mut self,
1681 module: &Module,
1682 global: &crate::GlobalVariable,
1683 handle: Handle<crate::GlobalVariable>,
1684 ) -> BackendResult {
1685 // Write group and binding attributes if present
1686 if let Some(ref binding) = global.binding {
1687 self.write_attributes(&[
1688 Attribute::Group(binding.group),
1689 Attribute::Binding(binding.binding),
1690 ])?;
1691 writeln!(self.out)?;
1692 }
1693
1694 // First write global name and address space if supported
1695 write!(self.out, "var")?;
1696 let (address, maybe_access) = address_space_str(global.space);
1697 if let Some(space) = address {
1698 write!(self.out, "<{space}")?;
1699 if let Some(access) = maybe_access {
1700 write!(self.out, ", {access}")?;
1701 }
1702 write!(self.out, ">")?;
1703 }
1704 write!(
1705 self.out,
1706 " {}: ",
1707 &self.names[&NameKey::GlobalVariable(handle)]
1708 )?;
1709
1710 // Write global type
1711 self.write_type(module, global.ty)?;
1712
1713 // Write initializer
1714 if let Some(init) = global.init {
1715 write!(self.out, " = ")?;
1716 self.write_const_expression(module, init, &module.global_expressions)?;
1717 }
1718
1719 // End with semicolon
1720 writeln!(self.out, ";")?;
1721
1722 Ok(())
1723 }
1724
1725 /// Helper method used to write global constants
1726 ///
1727 /// # Notes
1728 /// Ends in a newline
1729 fn write_global_constant(
1730 &mut self,
1731 module: &Module,
1732 handle: Handle<crate::Constant>,
1733 ) -> BackendResult {
1734 let name = &self.names[&NameKey::Constant(handle)];
1735 // First write only constant name
1736 write!(self.out, "const {name}: ")?;
1737 self.write_type(module, module.constants[handle].ty)?;
1738 write!(self.out, " = ")?;
1739 let init = module.constants[handle].init;
1740 self.write_const_expression(module, init, &module.global_expressions)?;
1741 writeln!(self.out, ";")?;
1742
1743 Ok(())
1744 }
1745
1746 // See https://github.com/rust-lang/rust-clippy/issues/4979.
1747 #[allow(clippy::missing_const_for_fn)]
1748 pub fn finish(self) -> W {
1749 self.out
1750 }
1751 }
1752
1753 struct WriterTypeContext<'m> {
1754 module: &'m Module,
1755 names: &'m crate::FastHashMap<NameKey, String>,
1756 }
1757
1758 impl TypeContext for WriterTypeContext<'_> {
1759 fn lookup_type(&self, handle: Handle<crate::Type>) -> &crate::Type {
1760 &self.module.types[handle]
1761 }
1762
1763 fn type_name(&self, handle: Handle<crate::Type>) -> &str {
1764 self.names[&NameKey::Type(handle)].as_str()
1765 }
1766
1767 fn write_unnamed_struct<W: Write>(&self, _: &TypeInner, _: &mut W) -> core::fmt::Result {
1768 unreachable!("the WGSL back end should always provide type handles");
1769 }
1770
1771 fn write_override<W: Write>(&self, _: Handle<crate::Override>, _: &mut W) -> core::fmt::Result {
1772 unreachable!("overrides should be validated out");
1773 }
1774
1775 fn write_non_wgsl_inner<W: Write>(&self, _: &TypeInner, _: &mut W) -> core::fmt::Result {
1776 unreachable!("backends should only be passed validated modules");
1777 }
1778
1779 fn write_non_wgsl_scalar<W: Write>(&self, _: crate::Scalar, _: &mut W) -> core::fmt::Result {
1780 unreachable!("backends should only be passed validated modules");
1781 }
1782 }
1783
1784 fn map_binding_to_attribute(binding: &crate::Binding) -> Vec<Attribute> {
1785 match *binding {
1786 crate::Binding::BuiltIn(built_in) => {
1787 if let crate::BuiltIn::Position { invariant: true } = built_in {
1788 vec![Attribute::BuiltIn(built_in), Attribute::Invariant]
1789 } else {
1790 vec![Attribute::BuiltIn(built_in)]
1791 }
1792 }
1793 crate::Binding::Location {
1794 location,
1795 interpolation,
1796 sampling,
1797 blend_src: None,
1798 } => vec![
1799 Attribute::Location(location),
1800 Attribute::Interpolate(interpolation, sampling),
1801 ],
1802 crate::Binding::Location {
1803 location,
1804 interpolation,
1805 sampling,
1806 blend_src: Some(blend_src),
1807 } => vec![
1808 Attribute::Location(location),
1809 Attribute::BlendSrc(blend_src),
1810 Attribute::Interpolate(interpolation, sampling),
1811 ],
1812 }
1813 }