WebGPU Shading Language

Editor’s Draft,

Issue Tracking:
GitHub
Inline In Spec
Editors:
(Google)
(Apple Inc.)
Participate:
File an issue (open issues)

Abstract

Shading language for WebGPU.

Status of this document

This specification was published by the GPU for the Web Community Group. It is not a W3C Standard nor is it on the W3C Standards Track. Please note that under the W3C Community Contributor License Agreement (CLA) there is a limited opt-out and other conditions apply. Learn more about W3C Community and Business Groups.

1. Introduction

[[location 0]] var<out> gl_FragColor : vec4<f32>;
fn main() -> void {
    gl_FragColor = vec4<f32>(0.4, 0.4, 0.8, 1.0);
    return;
}
entry_point fragment = main;

1.1. Goals

2. Formal Type Definitions

Note: For the syntax of declaring types in WGSL please see the § 3 Grammar.

Programs calculate values. Each value in WGSL belongs to exactly one type. A type is a set of (mathematical) values.

We distinguish between the concept of a type and the syntax in WGSL to denote that type. In many cases the spelling of a type in this document is the same as its WGSL syntax. The spelling is different for structure types, or types containing structures.

2.1. Void type

Type Category Description
void Void No value.

The void type contains no values. It is used where a type is required by the language but where no values are produced or consumed. For example, it is used for the return type of a function which does not produce a value.

2.2. Scalar Types

Type Category Description
bool Boolean Values are true or false
i32 Numeric scalar 32 bit signed integer, two’s complement representation
u32 Numeric scalar 32 bit unsigned integer
f32 Numeric scalar 32 bit IEEE 754 floating point number, including infinities and NaNs

2.3. Vector Types

Type Description
vecN<T> Vector of N elements of type T. N must be in {2, 3, 4} and T must be one of the § 2.2 Scalar Types. We say T is the component type of the vector
EXAMPLE: Vector
vec2<f32>  # is a vector of two f32s.

2.4. Matrix Types

Type Description
matNxM<T> Matrix of N columns and M rows, where N and M are both in {2, 3, 4}. T must be f32.
EXAMPLE: Matrix
mat2x3<f32>  # is a 2 column, 3 row matrix of 32-bit floats.

2.5. Array Types

Type Description
array<E,N> An N-element array of elements of type E.
array<E> A runtime-sized array of elements of type E, also known as a runtime array. These may only appear in specific contexts.

(dneto): Complete description of Array<E,N>

(dneto): the last element of a struct defining the contents of a storage buffer.

2.6. Structure Types

Type Description
struct<T1,...,Tn> An ordered tuple of N members of types T1 through Tn, with N being an integer greater than 0.
EXAMPLE: Structure
type foo = struct {
  a : i32;
  b : vec2<f32>;
}

2.7. Pointer Types

Type Description
ptr<SC,T> Pointer (or reference) to storage in § 3.18 Storage Classes SC which can hold a value of the § 2.8 Storable types T. Here, T is the known as the pointee type.

Note: We’ve described a SPIR-V logical pointer type.

EXAMPLE: Pointer
ptr<storage_buffer, i32>
ptr<private, array<i32, 12>>

2.8. Storable types

The following types are storable:

Note: SPIR-V logical pointers are not storable.

2.9. Composite types

A type is composite if its values have a well-defined internal structure of typed components.

The following types are composite types:

WGSL has operations for:

2.10. Typed storage

In WGSL, a value of § 2.8 Storable types may be stored in memory, for later retrieval.

A pointer value P supports the following operations:

P.Write(V) Place a value V into the referenced storage. V’s type must match P’s pointee type.
P.Read() An evaluation yielding the value currently in the P’s referenced storage. The result type is P’s pointee type.
P.Subaccess(K) Valid for pointers with a composite pointee type where K must evaluate to an integer between 0 and one less than the number of components in P’s pointee type. The subaccess evaluation yields a pointer to the storage for the K’th component within P’s referenced storage, using zero-based indexing. If P’s storage class is SC, and the K’th member of P’s pointee type is of type T, then the result type is ptr<SC,T>.

Note: Assignment of swizzled values is not permitted (SubaccessSwizzle).
e.g. vec4<i32> v; v.xz = vec2<i32>(0, 1); is not allowed.

2.11. Pointer evaluation

A pointer may appear in exactly the following contexts

Indexing A subaccessing evaluation
  • E.g. a[12]

    • If a is a pointer to an array, this evaluates to a.Subaccess(12)

  • E.g. s.foo

    • If s is a pointer to a structure of type S, k is the index of the foo element of S, this evaluates to s.Subaccess(k)

Assigning (L-Value) On the left hand side of an assignment operation, and the right hand side matches the pointee type of the pointer.
  • E.g. v = 12; assuming prior declaration var v : i32

Copying On the right hand side of a const-declaration, and the type of the const-declaration matches the pointer type.
  • E.g. const v2 : ptr<private,i32> = v; assuming prior declaration var<private> v:i32

Parameter Used in a function call, where the function’s parameter type matches the pointer type.
Reading (R-Value) Any other context. Evaluates to P.Read(), yielding a value of P’s pointee type.

2.12. Variables

