moonnaga

    A WGSL front end: shader source in, validated intermediate representation and SPIR-V out.

    wgsl
    shader
    spir-v
    spirv
    wgpu
    webgpu
    compiler
    parser
    validator
    translator
    graphics
    gpu
    vulkan
    metal
    hlsl
    msl
    glsl
    binding
    entry point
    reflection
    Download zip
    Version
    0.0.1
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    1

    No dependencies

    #moonnaga

    The WGSL front end for MoonBit: shader source in, a validated intermediate representation out, and SPIR-V or WGSL for the targets a driver takes.

    A compiler, in four passes: parse, lower, validate, write. It implements the language the WebGPU specification binds — WGSL — and the validation rules a shader module has to satisfy before a device may run it.

    #What it does

    It doesIt does not
    Read WGSL into an abstract syntax tree, with diagnostics that carry a line and a columnCreate devices, adapters or queues
    Lower it to an intermediate representation: types, constants, globals, functions, expressions and statements, in arenasTalk to Vulkan, Metal, D3D12 or GL; that is the hal side of moonwgpu
    Validate a module against the language and the feature set the caller declaresOwn the WebGPU API types; the descriptors stay in moonwgpu/types
    Write the module back as WGSLLink, load or dispatch shaders
    Write the module as a SPIR-V binaryPromise compatibility with any other compiler's internal representation

    #Use

    ///|
    test {
    let source =
    #|@compute @workgroup_size(64)
    #|fn add(@builtin(global_invocation_id) id: vec3<u32>) {
    #| let i = id.x;
    #|}
    let shader = match @compile.parse(source) {
    Ok(shader) => shader
    Err(error) => {
    // `error.line` and `error.column` say where, `error.message` says what.
    abort(error.message)
    }
    }
    let text = @compile.write_wgsl(shader)
    assert_true(text.contains("fn add("))
    }

    SPIR-V, once the module validates:

    ///|
    test {
    let source =
    #|@compute @workgroup_size(1)
    #|fn main() { }
    let shader = match @compile.parse(source) {
    Ok(shader) => shader
    Err(_) => abort("the shader does not parse")
    }
    let info = match @compile.validate(shader) {
    Ok(info) => info
    Err(_) => abort("the shader does not validate")
    }
    let bytes = @compile.write_spirv(shader, info) catch {
    _ => abort("the shader is not translatable")
    }
    assert_eq(bytes[0], 0x03)
    }

    #Packages

    One package per stage, so a build that only needs the front end does not carry a writer.

    PackageWhat is in it
    moonnagathe intermediate representation, and the pass that builds it from source
    moonnaga/front/wgsllexer, parser, lowering: WGSL text in, a module out
    moonnaga/validthe validation rules and the capability record
    moonnaga/back/wgslthe module back out as WGSL text
    moonnaga/back/spvthe module out as a SPIR-V binary
    moonnaga/compilethe four stages behind one import, for a caller that wants the pipeline rather than a stage
    moonnaga/conformancethe snapshot replay against another compiler's recorded output

    #The representation

    An arena of types, constants, global variables, functions, expressions and statements. Expressions are flat: a node names its operands by handle, in evaluation order, which is what lets a writer decide where a temporary is needed without walking the same subtree twice.

    • Types: scalars, vectors, matrices, atomics, pointers, arrays, structs, images, samplers, binding arrays.
    • Expressions: literals, constants, composition, access, load, arithmetic, the math functions, texture sampling and queries, conversions.
    • Statements: emit, block, if, switch, loop, break, continue, return, discard, barriers, store, call, atomics.

    Each function carries the type of every expression and, when it is a pointer, the address space it points into. A back end needs both: x[i] addresses an array and x.y a struct member, and the expression itself does not say which.

    #Diagnostics

    parse returns the module or one diagnostic: a message, a span, and the line and column a reader would point at.

    ///|
    test {
    let result = @compile.parse("fn f() { let x = ; }")
    assert_eq(result is Err(_), true)
    }

    Validation reports the declaration at fault: the function, the global or the type, plus a message naming the rule.

    #Conformance

    The snapshot corpus is the WGSL test suite of another compiler, transcribed: 74 shaders that come with a recorded WGSL round-trip output. Each case is read, validated and written back, and the text is compared with the recording byte for byte. scripts/gen_snapshot_corpus.py embeds the corpus; the replay lives in moonnaga/conformance.

    Identical: 4 of 74. The four that agree are array-in-function-return-type, empty, empty-if and multiview. The rest split into two groups.

    Refused, 24 cases — the front end stops before writing anything:

    ReasonCases
    atomicCompareExchangeWeak is not implementedabstract-types-atomic, atomicOps, atomicOps-int64
    textureAtomicMax and the other texture atomics are not implementedatomicTexture, atomicTexture-int64
    atomicCompareExchangeWeak in a longer expressionatomicCompareExchange, atomicCompareExchange-int64
    A struct-typed alias used as a constructor (Vec2, FVec3)module-scope, type-alias
    An alias to a matrix used as a constructor (mat4x3f)operators
    vec2h, modf, subgroupBarrier, textureSampleBaseClampToEdgef16, math-functions, subgroup-operations, image, texture-external
    A pointer argument in a call expressionpointer-function-arg, access
    A matrix constructor whose arguments are neither all columns nor all scalarsconstructors
    const_assert over select, which the folder does not evaluateselect
    A continue or break inside a continuing block that reads a variable of the outer loop bodybreak-if
    A let whose initialiser is a compound expression the parser rejectsabstract-types-var

    Differed, 46 cases — both sides produce a module, the text differs. The causes are structural rather than semantic:

    CauseWhy the text differs
    Constant foldingThe recording has const initialisers folded through, and array lengths replaced with literals; this front end keeps the expression the source wrote
    Expression orderingThe recording hoists every side-effecting expression into let _eN temporaries; this writer inlines a pure expression at each use
    Name disambiguationBoth rename a second uv to uv_1, but the counters differ once a temporary is introduced on one side only
    Attribute layoutThe recording puts @vertex on a line of its own with a trailing space; this writer does the same, but a one-element @workgroup_size(64) is written (64, 1, 1) here
    Declaration orderThe recording emits structs, then constants, then globals, then functions; so does this writer, but the recording first drops what nothing refers to

    None of these change what a driver would run, and none is a difference in acceptance: every case the front end accepts produces a module that this library's own validator accepts.

    #SPIR-V

    moonnaga/back/spv writes SPIR-V 1.3. The output of the shipped example passes spirv-val --target-env vulkan1.1; the CI workflow runs that check on every push for the shaders the examples compile.

    What the writer covers: scalar, vector, matrix and struct types, buffers in the uniform and storage spaces (wrapping a bare array in a struct, which Vulkan requires), constants, access chains, loads, stores, arithmetic, comparisons, selections, the GLSL.std.450 math functions, function calls, structured control flow, entry point interfaces (arguments read from and results written to global variables, since a Vulkan entry point takes no parameters).

    What it refuses, by name, rather than guessing: atomics, textureStore, derivatives, arrayLength, workgroup uniform loads, pipeline constants and binding arrays.

    #Examples

    ExampleWhat it shows
    src/examples/01-compileread, validate and write back one compute shader
    src/examples/02-spirvthe same shader as a SPIR-V binary, printed as hex

    moon run src/examples/01-compile moon run src/examples/02-spirv | xxd -r -p > add.spv spirv-val add.spv

    #Limits

    • No GLSL or HLSL front end, and no SPIR-V front end: nothing in the stack produces those, and the WebGPU API takes WGSL only.
    • The MSL and HLSL writers are not here yet; the representation and the SPIR-V writer are what the native backends of moonwgpu need first.
    • Sampled texture types assume f32 texels; an integer texture bound through a sampled handle is not distinguished yet.

    #Licence

    Apache-2.0. See LICENSE.

    AccelerationStructureType

    pub(all) struct AccelerationStructureType {
    vertex_return : Bool
    } derive(Eq,
    Debug
    )

    AccessExpr

    pub(all) struct AccessExpr {
    base : Handle
    index : Handle
    } derive(
    Debug
    )

    AccessIndexExpr

    pub(all) struct AccessIndexExpr {
    base : Handle
    index : Int
    } derive(
    Debug
    )

    AddressSpace

    pub(all) enum AddressSpace {
    Function
    Private
    WorkGroup
    Uniform
    Storage(StorageAccess)
    PushConstant
    Handle
    } derive(Eq, Hash,
    Debug
    )

    Where a variable lives, which is what decides who may write it and how it reaches the GPU.

    Arena

    pub(all) struct Arena[T] {
    items : Array[T]
    }

    A dense, append-only store, which is how the module keeps types, constants, globals, functions, expressions and statements addressable.

    Nothing is ever removed: the front end appends, and a later pass rewrites entries in place. Order is insertion order, and it is load-bearing — the writers walk the arenas in that order, so a module that has been compacted writes out differently from one that has not.

    Arena::add

    fn[T] Arena::add(self : Arena[T], value : T) -> Handle

    Arena::compact

    fn[T] Arena::compact(self : Arena[T], keep : (Handle, T) -> Bool) -> (Arena[T], Array[Int])

    Rebuilds the arena from the entries keep selects, remapping handles.

    The writers name temporaries after handle indices, so a module that still holds entries nobody refers to writes out with gaps in those names. A compaction pass drops the unreachable entries first; this is the mechanism it uses, and the remap table it returns is how the caller rewrites its own references.

    Arena::each

    fn[T] Arena::each(self : Arena[T], visit : (Handle, T) -> Unit) -> Unit

    Walks the arena in index order, handing out the handle and the entry.

    Arena::find

    fn[T] Arena::find(self : Arena[T], pred : (T) -> Bool) -> Handle?

    The index of the first entry for which pred holds.

    Arena::get

    fn[T] Arena::get(self : Arena[T], handle : Handle) -> T

    Arena::get_or

    fn[T] Arena::get_or(self : Arena[T], handle : Handle, fallback : T) -> T

    Arena::is_empty

    fn[T] Arena::is_empty(self : Arena[T]) -> Bool

    Arena::iter

    fn[T] Arena::iter(self : Arena[T]) -> Iter[T]

    Arena::len

    fn[T] Arena::len(self : Arena[T]) -> Int

    Arena::new

    fn[T] Arena::new() -> Arena[T]

    Arena::set

    fn[T] Arena::set(self : Arena[T], handle : Handle, value : T) -> Unit

    ArraySize

    pub(all) enum ArraySize {
    Fixed(Int)
    Override
    Dynamic
    } derive(Eq,
    Debug
    )

    The length of an array.

    ArrayType

    pub(all) struct ArrayType {
    base : Handle
    size : ArraySize
    stride : Int
    } derive(Eq,
    Debug
    )

    AsExpr

    pub(all) struct AsExpr {
    expr : Handle
    kind : ScalarKind
    convert : Int?
    } derive(
    Debug
    )

    AsType

    pub(all) struct AsType {
    kind : ScalarKind
    convert : Int?
    } derive(Eq,
    Debug
    )

    A conversion from one scalar kind or width to another.

    AtomicFunction

    pub(all) enum AtomicFunction {
    AtomicAdd
    AtomicSubtract
    AtomicAnd
    AtomicExclusiveOr
    AtomicInclusiveOr
    AtomicMin
    AtomicMax
    AtomicExchange
    AtomicCompareExchangeWeak
    } derive(Eq,
    Debug
    )

    What an atomic operation does to the memory it addresses.

    AtomicResultExpr

    pub(all) struct AtomicResultExpr {
    ty : Handle
    comparison : Bool
    } derive(
    Debug
    )

    AtomicStatement

    pub(all) struct AtomicStatement {
    fun : AtomicFunction
    pointer : Handle
    value : Handle
    result : Handle
    } derive(
    Debug
    )

    BarrierKind

    pub(all) enum BarrierKind {
    Workgroup
    Storage
    Texture
    } derive(Eq,
    Debug
    )

    Which memories a barrier orders.

    BinaryExpr

    pub(all) struct BinaryExpr {
    op : BinaryOperator
    left : Handle
    right : Handle
    } derive(
    Debug
    )

    BinaryOperator

    pub(all) enum BinaryOperator {
    Add
    Subtract
    Multiply
    Divide
    Modulo
    Equal
    NotEqual
    Less
    LessEqual
    Greater
    GreaterEqual
    And
    ExclusiveOr
    InclusiveOr
    LogicalAnd
    LogicalOr
    ShiftLeft
    ShiftRight
    } derive(Eq,
    Debug
    )

    Binding

    pub(all) enum Binding {
    BuiltIn(BuiltIn)
    Location(Int)
    } derive(Eq,
    Debug
    )

    What a struct member or an entry point argument is bound to.

    BindingArrayType

    pub(all) struct BindingArrayType {
    base : Handle
    size : ArraySize
    } derive(Eq,
    Debug
    )

    BuiltIn

    pub(all) enum BuiltIn {
    Position(Bool)
    ViewIndex
    BaseInstance
    BaseVertex
    ClipDistance
    CullDistance
    InstanceIndex
    PointSize
    VertexIndex
    DrawId
    FragDepth
    PointCoord
    FrontFacing
    PrimitiveIndex
    SampleIndex
    SampleMask
    GlobalInvocationId
    LocalInvocationId
    LocalInvocationIndex
    WorkgroupId
    WorkgroupSize
    NumWorkgroups
    NumSubgroups
    SubgroupId
    SubgroupSize
    SubgroupInvocationId
    } derive(Eq, Hash,
    Debug
    )

    A built-in input or output, named by the WebGPU specification.

    CallStatement

    pub(all) struct CallStatement {
    function : Handle
    arguments : Array[Handle]
    result : Handle?
    } derive(
    Debug
    )

    ComposeExpr

    pub(all) struct ComposeExpr {
    ty : Handle
    components : Array[Handle]
    } derive(
    Debug
    )

    ConservativeDepth

    pub(all) enum ConservativeDepth {
    GreaterEqual
    LessEqual
    Unchanged
    } derive(Eq,
    Debug
    )

    Constant

    pub(all) struct Constant {
    name : String?
    ty : Handle
    init : Handle
    } derive(
    Debug
    )

    DerivativeAxis

    pub(all) enum DerivativeAxis {
    X
    Y
    Width
    } derive(Eq,
    Debug
    )

    DerivativeControl

    pub(all) enum DerivativeControl {
    Coarse
    Fine
    None
    } derive(Eq,
    Debug
    )

    DerivativeExpr

    pub(all) struct DerivativeExpr {
    axis : DerivativeAxis
    ctrl : DerivativeControl
    expr : Handle
    } derive(
    Debug
    )

    EarlyDepthTest

    pub(all) struct EarlyDepthTest {
    conservative : ConservativeDepth?
    } derive(Eq,
    Debug
    )

    EntryPoint

    pub(all) struct EntryPoint {
    name : String
    stage : ShaderStage
    early_depth_test : EarlyDepthTest?
    workgroup_size : Array[Int]
    workgroup_size_overrides : Array[Handle?]
    function : Handle
    } derive(
    Debug
    )

    The interface of one entry point, and the function that implements it.

    Expression

    pub(all) enum Expression {
    Literal(Literal)
    Constant(Handle)
    Override(Handle)
    ZeroValue(Handle)
    Compose(ComposeExpr)
    Access(AccessExpr)
    AccessIndex(AccessIndexExpr)
    Splat(SplatExpr)
    Swizzle(SwizzleExpr)
    FunctionArgument(Int)
    GlobalVariable(Handle)
    LocalVariable(Handle)
    Load(Handle)
    ImageSample(ImageSampleExpr)
    ImageLoad(ImageLoadExpr)
    ImageQuery(ImageQueryExpr)
    Unary(UnaryExpr)
    Binary(BinaryExpr)
    Select(SelectExpr)
    Derivative(DerivativeExpr)
    Relational(RelationalExpr)
    Math(MathExpr)
    As(AsExpr)
    CallResult(Handle)
    AtomicResult(AtomicResultExpr)
    WorkGroupUniformLoadResult(Handle)
    ArrayLength(Handle)
    } derive(
    Debug
    )

    One expression of a function or of a constant initialiser.

    Expressions are a flat arena rather than a tree: a node refers to its operands by handle, and the front end appends in evaluation order. That is what lets a writer decide where a temporary is needed without walking the same subtree twice.

    Function

    pub(all) struct Function {
    name : String?
    arguments : Array[FunctionArgument]
    result : FunctionResult
    local_variables : Arena[LocalVariable]
    expressions : Arena[Expression]
    named_expressions : Map[Int, String]
    expr_types : Array[Handle]
    expr_spaces : Array[AddressSpace?]
    body : Array[Statement]
    } derive(
    Debug
    )

    A function, its arena of expressions, and the names the source gave to some of them.

    Function::new

    fn Function::new() -> Function

    FunctionArgument

    pub(all) struct FunctionArgument {
    name : String?
    ty : Handle
    binding : Binding?
    interpolate : InterpolationBinding?
    } derive(
    Debug
    )

    FunctionResult

    pub(all) struct FunctionResult {
    ty : Handle?
    binding : Binding?
    interpolate : InterpolationBinding?
    } derive(
    Debug
    )

    GlobalVariable

    pub(all) struct GlobalVariable {
    name : String?
    space : AddressSpace
    binding : ResourceBinding?
    ty : Handle
    init : Handle?
    } derive(
    Debug
    )

    Handle

    pub(all) struct Handle {
    index : Int
    } derive(Compare, Eq, Hash,
    Debug
    )

    A reference to one entry of an [Arena].

    A handle carries nothing but a position, so it says nothing about which arena issued it. Every use that hands a handle to an arena of another kind is a compiler bug rather than a diagnostic, and is reported as one.

    Handle::new

    fn Handle::new(index : Int) -> Handle

    Handle::to_int

    fn Handle::to_int(self : Handle) -> Int

    IfStatement

    pub(all) struct IfStatement {
    condition : Handle
    accept : Array[Statement]
    reject : Array[Statement]
    } derive(
    Debug
    )

    ImageClass

    pub(all) enum ImageClass {
    Sampling
    Depth
    Storage(StorageAccess, String)
    } derive(Eq, Hash,
    Debug
    )

    The three ways a handle can reach a texture.

    ImageDimension

    pub(all) enum ImageDimension {
    D1
    D2
    D3
    Cube
    } derive(Eq, Hash,
    Debug
    )

    The dimensions of a texture.

    ImageLoadExpr

    pub(all) struct ImageLoadExpr {
    image : Handle
    coordinate : Handle
    array_index : Handle?
    sample : Handle?
    level : Handle?
    } derive(
    Debug
    )

    ImageQueryExpr

    pub(all) struct ImageQueryExpr {
    image : Handle
    query : ImageQueryKind
    } derive(
    Debug
    )

    ImageQueryKind

    pub(all) enum ImageQueryKind {
    Size
    NumLevels
    NumLayers
    NumSamples
    } derive(Eq,
    Debug
    )

    ImageSampleExpr

    pub(all) struct ImageSampleExpr {
    image : Handle
    sampler : Handle
    gather : SwizzleComponent?
    coordinate : Handle
    array_index : Handle?
    offset : Handle?
    level : SampleLevel
    depth_ref : Handle?
    } derive(
    Debug
    )

    ImageStoreStatement

    pub(all) struct ImageStoreStatement {
    image : Handle
    coordinate : Handle
    array_index : Handle?
    value : Handle
    } derive(
    Debug
    )

    ImageType

    pub(all) struct ImageType {
    dim : ImageDimension
    arrayed : Bool
    class : ImageClass
    } derive(Eq,
    Debug
    )

    Interpolation

    pub(all) enum Interpolation {
    Perspective
    Linear
    Flat
    } derive(Eq,
    Debug
    )

    The interpolation a fragment input asks for.

    InterpolationBinding

    pub(all) struct InterpolationBinding {
    interpolation : Interpolation
    sampling : Sampling?
    } derive(Eq,
    Debug
    )

    Layout

    pub(all) struct Layout {
    size : Int
    alignment : Int
    } derive(Eq,
    Debug
    )

    Literal

    pub(all) enum Literal {
    F64(Double)
    F32(Float)
    U32(UInt)
    I32(Int)
    U64(UInt64)
    I64(Int64)
    Bool(Bool)
    AbstractInt(Int64)
    AbstractFloat(Double)
    } derive(Eq,
    Debug
    )

    A literal as the front end read it. The abstract forms are the ones WGSL gives to an unsuffixed number literal before it is forced into a concrete type; they never survive validation.

    LocalVariable

    pub(all) struct LocalVariable {
    name : String?
    ty : Handle
    init : Handle?
    } derive(
    Debug
    )

    LoopStatement

    pub(all) struct LoopStatement {
    body : Array[Statement]
    continuing : Array[Statement]
    break_if : Handle?
    } derive(
    Debug
    )

    MathExpr

    pub(all) struct MathExpr {
    fun : MathFunction
    arg : Handle
    arg1 : Handle?
    arg2 : Handle?
    arg3 : Handle?
    } derive(
    Debug
    )

    MathFunction

    pub(all) enum MathFunction {
    Abs
    Min
    Max
    Clamp
    Saturate
    Cos
    Cosh
    Sin
    Sinh
    Tan
    Tanh
    Acos
    Asin
    Atan
    Atan2
    Asinh
    Acosh
    Atanh
    Radians
    Degrees
    Ceil
    Floor
    Round
    Fract
    Trunc
    Modf
    Frexp
    Ldexp
    Exp
    Exp2
    Log
    Log2
    Pow
    Dot
    Dot4I8Packed
    Dot4U8Packed
    Outer
    Cross
    Distance
    Length
    Normalize
    FaceForward
    Reflect
    Refract
    Sign
    Fma
    Mix
    Step
    SmoothStep
    Sqrt
    InverseSqrt
    Inverse
    Transpose
    Determinant
    QuantizeToF16
    CountTrailingZeros
    CountLeadingZeros
    CountOneBits
    ReverseBits
    ExtractBits
    InsertBits
    FirstTrailingBit
    FirstLeadingBit
    Pack4x8snorm
    Pack4x8unorm
    Pack2x16snorm
    Pack2x16unorm
    Pack2x16float
    Pack4xI8
    Pack4xU8
    Pack4xI8Clamp
    Pack4xU8Clamp
    Unpack4x8snorm
    Unpack4x8unorm
    Unpack2x16snorm
    Unpack2x16unorm
    Unpack2x16float
    Unpack4xI8
    Unpack4xU8
    } derive(Eq,
    Debug
    )

    MatrixType

    pub(all) struct MatrixType {
    columns : VectorSize
    rows : VectorSize
    scalar : Scalar
    } derive(Eq,
    Debug
    )

    Module

    pub(all) struct Module {
    types : Arena[Type]
    constants : Arena[Constant]
    overrides : Arena[Override]
    global_variables : Arena[GlobalVariable]
    functions : Arena[Function]
    entry_points : Array[EntryPoint]
    const_expressions : Arena[Expression]
    special_types : SpecialTypes
    } derive(
    Debug
    )

    A whole shader module: the types, the values at module scope, the functions and the entry points, all in the order the front end saw them.

    Module::components_of

    fn Module::components_of(self : Module, handle : Handle) -> Int?

    How many components a scalar-or-vector type has: one for a scalar.

    Module::is_sized

    fn Module::is_sized(self : Module, handle : Handle) -> Bool

    Whether every value of this type has one size, which decides whether it may be a local, an argument or a struct member that is not the last one.

    Module::layout

    fn Module::layout(self : Module, handle : Handle, round_up : Int) -> Layout

    The size and alignment of a type, following the uniform-buffer layout rules of the WGSL specification.

    Module::new

    fn Module::new() -> Module

    Module::scalar_of

    fn Module::scalar_of(self : Module, handle : Handle) -> Scalar?

    The scalar a scalar-or-vector type is made of.

    Module::size_of

    fn Module::size_of(self : Module, handle : Handle) -> Int

    The number of bytes one value of this type occupies in a buffer, as an integer when the type has one.

    Module::type_inner

    fn Module::type_inner(self : Module, handle : Handle) -> TypeInner

    Module::type_name

    fn Module::type_name(self : Module, handle : Handle) -> String

    The name of a type as WGSL writes it, which is what diagnostics quote.

    Override

    pub(all) struct Override {
    name : String
    ty : Handle
    init : Handle?
    } derive(
    Debug
    )

    A pipeline-overridable constant: a value the module leaves open for the pipeline to fill in.

    PointerType

    pub(all) struct PointerType {
    base : Handle
    space : AddressSpace
    } derive(Eq,
    Debug
    )

    RayQueryType

    pub(all) struct RayQueryType {
    vertex_return : Bool
    } derive(Eq,
    Debug
    )

    RelationalExpr

    pub(all) struct RelationalExpr {
    fun : RelationalFunction
    argument : Handle
    } derive(
    Debug
    )

    RelationalFunction

    pub(all) enum RelationalFunction {
    All
    Any
    IsNan
    IsInf
    } derive(Eq,
    Debug
    )

    ResourceBinding

    pub(all) struct ResourceBinding {
    group : Int
    binding : Int
    } derive(Eq,
    Debug
    )

    SampleLevel

    pub(all) enum SampleLevel {
    Auto
    Zero
    Exact(Handle)
    Bias(Handle)
    Gradient(Handle, Handle)
    } derive(Eq,
    Debug
    )

    How the level of detail of a sampling operation is chosen.

    SamplerType

    pub(all) struct SamplerType {
    comparison : Bool
    } derive(Eq,
    Debug
    )

    Sampling

    pub(all) enum Sampling {
    Center
    Centroid
    Sample
    First
    Either
    } derive(Eq,
    Debug
    )

    Where in the pixel an interpolated value is taken.

    Scalar

    pub(all) struct Scalar {
    kind : ScalarKind
    width : Int
    } derive(Eq, Hash,
    Debug
    )

    A scalar type: a kind and a width in bytes.

    Scalar::is_abstract

    fn Scalar::is_abstract(self : Scalar) -> Bool

    Whether the width is still open, which is true of the abstract types only.

    Scalar::is_bool

    fn Scalar::is_bool(self : Scalar) -> Bool

    Scalar::is_float

    fn Scalar::is_float(self : Scalar) -> Bool

    Scalar::is_integer

    fn Scalar::is_integer(self : Scalar) -> Bool

    Scalar::new

    fn Scalar::new(kind : ScalarKind, width : Int) -> Scalar

    ScalarKind

    pub(all) enum ScalarKind {
    Sint
    Uint
    Float
    Bool
    AbstractInt
    AbstractFloat
    } derive(Eq, Hash,
    Debug
    )

    The four kinds of scalar WGSL has.

    SelectExpr

    pub(all) struct SelectExpr {
    condition : Handle
    accept : Handle
    reject : Handle
    } derive(
    Debug
    )

    ShaderStage

    pub(all) enum ShaderStage {
    Vertex
    Fragment
    Compute
    Task
    Mesh
    } derive(Eq,
    Debug
    )

    SourceLocation

    pub(all) struct SourceLocation {
    line : Int
    column : Int
    } derive(Eq,
    Debug
    )

    A position in the source text, counting from one, as a reader sees it.

    Span

    pub(all) struct Span {
    start : Int
    end : Int
    } derive(Eq,
    Debug
    )

    A half-open byte range into the source text. The offsets are bytes rather than characters because that is what the lexer tracks, and diagnostics convert them to a line and a column on the way out.

    Span::new

    fn Span::new(start : Int, end : Int) -> Span

    SpecialTypes

    pub(all) struct SpecialTypes {
    atomic_compare_exchange_result : Handle?
    } derive(
    Debug
    )

    SpecialTypes::empty

    fn SpecialTypes::empty() -> SpecialTypes

    SplatExpr

    pub(all) struct SplatExpr {
    size : VectorSize
    value : Handle
    } derive(
    Debug
    )

    Statement

    pub(all) enum Statement {
    Emit(Handle)
    Block(Array[Statement])
    If(IfStatement)
    Switch(SwitchStatement)
    Loop(LoopStatement)
    Break
    Continue
    Return(Handle?)
    Kill
    ControlBarrier(BarrierKind)
    MemoryBarrier(BarrierKind)
    Store(StoreStatement)
    ImageStore(ImageStoreStatement)
    Atomic(AtomicStatement)
    WorkGroupUniformLoad(WorkGroupUniformLoadStatement)
    Call(CallStatement)
    } derive(
    Debug
    )

    One statement of a function body.

    Blocks are statement arrays rather than a nested statement, which keeps the flattening a writer does for if and loop bodies a matter of walking the array it already has.

    StorageAccess

    pub(all) enum StorageAccess {
    Read
    Write
    ReadWrite
    } derive(Eq, Hash,
    Debug
    )

    The access a storage buffer was declared with.

    StorageAccess::may_load

    fn StorageAccess::may_load(self : StorageAccess) -> Bool

    StorageAccess::may_store

    fn StorageAccess::may_store(self : StorageAccess) -> Bool

    StoreStatement

    pub(all) struct StoreStatement {
    pointer : Handle
    value : Handle
    } derive(
    Debug
    )

    StructMember

    pub(all) struct StructMember {
    name : String
    ty : Handle
    binding : Binding?
    offset : Int
    interpolate : InterpolationBinding?
    } derive(
    Debug
    )

    StructType

    pub(all) struct StructType {
    members : Array[StructMember]
    span : Int
    } derive(
    Debug
    )

    SwitchCase

    pub(all) struct SwitchCase {
    value : SwitchValue
    body : Array[Statement]
    fall_through : Bool
    } derive(
    Debug
    )

    SwitchStatement

    pub(all) struct SwitchStatement {
    selector : Handle
    cases : Array[SwitchCase]
    } derive(
    Debug
    )

    SwitchValue

    pub(all) enum SwitchValue {
    I32(Int)
    U32(UInt)
    I64(Int64)
    U64(UInt64)
    Default
    } derive(Eq,
    Debug
    )

    The value a case of a switch selects on.

    SwizzleComponent

    pub(all) enum SwizzleComponent {
    X
    Y
    Z
    W
    } derive(Eq,
    Debug
    )

    SwizzleComponent::to_int

    fn SwizzleComponent::to_int(self : SwizzleComponent) -> Int

    SwizzleExpr

    pub(all) struct SwizzleExpr {
    size : VectorSize
    vector : Handle
    pattern : Array[SwizzleComponent]
    } derive(
    Debug
    )

    Type

    pub(all) struct Type {
    name : String?
    inner : TypeInner
    } derive(
    Debug
    )

    A named type. A named entry is what WGSL can write down; an anonymous one is what the front end synthesises for images, matrices and the like.

    Type::new

    fn Type::new(name : String?, inner : TypeInner) -> Type

    TypeInner

    pub(all) enum TypeInner {
    Scalar(Scalar)
    Vector(VectorType)
    Matrix(MatrixType)
    Atomic(Scalar)
    Pointer(PointerType)
    ValuePointer(ValuePointerType)
    Array(ArrayType)
    Struct(StructType)
    Image(ImageType)
    Sampler(SamplerType)
    AccelerationStructure(AccelerationStructureType)
    RayQuery(RayQueryType)
    BindingArray(BindingArrayType)
    } derive(
    Debug
    )

    What a type is. A struct's name lives in its [Type] rather than here, so two structs are the same type only if they are the same entry.

    TypeInner::is_data

    fn TypeInner::is_data(self : TypeInner) -> Bool

    Whether the value of this type can be held in a variable, passed by value or stored in a buffer. Opaque handles, pointers and unsized arrays cannot.

    TypeInner::is_sized

    fn TypeInner::is_sized(self : TypeInner) -> Bool

    TypeInner::name

    fn TypeInner::name(self : TypeInner) -> String

    The outermost type name a reader would recognise, for diagnostics.

    UnaryExpr

    pub(all) struct UnaryExpr {
    op : UnaryOperator
    expr : Handle
    } derive(
    Debug
    )

    UnaryOperator

    pub(all) enum UnaryOperator {
    Negate
    LogicalNot
    BitwiseNot
    } derive(Eq,
    Debug
    )

    ValuePointerType

    pub(all) struct ValuePointerType {
    size : VectorSize?
    scalar : Scalar
    space : AddressSpace
    } derive(Eq,
    Debug
    )

    VectorSize

    pub(all) enum VectorSize {
    Bi
    Tri
    Quad
    } derive(Compare, Eq, Hash,
    Debug
    )

    How many components a vector has.

    VectorSize::from_int

    fn VectorSize::from_int(count : Int) -> VectorSize?

    The vector size with that many components, if there is one.

    VectorSize::to_int

    fn VectorSize::to_int(self : VectorSize) -> Int

    VectorType

    pub(all) struct VectorType {
    size : VectorSize
    scalar : Scalar
    } derive(Eq,
    Debug
    )

    WorkGroupUniformLoadStatement

    pub(all) struct WorkGroupUniformLoadStatement {
    pointer : Handle
    result : Handle
    } derive(
    Debug
    )

    align_to

    fn align_to(value : Int, alignment : Int) -> Int

    boolean

    fn boolean() -> Scalar

    float

    fn float(width : Int) -> Scalar

    location_of

    fn location_of(text : StringView, offset : Int) -> SourceLocation

    scalar_bool

    let scalar_bool : Scalar

    scalar_f32

    let scalar_f32 : Scalar

    scalar_f64

    let scalar_f64 : Scalar

    scalar_i32

    let scalar_i32 : Scalar

    scalar_i64

    let scalar_i64 : Scalar

    scalar_name

    fn scalar_name(scalar : Scalar) -> String

    scalar_u32

    let scalar_u32 : Scalar

    scalar_u64

    let scalar_u64 : Scalar

    sint

    fn sint(width : Int) -> Scalar

    uint

    fn uint(width : Int) -> Scalar

    vector_alignment

    fn vector_alignment(width : Int, count : Int) -> Int

    The alignment a vector of count components of that width has: the size rounded up to a power of two, which is what makes a vec3 align like a vec4.