gogpu/naga 是一个托管在 GitHub 上的开源项目,主要使用 Go 编写,采用 MIT License 许可证,目前获得 61 个 Star、15 次 Fork。
仓库全名
gogpu/naga
README 摘要
naga Pure Go Shader Compiler WGSL to SPIR-V, MSL, GLSL, HLSL, and DXIL; WGSL, SPIR-V and Vulkan GLSL share one IR. Zero CGO. Part of the GoGPU ecosystem Overview naga is a shader compiler written entirely in Go. It compiles WGSL (WebGPU Shading Language) to multiple backend formats without requiring CGO or external dependencies, reads SPIR-V binaries into its IR (spirv.Parse), and parses Vulkan GLSL 440/450/460 with…
naga is a shader compiler written entirely in Go. It compiles WGSL (WebGPU Shading Language) to multiple backend formats without requiring CGO or external dependencies, reads SPIR-V binaries into its IR (spirv.Parse), and parses Vulkan GLSL 440/450/460 with glsl.Parse.
Key Features
Category
Capabilities
Input
Full WGSL parser (120+ tokens), 48 short type aliases (vec3f, mat4x4f…), abstract constructors; SPIR-V binaries through spirv.Parse — types, constants, bindings, control flow, calls, images and sampling, atomics, subgroups, combined image samplers, row-major matrix members with their reads and stores, Coherent/Volatile decorations; Vulkan GLSL 440/450/460 through glsl.Parse — its own preprocessor, the texture and image sampling surface with image queries and barriers, combined image samplers split into image + sampler globals; the GL 3.30 core and ES 3.00 dialects with one binding counter per group, ParseOptions.ResourceBindings by source name and plain uniforms collected into one generated std140 block (ParseInfo.DefaultBlock)
Outputs
SPIR-V (checked with spirv-val in CI), MSL, GLSL, HLSL; DXIL — 236 of 267 entry points pass IDxcValidator (experimental)
Ray query types, acceleration structures, 7 ray query builtins
Compatibility
Tested against Rust naga’s WGSL snapshot corpus (172 shaders, gfx-rs/wgpu 14328f49): every output is compared, and each known difference is recorded with its reason — see Rust Naga Compatibility
Build
Zero CGO, single binary
Features
Pure Go — No CGO, no external dependencies
WGSL Frontend — Full lexer and parser (120+ tokens), 48 short type aliases (vec3f, mat4x4f, etc.), abstract constructors (vec3(1,2,3))
GLSL Frontend — glsl.Parse reads Vulkan GLSL 440/450/460 and the GL 3.30 core / ES 3.00 dialects into the same IR under the WGSL frontend’s error contract: its own preprocessor, interface blocks with std140/std430 layouts, storage images, specialization constants, the builtin catalogue including the image and sampling families and the level-of-detail query (textureQueryLod, whose sampler and coordinate travel in the IR’s query), the atomic families (memory and image atomics, compare-exchange included), barriers and texture gather; a combined image sampler (uniform sampler2D) becomes an image global and a sampler global, a source without layout(binding) takes its bindings from one counter per group with ParseOptions.ResourceBindings reserving a resource’s slot by name, and the plain uniforms of a GL 3.30 core or ES 3.00 source are collected into one generated std140 block whose binding, size and member offsets ParseInfo.DefaultBlock reports. Each dialect’s feature gates, ES precision rules and the #extension matrix follow the Khronos specifications, with glslang as the recorded cross-check. MSL and HLSL output matches Rust naga’s naga-cli on the vendored GLSL corpus, with every difference recorded. Preview: the frontend is not complete — the subgroup surface is complete (elect and all-equal, the ballot and its bit operations, the clustered reductions, the ballot-mask variables written on every backend), and the remaining refusals are the Min/Max/And/Or/Xor scans, the atomic-counter barrier, textureGatherOffsets (the IR carries a single constant offset) and imageSamples (multisampled storage images are a class the frontend does not model yet), named in the error; ParseInfo/ParseOptions may still change until the frontend is
Rust Naga Compatibility — every IR, SPIR-V, MSL, GLSL and HLSL output is compared with Rust naga’s on its 172-shader WGSL corpus (SPIR-V by instruction counts); known differences are recorded per output with a reason. 29 own test shaders; 912 golden outputs
IR — Complete intermediate representation (expressions, statements, types)
Swizzle Operations — Full vector swizzle support (.xyz, .rgba, .xxyy, etc.)
Function Calls — OpFunctionCall support for modular WGSL shaders with helper functions
SPIR-V Backend — Vulkan-compatible bytecode generation: integer div/mod safety wrappers, image bounds checking (Restrict/ReadZeroSkipWrite), ray query helpers, loop bounding (on by default), workgroup zero-init polyfill, NonUniform decorations, capability-aware instruction emission
MSL Backend — Metal Shading Language output for macOS/iOS, vertex pulling transform, external textures, function-scope workgroup declarations (no host setThreadgroupMemoryLength needed)
GLSL Backend — OpenGL Shading Language for OpenGL 3.3+, ES 3.0+, dead code elimination, image bounds checking, version-aware layout(binding=N) emission (SupportsExplicitLocations for GL 4.2+/ES 3.1+), UniformInfo reflection for runtime binding fallback on older GL drivers
HLSL Backend — High-Level Shading Language for DirectX 11/12, shader models 5.0–6.7 (FXC and DXC); helpers get one exit where FXC would miscompile an early return
DXIL Backend (experimental) — Direct DXIL generation from naga IR (236 of 267 corpus entry points pass IDxcValidator; 113 of 177 DXC roundtrip comparisons match exactly; gg production shaders: every valid entry point passes; GPU readback corpus on D3D12 with Intel and NVIDIA). LLVM 3.7 bitcode with dx.op intrinsics, DXBC container. Vertex, fragment, compute, and mesh shaders (SM 6.0–6.9). CBV/SRV/UAV (read-only storage as SRV, read-write as UAV), atomics (i32/i64/f32 + image), barriers, ray query (35 intrinsics), wave/subgroup ops (13 intrinsics), texture sampling (8 variants), matrix scalarization, pack/unpack, helper functions. Optimization passes: DCE (liveness through control dependence, dead loops removed), SROA (struct decomposition, aggregate locals split per element), mem2reg (SSA promotion), single-store local promotion, loadInput DCE (per-member backwards reachability), workgroup struct decomposition, function inlining (early-return wrapping), strength reduction (mul→shl, urem→and, sub→add), constant folding. Options.BindingMap for WGSL→DXIL (space, register) remap (wgpu root signature compatibility). Eliminates FXC/DXC dependency. dxil.Compile() API.
Type Conversions — Scalar constructors f32(x), u32(y), i32(z) with correct SPIR-V opcodes
Bitcast — bitcast<T>(expr) for reinterpreting bit patterns between types
Warnings — Unused variable detection with _ prefix exception
The zero value of every options struct is the safe one: SPIR-V 1.0, bounds checks on (Restrict), loops bounded,
workgroup memory zeroed, every binding required, no optional capability. Ask for more explicitly:
opts := naga.CompileOptions{
SPIRV: spirv.Options{Version: spirv.Version1_3}, // subgroup operations need 1.3
Capabilities: valid.CapShaderFloat16, // the device's features
}
spirvBytes, err := naga.CompileWithOptions(source, opts)
A backend never raises the target version a shader needs: it refuses with an error that names the feature and the
version (errors.Is(err, backend.ErrUnsupported)).
CLI Tool
# Install
go install github.com/gogpu/naga/cmd/nagac@latest
# Compile shader
nagac -o shader.spv shader.wgsl
# With debug info
nagac -debug -o shader.spv shader.wgsl
# Show version
nagac -version
Development Tools
# SPIR-V disassembler (debugging shader compilation)
go install github.com/gogpu/naga/cmd/spvdis@latest
spvdis shader.spv
# DXIL validator — Pure Go wrapper around Microsoft IDxcValidator (Windows)
# Calls dxil.dll with zero CGO. Runs a three-layer
# defensive pre-check (DXBC structural + LLVM bitcode metadata walker)
# before handing blobs to IDxcValidator::Validate.
go install github.com/gogpu/naga/cmd/dxilval@latest
dxilval shader.dxil # validate a single container
dxilval --wgsl shader.wgsl # compile through naga, then validate
dxilval --corpus snapshot/testdata/rust/in/wgsl/ # walk a directory, typed-error summary
# Texture shader compile tool (testing)
go install github.com/gogpu/naga/cmd/texture_compile@latest
texture_compile shader.wgsl
Parse, Validate, Write Any Backend
The same steps as Rust naga: parse WGSL to IR, validate it with the device’s capabilities, then hand the module to
any backend. Every backend has the one contract Compile(*ir.Module, Options) (output, TranslationInfo, error).
module, _, err := wgsl.Parse(source, wgsl.ParseOptions{})
if err != nil {
var pe *wgsl.ParseError
if errors.As(err, &pe) {
fmt.Println(pe.Format(source, "shader.wgsl")) // labelled source lines, as Rust naga prints them
}
return err
}
info, err := valid.Validate(module, valid.Options{Capabilities: valid.CapShaderFloat16})
if err != nil {
return err // a valid.Errors: every problem, errors.As finds each *valid.Error
}
_ = info // per entry point: the globals it uses and how (bind group layouts, workgroup size limits)
spirvBytes, _, err := spirv.Compile(module, spirv.Options{}) // Vulkan
mslCode, _, err := msl.Compile(module, msl.Options{}) // Metal
glslCode, _, err := glsl.Compile(module, glsl.Options{LangVersion: glsl.Version450}) // OpenGL; one entry point
hlslCode, _, err := hlsl.Compile(module, hlsl.Options{}) // Direct3D through FXC/DXC
dxilBytes, _, err := dxil.Compile(module, dxil.Options{}) // Direct3D 12, no compiler
GLSL and DXIL write one entry point: select it with Options.EntryPoint = &backend.EntryPointSelector{Stage, Name}
when the module has several.
GLSL Input
Vulkan GLSL 440/450/460 reaches the same pipeline through glsl.Parse: the module it returns is the one the WGSL
frontend would produce, so validation and every backend above apply unchanged.
The frontend is a preview: much of the Vulkan GLSL surface and the GL 3.30 core / ES 3.00 dialects is
implemented and verified end to end, including the level-of-detail query (textureQueryLod, GLSL 4.00+; the
GL 3.30 core and ES 3.00 dialects refuse it, as they have no such function), the subgroup built-in variables
(gl_SubgroupSize and the basic family’s other three) and the subgroup elect and all-equal builtins, but a few
subgroup forms the IR cannot express are refused with a message naming the limit; the ParseInfo/ParseOptions
shape may still change until the frontend is complete.
module, info, err := glsl.Parse(source, glsl.ParseOptions{Stage: ir.StageFragment})
if err != nil {
var pe *glsl.ParseError
if errors.As(err, &pe) {
fmt.Println(pe.Format(source, "shader.frag")) // the WGSL frontend's error layout
}
return err
}
for _, split := range info.CombinedSamplers { // uniform sampler2D: image + sampler globals
fmt.Println(split.Sampler, "->", split.Split)
}
if _, err := valid.Validate(module, valid.Options{}); err != nil {
return err
}
spirvBytes, _, err := spirv.Compile(module, spirv.Options{})
GLSL does not name its stage, so ParseOptions.Stage supplies it; combined image samplers are split by default
(CombinedImageSampler: frontend.CombinedImageSamplerReject refuses the declaration instead), and
ParseOptions.SamplerBindings places the sampler of each split. A GL 3.30 core or ES 3.00 source has no
layout(binding): ParseOptions.ResourceBindings places a module-scope resource by its source name and every
other resource takes the next free slot of its group. A plain uniform outside any block (uniform mat4 mvp;)
becomes a member of one generated std140 block: ParseInfo.DefaultBlock reports the block’s binding, its size and
every member’s offset, and a caller fills the buffer from those offsets rather than re-deriving the layout
(Vulkan GLSL has no default uniform block, so there the declaration is refused).
Pipeline Constants
override declarations get their values per pipeline. Parse and validate once, then process the module for each
pipeline before any backend, as wgpu does:
Subgroup: subgroupElect, subgroupBallot, subgroupAll, subgroupAny, subgroupAdd/Mul/Min/Max/And/Or/Xor, subgroupBroadcast/First, subgroupShuffle/XOR/Up/Down, quadSwap/Broadcast (need enable subgroups;, as the WGSL spec requires)
Directives: enable for f16, clip_distances, dual_source_blending, subgroups, primitive_index, draw_index and wgpu’s extensions; a feature used without its enable is an error
Ray Query: rayQueryInitialize, rayQueryProceed, rayQueryGetCommittedIntersection, rayQueryGetCandidateIntersection, rayQueryTerminate
Uniform Load: workgroupUniformLoad
Array: arrayLength
Status
Current Version: See CHANGELOG.md for release history.
Backend
Status
Target Platform
SPIR-V
✅ Stable, spirv-val in CI
Vulkan
MSL
✅ Stable
Metal (macOS/iOS)
GLSL
✅ Stable, version-aware binding
OpenGL 3.3+, ES 3.0+
HLSL
✅ Stable
DirectX 11/12
DXIL
236/267 entry points pass IDxcValidator (Rust naga and own corpus), 113/177 DXC golden
Coverage per package and per commit is on Codecov. Tests verify output
(exact strings, spirv-val, IDxcValidator, DXC roundtrip), negative cases with Rust naga’s error texts, and GPU
readback values; every fix ships with a test that failed before it.
Architecture
All backends follow the DXIL internal package pattern — implementation in internal/codegen/, thin public API with real types (not aliases). Zero panics in error paths.
naga (Rust) — the Rust implementation whose design this project builds on (see UPSTREAM)
Rust Naga Compatibility
naga is tested against the WGSL snapshot corpus of Rust naga:
172 shaders with their test parameters and reference outputs, vendored from gfx-rs/wgpu at commit 14328f49
(snapshot/testdata/rust/, with a manifest of every file). Every output Rust’s snapshot driver writes — IR,
SPIR-V, MSL, GLSL, HLSL — is compared with ours. An output that does not match is a test failure unless it is
recorded in snapshot/rust_deviations_test.go with its reason and a fingerprint of the difference; most records
name the upstream commits not ported yet, and some are bugs being fixed. SPIR-V is still compared by
instruction counts rather than exactly. Shaders using features we do not support yet (cooperative matrices,
debugPrintf, ray tracing pipelines) are listed with their expected error. In addition, 29 own test shaders and
the golden outputs of every backend (snapshot/testdata/golden/) guard against unintended changes.
Ecosystem
naga is the shader compiler for the GoGPU ecosystem.
We welcome contributions! Areas where help is needed:
Additional WGSL features
Test cases from real shaders
Backend optimizations
Documentation improvements
Star History
Acknowledgments
naga is an independent Go implementation. It builds on the design of Rust naga,
part of the gfx-rs/wgpu project, and is tested against its WGSL shader corpus. Thanks to its authors and contributors.
评论