A variable is a named reference to storage that can contain a value of a particular type.

Two types are associated with a variable: its store type (the type of value that may be placed in the referenced storage) and its reference type (the type of the variable itself). If a variable has store type T and storage class S, then its reference type is pointer-to-T-in-S.

A variable declaration

Consider the following snippet of WGSL:
var x : f32 = 1.0;
const y = x * x + x + 1;

Because x is a variable, all accesses to it turn into load and store operations. If this snippet was compiled to SPIR-V, it would be represented as

%temp_1 = OpLoad %float %x
%temp_2 = OpLoad %float %x
%temp_3 = OpFMul %float %temp_1 %temp_2
%temp_4 = OpLoad %float %x
%temp_5 = OpFAdd %float %temp_3 %temp_4
%y      = OpFAdd %float %temp_5 %one

However, it is expected that either the browser or the driver optimizes this intermediate representation such that the redundant loads are eliminated.

3. Grammar

3.1. Scoping

Scoping is the set of rules determining where a variable may be used.

(dneto) also lifetime.

There are multiple levels of scoping depending on how and where things are declared.

Note: Shadow variables are not allowed in WGSL. A variable must not be defined in a given scope or any scope above the current one.

3.2. Module Scope

Any variable declared outside a function is at module scope.

3.3. Function Scope

Variables declared within a function are at function scope. The variable is visible at any scoping level which comes after the variable declaration in the source code. The variable is not visible until it is declared.

3.4. Comments

Comments begin with a # and continue to the end of the current line. There are no multi-line comments.

3.5. Precedence

(dsinclair) Write out precedence rules. Matches c and glsl rules ....

3.6. Type Promotions

There are no implicit type promotions in WGSL. If you want to convert between types you must use the cast syntax to do it.
var e : f32 = 3;    # error: literal is the wrong type

var f : f32 = 1.0;

var t : i32 = i32(f);

The non-promotion extends to vector classes as well. There are no overrides to shorten vector declarations based on the type or number of elements provided. If you want vec4<f32> you must provide 4 float values in the constructor.

3.7. Identifiers and Numeric Literals

Token Definition
FLOAT_LITERAL (-?[0-9].[0-9]+ | -?[0-9]+.[0-9])(e(+|-)?[0-9]+)?
INT_LITERAL -?0x[0-9a-fA-F]+ | 0 | -?[1-9][0-9]*
UINT_LITERAL 0x[0-9a-fA-F]+u | 0u | [1-9][0-9]*u
IDENT [a-zA-Z][0-9a-zA-Z_]*
STRING_LITERAL "[^"]*"

Note: literals are parsed greedy. This means that for statements like a -5 this will not parse as a minus 5 but instead as a -5 which may be unexpected. A space must be inserted after the - if the first expression is desired.

3.7.1. Default Values

3.8. Keywords

Token Definition
ARRAY array
BOOL bool
FLOAT32 f32
INT32 i32
MAT2x2 mat2x2 # column x row
MAT2x3 mat2x3 # column x row
MAT2x4 mat2x4 # column x row
MAT3x2 mat3x2 # column x row
MAT3x3 mat3x3 # column x row
MAT3x4 mat3x4 # column x row
MAT4x2 mat4x2 # column x row
MAT4x3 mat4x3 # column x row
MAT4x4 mat4x4 # column x row
POINTER ptr
STRUCT struct
UINT32 u32
VEC2 vec2
VEC3 vec3
VEC4 vec4
VOID void
AS as
BINDING binding
BLOCK block
BREAK break
BUILTIN builtin
CASE case
CAST cast
COMPUTE compute
CONST const
CONTINUE continue
CONTINUING continuing
DEFAULT default
ELSE else
ELSE_IF elseif
ENTRY_POINT entry_point
FALLTHROUGH fallthrough
FALSE false
FN fn
FRAGMENT fragment
FUNCTION function
IF if
IMAGE image
IMPORT_ import
IN in
KILL kill
LOCATION location
LOOP loop
OFFSET offset
OUT out
PRIVATE private
RETURN return
SET set
STORAGE_BUFFER storage_buffer
SWITCH switch
TRUE true
TYPE type
UNIFORM uniform
UNIFORM_CONSTANT uniform_constant
UNLESS unless
VAR var
VERTEX vertex
WORKGROUP workgroup

3.9. Reserved Keywords

The following is a list of keywords which are reserved for future expansion.
asm bf16 do enum f16
f64 for i8 i16 i64
let typedef u8 u16 u64
using while regardless premerge

3.10. Syntactic Tokens

AND &
AND_AND &&
ARROW ->
ATTR_LEFT [[
ATTR_RIGHT ]]
FORWARD_SLASH /
BANG !
BRACKET_LEFT [
BRACKET_RIGHT ]
BRACE_LEFT {
BRACE_RIGHT }
COLON :
COMMA ,
EQUAL =
EQUAL_EQUAL ==
NOT_EQUAL !==
GREATER_THAN >
GREATER_THAN_EQUAL >=
LOGICAL_SHIFT_RIGHT >>
ARITH_SHIFT_RIGHT >>>
LESS_THAN <
LESS_THAN_EQUAL <=
SHIFT_LEFT <<
MOD %
MINUS -
NAMESPACE ::
PERIOD .
PLUS +
OR |
OR_OR ||
PAREN_LEFT (
PAREN_RIGHT )
SEMICOLON ;
STAR *
XOR ^

