A WGSL front end: shader source in, validated intermediate representation and SPIR-V out.
| It does | It does not |
|---|---|
| Read WGSL into an abstract syntax tree, with diagnostics that carry a line and a column | Create devices, adapters or queues |
| Lower it to an intermediate representation: types, constants, globals, functions, expressions and statements, in arenas | Talk 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 declares | Own the WebGPU API types; the descriptors stay in moonwgpu/types |
| Write the module back as WGSL | Link, load or dispatch shaders |
| Write the module as a SPIR-V binary | Promise compatibility with any other compiler's internal representation |
///|
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("))
}///|
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)
}| Package | What is in it |
|---|---|
| moonnaga | the intermediate representation, and the pass that builds it from source |
| moonnaga/front/wgsl | lexer, parser, lowering: WGSL text in, a module out |
| moonnaga/valid | the validation rules and the capability record |
| moonnaga/back/wgsl | the module back out as WGSL text |
| moonnaga/back/spv | the module out as a SPIR-V binary |
| moonnaga/compile | the four stages behind one import, for a caller that wants the pipeline rather than a stage |
| moonnaga/conformance | the snapshot replay against another compiler's recorded output |
///|
test {
let result = @compile.parse("fn f() { let x = ; }")
assert_eq(result is Err(_), true)
}| Reason | Cases |
|---|---|
| atomicCompareExchangeWeak is not implemented | abstract-types-atomic, atomicOps, atomicOps-int64 |
| textureAtomicMax and the other texture atomics are not implemented | atomicTexture, atomicTexture-int64 |
| atomicCompareExchangeWeak in a longer expression | atomicCompareExchange, 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, textureSampleBaseClampToEdge | f16, math-functions, subgroup-operations, image, texture-external |
| A pointer argument in a call expression | pointer-function-arg, access |
| A matrix constructor whose arguments are neither all columns nor all scalars | constructors |
| const_assert over select, which the folder does not evaluate | select |
| A continue or break inside a continuing block that reads a variable of the outer loop body | break-if |
| A let whose initialiser is a compound expression the parser rejects | abstract-types-var |
| Cause | Why the text differs |
|---|---|
| Constant folding | The recording has const initialisers folded through, and array lengths replaced with literals; this front end keeps the expression the source wrote |
| Expression ordering | The recording hoists every side-effecting expression into let _eN temporaries; this writer inlines a pure expression at each use |
| Name disambiguation | Both rename a second uv to uv_1, but the counters differ once a temporary is introduced on one side only |
| Attribute layout | The 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 order | The recording emits structs, then constants, then globals, then functions; so does this writer, but the recording first drops what nothing refers to |
| Example | What it shows |
|---|---|
| src/examples/01-compile | read, validate and write back one compute shader |
| src/examples/02-spirv | the 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.spvpub(all) enum AddressSpace {
Function
Private
WorkGroup
Uniform
Storage(StorageAccess)
PushConstant
Handle
} derive(Eq, Hash, Debug)pub(all) struct AtomicStatement {
fun : AtomicFunction
pointer : Handle
value : Handle
result : Handle
} derive(Debug)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)pub(all) struct DerivativeExpr {
axis : DerivativeAxis
ctrl : DerivativeControl
expr : Handle
} derive(Debug)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)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)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)pub(all) struct FunctionArgument {
name : String?
ty : Handle
binding : Binding?
interpolate : InterpolationBinding?
} derive(Debug)pub(all) struct FunctionResult {
ty : Handle?
binding : Binding?
interpolate : InterpolationBinding?
} derive(Debug)pub(all) struct GlobalVariable {
name : String?
space : AddressSpace
binding : ResourceBinding?
ty : Handle
init : Handle?
} derive(Debug)pub(all) struct ImageSampleExpr {
image : Handle
sampler : Handle
gather : SwizzleComponent?
coordinate : Handle
array_index : Handle?
offset : Handle?
level : SampleLevel
depth_ref : Handle?
} derive(Debug)pub(all) struct ImageType {
dim : ImageDimension
arrayed : Bool
class : ImageClass
} derive(Eq, Debug)pub(all) struct InterpolationBinding {
interpolation : Interpolation
sampling : Sampling?
} derive(Eq, Debug)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)pub(all) struct MatrixType {
columns : VectorSize
rows : VectorSize
scalar : Scalar
} derive(Eq, Debug)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)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)pub(all) struct StructMember {
name : String
ty : Handle
binding : Binding?
offset : Int
interpolate : InterpolationBinding?
} derive(Debug)pub(all) struct SwitchCase {
value : SwitchValue
body : Array[Statement]
fall_through : Bool
} derive(Debug)pub(all) struct SwizzleExpr {
size : VectorSize
vector : Handle
pattern : Array[SwizzleComponent]
} derive(Debug)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)pub(all) struct ValuePointerType {
size : VectorSize?
scalar : Scalar
space : AddressSpace
} derive(Eq, Debug)fn vector_alignment(width : Int, count : Int) -> IntInstall
Download zipA WGSL front end: shader source in, validated intermediate representation and SPIR-V out.