3.11. Preamble

WGSL is focused on WebGPU shaders. As such, the following is defined for all shaders which are generated:
EXAMPLE: Preamble
....
OpCapability Shader
OpCapability VulkanMemoryModel
OpMemoryModel Logical VulkanKHR
....

While we recognize that most Vulkan devices will not support VulkanMemoryModel we expect the SPIR-V generated to be converted by SPIRV-Tools after the fact to make the shader compatible.

translation_unit
  : global_decl* EOF

3.12. Global Declarations

global_decl
  : SEMICOLON
  | import_decl SEMICOLON
  | global_variable_decl SEMICOLON
  | global_constant_decl SEMICOLON
  | entry_point_decl SEMICOLON
  | type_alias SEMICOLON
  | function_decl

3.13. Imports

There is one import provided which is GLSL.std.450. All other uses of import will be rejected by WGSL as being unknown. All uses of the imported methods must be prefixed by the import name as provided after the as keyword.
import_decl
  : IMPORT STRING_LITERAL AS (IDENT NAMESPACE)* IDENT

The methods defined in GLSL.std.450 become available with the given prefix. The initial import will add an OpExtInstImport instruction to the SPIR-V module header and each usage of a GLSL method will add the appropriate OpExtIns invocation.

EXAMPLE: Import
import "GLSL.std.450" as std::glsl;
  %1 = OpExtInstImport "GLSL.std.450"

3.14. Module Variables

global_variable_decl
  : variable_decoration_list variable_decl
  | variable_decoration_list variable_decl EQUAL const_expr

global_constant_decl
  : CONST variable_ident_decl EQUAL const_expr

variable_decoration_list
  : ATTR_LEFT (variable_decoration COMMA)* variable_decoration ATTR_RIGHT

variable_decoration
  : LOCATION INT_LITERAL
  | BUILTIN IDENT
  | BINDING INT_LITERAL
  | SET INT_LITERAL
EXAMPLE: Variable Decorations
[[location 2]]
   OpDecorate %gl_FragColor Location 2

[[binding 3, set 4]]
   OpDecorate %gl_FragColor Binding 3
   OpDecorate %gl_FragColor DescriptorSet 4
EXAMPLE: Valid Builtin Decoration Identifiers
[[builtin position]]
      OpDecorate %gl_Position BuiltIn Position

[[builtin vertex_idx]]
      OpDecorate %gl_VertexIdx BuiltIn VertexIndex

[[builtin instance_idx]]
      OpDecorate %gl_InstanceId BuiltIn InstanceIndex

[[builtin front_facing]]
      OpDecorate %gl_FrontFacing BuiltIn FrontFacing

[[builtin frag_coord]]
      OpDecorate %gl_FragCoord BuiltIn FragCoord

[[builtin frag_depth]]
      OpDecorate %gl_FragDepth BuiltIn FragDepth

[[builtin num_workgroups]]
      OpDecorate %gl_NumWorkGroups BuiltIn NumWorkgroups

[[builtin workgroup_size]]
      OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize

[[builtin local_invocation_id]]
      OpDecorate %gl_LocalInvocationID BuiltIn LocalInvocationId

[[builtin local_invocation_idx]]
      OpDecorate %gl_LocalInvocationIndex BuiltIn LocalInvocationIndex

[[builtin global_invocation_id]]
      OpDecorate %gl_GlobalInvocationID BuiltIn GlobalInvocationId

The usages of the variable builtin decorations is further restricted in the type, function decorations and storage class.

Name Type Restrictions
position vec4<f32> Vertex Output
vertex_idx i32 Vertex Input
instance_idx i32 Vertex Input
front_facing bool Fragment Input
frag_coord vec4<f32> Fragment Input
frag_depth f32 Fragment Output
num_workgroups vec3<u32> Compute Input
workgroup_size vec3<u32> Compute Input
local_invocation_id vec3<u32> Compute Input
global_invocation_id vec3<u32> Compute Input
local_invocation_idx u32 Compute Input
variable_decl
  : VAR variable_storage_decoration? variable_ident_decl

variable_ident_decl
  : IDENT COLON type_decl

variable_storage_decoration:
  : LESS_THAN storage_class GREATER_THAN

3.15. Initializers

A variable must be in the Output, Private or Function storage class in order to have an initializer. As well, all variables in the Output, Private and Function storage class must have an initializer.
EXAMPLE: Global Scope
var bar : f32     # Error. Must have storage class. E.g. private

[[location 3]] var<in> foo : f32;

                    OpName %foo "foo"
                    OpDecorate %foo Location 3
           %float = OpTypeFloat 32
%_ptr_Input_float = OpTypePointer Input %float
             %foo = OpVariable %_ptr_Input_float Input

type S = [[block]] struct {
  f : vec4<f32>;
  a : array<i32>;
};
var<storage_buffer> buf : S;

                        OpDecorate %S Block
               %float = OpTypeFloat 32
             %v4float = OpTypeVector %float 4
   %_runtimearr_float = OpTypeRuntimeArray %float
                   %S = OpTypeStruct %v4float %_runtimearr_float
%_ptr_StorageBuffer_S = OpTypePointer StorageBuffer %S
             %buf = OpVariable %_ptr_StorageBuffer_S StorageBuffer
EXAMPLE: Function Scope
var foo : f32 = 2.5;

                       OpName %i "i"
              %float = OpTypeFloat 32
          %float_2_5 = OpConstant %float 2.5
%_ptr_Function_float = OpTypePointer Function %float
                      ...
                 %fn = OpFunction ...
              %i = OpVariable %_ptr_Function_float Function %float_2_5

3.16. Type Alias

type_alias
  : TYPE IDENT EQUAL type_decl
  | TYPE IDENT EQUAL struct_decl
EXAMPLE: Type Alias
type Arr = array<i32, 5>;

type ResType = struct {
  sf0 : vec4<f32>;
  sf1 : vec4<i32>;
};

type RTArr = [[stride 16]] array<vec4<f32>>;

type S = [[block]] struct {
  [[offset 0]] a : f32;
  [[offset 4]] b : f32;
  [[offset 16]] data : RTArr;
};

3.17. Type Declarations

type_decl
  : IDENT
  | BOOL
  | FLOAT32
  | INT32
  | UINT32
  | VEC2 LESS_THAN type_decl GREATER_THAN
  | VEC3 LESS_THAN type_decl GREATER_THAN
  | VEC3 LESS_THAN type_decl GREATER_THAN
  | PTR LESS_THAN storage_class, type_decl GREATER_THAN
  | ARRAY LESS_THAN type_decl COMMA INT_LITERAL GREATER_THAN
  | ARRAY LESS_THAN type_decl GREATER_THAN
  | MAT2x2 LESS_THAN type_decl GREATER_THAN
  | MAT2x3 LESS_THAN type_decl GREATER_THAN
  | MAT2x4 LESS_THAN type_decl GREATER_THAN
  | MAT3x2 LESS_THAN type_decl GREATER_THAN
  | MAT3x3 LESS_THAN type_decl GREATER_THAN
  | MAT3x4 LESS_THAN type_decl GREATER_THAN
  | MAT4x2 LESS_THAN type_decl GREATER_THAN
  | MAT4x3 LESS_THAN type_decl GREATER_THAN
  | MAT4x4 LESS_THAN type_decl GREATER_THAN
EXAMPLE: Type Declarations
identifier
  Allows to specify types created by the type command

bool
   %1 = OpTypeBool

f32
   %2 = OpTypeFloat 32

i32
   %3 = OpTypeInt 32 1

u32
   %4 = OpTypeInt 32 0

struct { i : i32; j : u32; x : f32; y : f32; }
   %foo = OpTypeStruct %3 %4 %2 %2 ;  assuming above SPIR-V types

vec2<f32>
    %7 = OpTypeVector %float 2

array<f32, 4>
   %uint_4 = OpConstant %uint 4
        %9 = OpTypeArray %float %uint_4

array<f32>
   %rtarr = OpTypeRuntimeArray %float

mat2x3<f32>
   %vec = OpTypeVector %float 3
     %6 = OpTypeMatrix %vec 2

3.18. Storage Classes

storage_class
  : INPUT
  | OUTPUT
  | UNIFORM
  | WORKGROUP
  | UNIFORM_CONSTANT
  | STORAGE_BUFFER
  | IMAGE
  | PRIVATE
  | FUNCTION
Name SPIR-V Storage Class
input Input
output Output
uniform Uniform
workgroup Workgroup
uniform_constant UniformConstant
storage_buffer StorageBuffer
image Image
private Private
function Function

3.19. Structures

struct_decl
  : struct_decoration_decl? STRUCT struct_body_decl

struct_decoration_decl
  : ATTR_LEFT struct_decoration ATTR_RIGHT

struct_decoration
  : BLOCK

struct_body_decl
  : BRACE_LEFT struct_member* BRACE_RIGHT

struct_member
  : struct_member_decoration_decl variable_ident_decl SEMICOLON

struct_member_decoration_decl
  :
  | ATTR_LEFT (struct_member_decoration COMMA)* struct_member_decoration ATTR_RIGHT

struct_member_decoration
  : OFFSET INT_LITERAL

Note: Layout decorations are required if the struct is used in an SSBO, UBO or Push Constant. Otherwise, the layout will be ignored.

(dneto): MatrixStride, RowMajor, ColMajor layout decorations are needed for matrices.

EXAMPLE: Structure
type my_struct = struct {
  [[offset 0]] a : f32;
  [[offset 4]] b : vec4<f32>;
};

              OpName %my_struct "my_struct"
              OpMemberName %my_struct 0 "a"
              OpMemberDecorate %my_struct 0 Offset 0
              OpMemberName %my_struct 1 "b"
              OpMemberDecorate %my_struct 1 Offset 4
 %my_struct = OpTypeStruct %float %v4float

3.20. Functions

Recursion is not permitted in WGSL.

Functions must end with a return statement. The return may be given with a value to be returned.

Function names must be unique over all functions and all variables in the module.

function_decl
  : function_header body_stmt

function_type_decl
  : type_decl
  | VOID

function_header
  : FN IDENT PAREN_LEFT param_list PAREN_RIGHT ARROW function_type_decl

param_list
  :
  | (variable_ident_decl COMMA)* variable_ident_decl
EXAMPLE: Function
void
    %6 = OpTypeVoid

fn my_func(i : i32, b : f32) -> i32 {
  return 2;
}

           OpName %my_func "my_func"
           OpName %a "a"
           OpName %b "b"
%my_func = OpFunction %int None %10
      %a = OpFunctionParameter %_ptr_Function_int
      %b = OpFunctionParameter %_ptr_Function_float
     %14 = OpLabel
           OpReturnValue %int_2
           OpFunctionEnd

3.20.1. Builtin Functions

Builtins SPIR-V
dpdx(IDENT) -> float OpDPdx
dpdx_coarse(IDENT) -> float OpDPdxCoarse
dpdx_fine(IDENT) -> float OpDPdxFine
dpdy(IDENT) -> float OpDPdy
dpdy_coarse(IDENT) -> float OpDPdyCoarse
dpdy_fine(IDENT) -> float OpDPdyFine
fwidth(IDENT) -> float OpFwidth
fwidth_coarse(IDENT) -> float OpFwidthCoarse
fwidth_fine(IDENT) -> float OpFwidthFine
all(BoolVec) -> bool OpAll
any(BoolVec) -> bool OpAny
is_finite(float) -> bool OpIsFinite
is_inf(float) -> bool OpIsInf
is_nan(float) -> bool OpIsNan
is_normal(float) -> bool OpIsNormal
dot(vecN , vecN ) -> float OpDot
outer_product(vecN , vecM ) -> matNxM OpOuterProduct

3.21. Entry Points

The entry_point declares an entry point into the module. The entry points may be forward declarations but the functions referenced must be declared in the file.

The input and output parameters to the entry point are determined by which global variables are used in the function and any called functions.

entry_point_decl:
   : ENTRY_POINT pipeline_stage EQUAL IDENT
   | ENTRY_POINT pipeline_stage AS STRING_LITERAL EQUAL IDENT
   | ENTRY_POINT pipeline_stage AS IDENT EQUAL IDENT

pipeline_stage
  : VERTEX
  | FRAGMENT
  | COMPUTE
EXAMPLE: Entry Point
entry_point vertex = main
   OpEntryPoint Vertex %vtx_main "vtx_main" %gl_FragColor

entry_point fragment as “frag_main” = main
   OpEntryPoint Fragment %main "frag_main" %gl_FragColor

entry_point compute = comp_main
   OpEntryPoint GLCompute %comp_main "comp_main" %gl_FragColor

3.22. Statements

body_stmt:
  : BRACE_LEFT statements BRACE_RIGHT

paren_rhs_stmt
  : PAREN_LEFT logical_or_expression PAREN_RIGHT

statements
  : statement*

statement
  : SEMICOLON
  | return_stmt SEMICOLON
  | if_stmt
  | unless_stmt
  | switch_stmt
  | loop_stmt
  | variable_stmt SEMICOLON
  | break_stmt SEMICOLON
  | continue_stmt SEMICOLON
  | KILL SEMICOLON
  | assignment_stmt SEMICOLON

variable_stmt
  : variable_decl
  | variable_decl EQUAL logical_or_expression
  | CONST variable_ident_decl EQUAL logical_or_expression

3.23. If Statement

if_stmt
  : IF paren_rhs_stmt body_stmt elseif_stmt? else_stmt?

elseif_stmt
  :ELSE_IF paren_rhs_stmt body_stmt elseif_stmt?

else_stmt
  : ELSE body_stmt

3.24. Unless Statement

unless_stmt
  : UNLESS paren_rhs_stmt body_stmt

3.25. Switch Statement

switch_stmt
  : SWITCH paren_rhs_stmt BRACE_LEFT switch_body+ BRACE_RIGHT

switch_body
  : CASE case_selectors COLON BRACE_LEFT case_body BRACE_RIGHT
  | DEFAULT COLON BRACE_LEFT case_body BRACE_RIGHT

case_selectors
  : const_literal (COMMA const_literal)*

case_body
  :
  | statement case_body
  | FALLTHROUGH SEMICOLON

A switch statement transfers control to one of a set of case clauses, or to a default clause, depending the evaluation of a selector expression of a scalar integer type.

If the selector value equals a value in a case selector list, then control is transferred to the body of that case clause. If the selector value does not equal any of the case selector values, then control is transferred to the default clause, if it exists, or otherwise to just past the switch body.

A literal value must not appear more than once in the case selectors for a switch statement.

The case selector values must have the same type as the selector expression.

Note: A literal value must not be duplicated within a case clause, and must not appear in more than one case selector list.

Note: The value of the literal is what matters, not the spelling. For example 0 and 00 both denote the zero value.

When control reaches the end of a case body, control normally transfers to the first statement after the switch statement. Alternately, executing a fallthrough statement transfers control to the body of the next case clause or default clause, whichever appears next in the switch body. A fallthrough statement must not appear as the last statement in the last case body of a switch.

3.26. Loop Statement

loop_stmt
  : LOOP BRACE_LEFT statements continuing_stmt? BRACE_RIGHT

The loop construct causes a block of statements, the loop body, to execute repeatedly.

This repetition can be interrupted by a § 3.27 Break statement, return, or kill.

Optionally, the last statement in the loop body may be a § 3.29 Continuing statement.

Note: The loop statement is one of the biggest differences from other shader languages. This design directly expresses loop idioms commonly found in compiled code. In particular, placing the loop update statements at the end of the loop body allows them to naturally use values defined in the loop body.

EXAMPLE: GLSL Loop
int a = 2;
for (int i = 0; i < 4; i++) {
  a *= 2;
}
EXAMPLE: WGSL Loop
const a : i32 = 2;
var i : i32 = 0;      // <1>
loop {
  break if (i >= 4);

  a = a * 2;

  i = i + 1;
}
EXAMPLE: GLSL Loop with continue
int a = 2;
const int step = 1;
for (int i = 0; i < 4; i += step) {
  if (i % 2 == 0) continue;
  a *= 2;
}
EXAMPLE: WGSL Loop with continue
const a : i32 = 2;
var i : i32 = 0;
loop {
  break if (i >= 4);

  const step : i32 = 1;

  i = i + 1;
  continue if (i % 2 == 0);

  a = a * 2;
}
EXAMPLE: WGSL Loop with continue and continuing
const a : i32 = 2;
var i : i32 = 0;
loop {
  break if (i >= 4);

  const step : i32 = 1;

  continue if (i % 2 == 0);

  a = a * 2;

  continuing {   // <2>
    i = i + step;
  }
}

3.26.1. Other Looping Constructs

Note: This is proposed but not in the WGSL spec yet

The for(var i : i32 = 0; i < 4; i = i + 1) {} statement is syntactic sugar on top of the § 3.26 Loop Statement.

The while(i < 4) {} is syntactic sugar on top of the § 3.26 Loop Statement where there is no continuing construct.

3.27. Break statement

break_stmt
  : BREAK ({IF | UNLESS} paren_rhs_stmt)?

Use a break statement to transfer control to the first statement after the body of the nearest-enclosing § 3.26 Loop Statement or § 3.25 Switch Statement.

The break statement has three forms:

When a break statement is placed such that it would exit from a loop’s § 3.29 Continuing statement, the break statement must appear last in that § 3.29 Continuing statement.

3.28. Continue statement

continue_stmt
  : CONTINUE ({IF | UNLESS} paren_rhs_stmt)?

Use a continue statement to transfer control in the nearest-enclosing § 3.26 Loop Statement:

The continue statement has three forms:

A continue statement must not be placed such that it would transfer control to an enclosing § 3.29 Continuing statement. (It is a forward branch when branching to a continuing statement.)

A continue statement must not be placed such that it would transfer control past a declaration used in the targeted continuing construct.

EXAMPLE: Invalid continue bypasses declaration
var i : i32 = 0;
loop {
  break if (i >= 4);
  continue if (i % 2 == 0); // <3>

  const step : i32 = 2;

  continuing {
    i = i + step;
  }
}

3.29. Continuing statement

continuing_stmt:
  : CONTINUING body_stmt

A continuing construct is a block of statements to be executed at the end of a loop iteration. The construct is optional.

The block of statements must not contain a return or kill statement.

3.30. Expression statement

primary_expression
  : (IDENT NAMESPACE)* IDENT
  | type_decl PAREN_LEFT argument_expression_list PAREN_RIGHT
  | const_literal
  | paren_rhs_stmt
  | CAST LESS_THAN type_decl GREATER_THAN paren_rhs_stmt
      OpConvertFToU
      OpConvertFToS
      OpConvertSToF
      OpConvertUToF
      OpUConvert
      OpSConvert
      OpFConvert
  | AS LESS_THAN type_decl GREATER_THAN paren_rhs_stmt
      OpBitcast

postfix_expression
  :
  | BRACKET_LEFT logical_or_expression BRACKET_RIGHT postfix_expression
  | PAREN_LEFT argument_expression_list* PAREN_RIGHT postfix_expression
  | PERIOD IDENT postfix_expression

argument_expression_list
  : (logical_or_expression COMMA)* logical_or_expression

unary_expression
  : singular_expression
  | MINUS unary_expression
      OpSNegate
      OpFNegate
  | BANG unary_expression
      OpNot

singular_expression
  : primary_expression postfix_expression

multiplicative_expression
  : unary_expression
  | multiplicative_expression STAR unary_expression
      OpVectorTimesScalar
      OpMatrixTimesScalar
      OpVectorTimesMatrix
      OpMatrixTimesVector
      OpMatrixTimesMatrix
      OpIMul
      OpFMul
  | multiplicative_expression FORWARD_SLASH unary_expression
      OpUDiv
      OpSDiv
      OpFDiv
  | multiplicative_expression MODULO unary_expression
      OpUMOd
      OpSMod
      OpFMod

additive_expression
  : multiplicative_expression
  | additive_expression PLUS multiplicative_expression
      OpIAdd
      OpFAdd
  | additive_expression MINUS multiplicative_expression
      OpFSub
      OpISub

shift_expression
  : additive_expression
  | shift_expression SHIFT_LEFT additive_expression
        OpShiftLeftLogical
  | shift_expression LOGICAL_SHIFT_RIGHT additive_expression
        OpShiftRightLogical
  | shift_expression ARITH_SHIFT_RIGHT additive_expression
        OpShiftRightArithmetic

relational_expression
  : shift_expression
  | relational_expression LESS_THAN shift_expression
        OpULessThan
        OpFOrdLessThan
  | relational_expression GREATER_THAN shift_expression
        OpUGreaterThan
        OpFOrdGreaterThan
  | relational_expression LESS_THAN_EQUAL shift_expression
        OpULessThanEqual
        OpFOrdLessThanEqual
  | relational_expression GREATER_THAN_EQUAL shift_expression
        OpUGreaterThanEqual
        OpFOrdGreaterThanEqual

equality_expression
  : relational_expression
  | relational_expression EQUAL_EQUAL relational_expression
        OpIEqual
        OpFOrdEqual
  | relational_expression NOT_EQUAL relational_expression
        OpINotEqual
        OpFOrdNotEqual

and_expression
  : equality_expression
  | and_expression AND equality_expression
       OpBitwiseAnd

exclusive_or_expression
  : and_expression
  | exclusive_or_expression XOR and_expression
       OpBitwiseXor

inclusive_or_expression
  : exclusive_or_expression
  | inclusive_or_expression OR exclusive_or_expression
       OpBitwiseOr

logical_and_expression
  : inclusive_or_expression
  | logical_and_expression AND_AND inclusive_or_expression
      OpLogicalAnd

logical_or_expression
  : logical_and_expression
  | logical_or_expression OR_OR logical_and_expression
      OpLogicalOr

assignment_stmt
  : singular_expression EQUAL logical_or_expression
      If singular_expression is a variable, this maps to OpStore to the variable.
      Otherwise, singular expression is a pointer expression in an Assigning (L-value) context
      which maps to OpAccessChain followed by OpStore

3.31. Literal Statement

const_literal
  : INT_LITERAL
  | UINT_LITERAL
  | FLOAT_LITERAL
  | TRUE
  | FALSE

const_expr
  : type_decl PAREN_LEFT (const_expr COMMA)? const_expr PAREN_RIGHT
  | const_literal
EXAMPLE: Constants
-1
   %a = OpConstant %int -1

2
   %b = OpConstant %uint 2

3.2
   %c = OpConstant %float 3.2

true
    %d = OpConstantTrue

false
    %e = OpConstant False

vec4<f32>(1.2, 2.3, 3.4, 2.3)
    %f0 = OpConstant %float 1.2
    %f1 = OpConstant %float 2.3
    %f2 = OpConstant %float 3.4
     %f = OpConstantComposite %v4float %f0 %f1 %f2 %f1

3.32. Return statement

return_stmt
  : RETURN logical_or_expression?

A return statement ends execution of the current function. If the function is an entry point, then the current shader invocation is terminated. Otherwise, evaluation continues with the next expression or statement after the evaluation of the call site of the current function invocation.

If the return type of the function is the void type, then the return statement must not have an expression. Otherwise the expression must be present, and is called the return value. In this case the call site of this function invocation evaluates to the return value. The type of the return value must match the return type of the function.

4. Validation

Each validation item will be given a unique ID and a test must be provided when the validation is added. The tests will reference the validation ID in the test name.

5. Type Checking

Type checking is the process of mapping terms in the WGSL source language to § 2 Formal Type Definitions.

Generally, we start by determining types for the smallest WGSL source phrases, and then build up via combining rules.

If we can derive a type for the whole WGSL source program via the type rules, then we say the program is well-typed. Otherwise there is a type error and is not a valid WGSL program.

(dneto) complete

5.1. Preamble for those familiar with formal type checking

Much of it can be bottom-up, like usual.

The interesting bit is that the type of a pointer expression is either straightforward pointer type itself, or the pointee type, depending on its § 2.11 Pointer evaluation context:

5.2. How to read the rules

A type assertion is a mapping from some WGSL source expression to an WGSL type. When we write

e : T

we are saying the WGSL expression e is of type T In the rules below, the WGSL source expression will often have placeholders in italics that represent sub-expressions in the grammar.

In the following tables, each row represents a type deduction rule: If the conditions in the precondition column are satisfied, then the type assertion in the conclusion column is also satisfied.

For convenience, we will use the following shorthands:

Scalar § 2.2 Scalar Types, one of bool, i32, u32, f32
BoolVec § 2.3 Vector Types with bool component
Int i32 or u32
IntVec § 2.3 Vector Types with an Int component
Integral Int or § 2.3 Vector Types with an Int component
FloatVec § 2.3 Vector Types with f32 component
Floating f32 or FloatVec
Arity(T) number of components in § 2.3 Vector Types T

(dneto): Do we have to explicitly list the type environment Gamma? That’s confusing to newcomers.

5.3. Literal and unary expression type rules

Scalar literal type rules
Precondition Conclusion Notes
true : bool OpConstantTrue %bool
false : bool OpConstantFalse %bool
INT_LITERAL : i32 OpConstant %int literal
UINT_LITERAL : u32 OpConstant %uint literal
FLOAT_LITERAL : f32 OpConstant %float literal
Boolean constructor type rules
Precondition Conclusion Notes
e : bool bool(e) : bool Pass-through (OpCopyObject)
Numeric scalar constructor type rules
Precondition Conclusion Notes
e : i32 i32(e) : i32 Pass-through (OpCopyObject)
e : u32 i32(e) : i32 Reinterpretation of bits (OpBitcast)
e : f32 i32(e) : i32 Value conversion, including invalid cases (OpConvertFToS)
e : i32 u32(e) : u32 Reinterpretation of bits (OpBitcast)
e : u32 u32(e) : u32 Pass-through (OpCopyObject)
e : f32 u32(e) : u32 Value conversion, including invalid cases (OpConvertFToU)
e : i32 f32(e) : f32 Value conversion, including invalid cases (OpConvertSToF)
e : u32 f32(e) : f32 Value conversion, including invalid cases (OpConvertUToF)
e : f32 f32(e) : f32 Pass-through (OpCopyObject)
Vector constructor type rules, where T is a scalar type
Precondition Conclusion Notes
e1 : T
e2 : T
vec2<T>(e1,e2) : vec2<T> OpCompositeConstruct
e1 : T
e2 : T
e3 : T
vec3<T>(e1,e2,e3) : vec3<T> OpCompositeConstruct
e1 : T
e2 : T
e3 : T
e4 : T
vec4<T>(e1,e2,e3,e4) : vec4<T> OpCompositeConstruct
e1 : T
e2 : vec2<T>
vec3<T>(e1,e2) : vec3<T>
vec3<T>(e2,e1) : vec3<T>
OpCompositeConstruct
e1 : T
e2 : T
e3 : vec2<T>
vec4<T>(e1,e2,e3) : vec4<T>
vec4<T>(e1,e3,e2) : vec4<T>
vec4<T>(e3,e1,e2) : vec4<T>
OpCompositeConstruct
e1 : vec2<T>
e2 : vec2<T>
vec4<T>(e1,e2) : vec4<T> OpCompositeConstruct
e1 : T
e2 : vec3<T>
vec4<T>(e1,e2) : vec4<T>
vec4<T>(e2,e1) : vec4<T>
OpCompositeConstruct
Matrix constructor type rules
Precondition Conclusion Notes
e1 : vec2
e2 : vec2
e3 : vec2
e4 : vec2
mat2x2<f32>(e1,e2) : mat2x2
mat3x2<f32>(e1,e2,e3) : mat3x2
mat4x2<f32>(e1,e2,e3,e4) : mat4x2
Column by column construction.
OpCompositeConstruct
e1 : vec3
e2 : vec3
e3 : vec3
e4 : vec3
mat2x3<f32>(e1,e2) : mat2x3
mat3x3<f32>(e1,e2,e3) : mat3x3
mat4x3<f32>(e1,e2,e3,e4) : mat4x3
Column by column construction.
OpCompositeConstruct
e1 : vec4
e2 : vec4
e3 : vec4
e4 : vec4
mat2x4<f32>(e1,e2) : mat2x4
mat3x4<f32>(e1,e2,e3) : mat3x4
mat4x4<f32>(e1,e2,e3,e4) : mat4x4
Column by column construction.
OpCompositeConstruct
Unary operators
Precondition Conclusion Notes
e : T, T is Integral -e : T OpSNegate
e : T, T is Floating -e : T OpFNegate
e : bool !e : bool OpLogicalNot
e : BoolVec any(e) : bool OpAny
e : BoolVec all(e) : bool OpAll
e : f32 is_nan(e) : bool OpIsNan
e : T, T is FloatVec is_nan(e) : bool<N>, where N = Arity(T) OpIsNan
e : f32 is_inf(e) : bool OpIsInf
e : T, T is FloatVec is_inf(e) : bool<N>, where N = Arity(T) OpIsInf
e : f32 is_finite(e) : bool OpIsFinite
e : T, T is FloatVec is_finite(e) : bool<N>, where N = Arity(T) OpIsFinite
e : f32 is_normal(e) : bool OpIsNormal
e : T, T is FloatVec is_normal(e) : bool<N>, where N = Arity(T) OpIsNormal

(dneto): remaining unary operators

6. Glossary

Term Definition
Dominates Basic block A dominates basic block B if:
  • A and B are both in the same function F

  • Every control flow path in F that goes to B must also to through A

Strictly dominates A strictly dominates B if A dominates B and A != B
DomBy(A) The basic blocks dominated by A

Conformance

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

References

Normative References

[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119

Issues Index

(dneto): Complete description of Array<E,N>
(dneto): the last element of a struct defining the contents of a storage buffer.
(dneto) also lifetime.
(dsinclair) Write out precedence rules. Matches c and glsl rules ....
(dneto): MatrixStride, RowMajor, ColMajor layout decorations are needed for matrices.
(dneto) complete
(dneto): Do we have to explicitly list the type environment Gamma? That’s confusing to newcomers.
(dneto): remaining unary operators