Documentation
¶
Overview ¶
Package naga provides a Pure Go shader compiler.
naga compiles WGSL (WebGPU Shading Language) source code to multiple output formats:
- SPIR-V — Binary format for Vulkan
- MSL — Metal Shading Language for macOS/iOS
- GLSL — OpenGL Shading Language for OpenGL 3.3+, ES 3.0+
- HLSL — High Level Shading Language for DirectX
The package provides a simple, high-level API for shader compilation as well as lower-level access to individual compilation stages.
Example usage (SPIR-V):
source := `
@vertex
fn main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4<f32> {
return vec4<f32>(0.0, 0.0, 0.0, 1.0);
}
`
spirv, err := naga.Compile(source)
if err != nil {
log.Fatal(err)
}
For MSL output, use the msl package:
module, _ := naga.Lower(ast) mslCode, info, err := msl.Compile(module, msl.DefaultOptions())
For GLSL output, use the glsl package:
module, _ := naga.Lower(ast) glslCode, info, err := glsl.Compile(module, glsl.DefaultOptions())
Index ¶
- Constants
- Variables
- func Compile(source string) ([]byte, error)
- func CompileWithOptions(source string, opts CompileOptions) ([]byte, error)
- func GenerateSPIRV(module *ir.Module, opts spirv.Options) ([]byte, error)
- func Lower(ast *wgsl.Module) (*ir.Module, error)
- func LowerWithCapabilities(ast *wgsl.Module, source string, caps ir.Capabilities) (*ir.Module, error)
- func LowerWithSource(ast *wgsl.Module, source string) (*ir.Module, error)
- func Parse(source string) (*wgsl.Module, error)
- func ProcessOverrides(module *ir.Module, opts OverrideOptions) (*ir.Module, error)
- func Validate(module *ir.Module) ([]ir.ValidationError, error)
- type CompileOptions
- type EntryPointSelector
- type OverrideOptions
- type PipelineConstantError
- type PipelineConstants
Constants ¶
const ( // CapFloat64 enables f64 scalar type. CapFloat64 = ir.CapFloat64 // CapShaderInt64 enables i64 and u64 scalar types. CapShaderInt64 = ir.CapShaderInt64 // CapShaderFloat16 enables f16 scalar type. CapShaderFloat16 = ir.CapShaderFloat16 // CapAll enables all capabilities. CapAll = ir.CapAll )
Capability constants re-exported from ir for convenience. See ir.Capabilities for full documentation.
Variables ¶
var ( // ErrOverrideNotFound: a key names no override of the module. ErrOverrideNotFound = overrides.ErrNotFound // ErrOverrideMissingValue: an override an entry point uses has no value // and no default. ErrOverrideMissingValue = overrides.ErrMissingValue // ErrOverrideValueNotFinite: NaN or an infinity for a numeric override. ErrOverrideValueNotFinite = overrides.ErrValueNotFinite // ErrOverrideValueOutOfRange: the value does not fit the override's type. ErrOverrideValueOutOfRange = overrides.ErrValueOutOfRange // ErrNegativeWorkgroupSize: a workgroup size given by an override is not // positive. ErrNegativeWorkgroupSize = overrides.ErrNegativeWorkgroupSize // ErrNegativeMeshOutputMax: a mesh output limit given by an override is // negative. ErrNegativeMeshOutputMax = overrides.ErrNegativeMeshOutputMax // ErrEntryPointNotFound: OverrideOptions.EntryPoint selects no entry point. ErrEntryPointNotFound = overrides.ErrEntryPointNotFound )
Pipeline-constant errors.
Functions ¶
func Compile ¶
Compile compiles WGSL source code to SPIR-V binary using default options.
This is the simplest way to compile a shader. For more control, use CompileWithOptions or the individual Parse/Lower/Generate functions.
func CompileWithOptions ¶
func CompileWithOptions(source string, opts CompileOptions) ([]byte, error)
CompileWithOptions compiles WGSL source code to SPIR-V binary with custom options.
The compilation pipeline is:
- Parse WGSL source to AST
- Lower AST to IR (intermediate representation)
- Validate IR (if enabled)
- Replace overrides by their defaults (ProcessOverrides with no pipeline constants), as Rust naga's CLI does; an override without a default is an error. For pipeline constants use Parse, Lower, ProcessOverrides and a backend.
- Generate SPIR-V binary
func GenerateSPIRV ¶
GenerateSPIRV generates SPIR-V binary from IR module.
This is the final stage of compilation. The output is a binary blob that can be directly consumed by Vulkan or other SPIR-V consumers.
func Lower ¶
Lower converts WGSL AST to IR (Intermediate Representation). All capabilities are enabled (permissive mode for tools and tests). For strict capability validation, use LowerWithCapabilities.
The IR is a lower-level representation that includes type information, resolved identifiers, and a simpler structure suitable for code generation.
func LowerWithCapabilities ¶ added in v0.18.0
func LowerWithCapabilities(ast *wgsl.Module, source string, caps ir.Capabilities) (*ir.Module, error)
LowerWithCapabilities converts WGSL AST to IR with explicit capability control. The lowerer is always permissive; capability validation is performed by the validator after lowering. Types that require specific capabilities (f64, i64, u64, f16) produce validation errors unless the corresponding flag is set.
func LowerWithSource ¶ added in v0.4.0
LowerWithSource converts WGSL AST to IR, keeping source for error messages. All capabilities are enabled (permissive mode for tools and tests). For strict capability validation, use LowerWithCapabilities.
When source is provided, errors will include line:column information and can show source context using ErrorList.FormatAll().
func Parse ¶
Parse parses WGSL source code to AST (Abstract Syntax Tree).
This is the first stage of compilation. The AST represents the syntactic structure of the shader but does not include semantic information like types.
func ProcessOverrides ¶ added in v0.20.1
ProcessOverrides returns module with every override expression replaced by a constant holding its pipeline value or default, every expression that becomes constant evaluated, and workgroup sizes given by overrides resolved — Rust naga's back::pipeline_constants::process_overrides. Call it before a backend; naga.Compile calls it with the defaults.
module is never modified, and ProcessOverrides may be called concurrently on the same module. The result may be module itself when there is nothing to do (no overrides, and no EntryPoint or at most one entry point); treat it as read-only. Handles in the result are not stable relative to module.
A module produced by the WGSL frontend with no overrides (len(Overrides) == 0) has no override expressions, override workgroup sizes or override-sized arrays and needs no processing, but call ProcessOverrides anyway when Constants is not empty: a key that names no override is an error (ErrOverrideNotFound).
With EntryPoint, globals the entry point does not use are removed. A backend that numbers resources by their position in the module (MSL without msl.Options.PerEntryPointMap) can then give them other slots.
The result keeps the overrides arena, with each initializer evaluated, and override-sized arrays stay pending (ir.ArraySize.Resolve sizes them; backends do), as in Rust. With EntryPoint the selected entry point is EntryPoints[0]. Processing a processed module again with other constants is not supported: process the module from the frontend for every pipeline.
Errors: a *PipelineConstantError for a constant (errors.Is with ErrOverrideNotFound, ErrOverrideMissingValue, ErrOverrideValueNotFinite, ErrOverrideValueOutOfRange); ErrEntryPointNotFound; ErrNegativeWorkgroupSize; ErrNegativeMeshOutputMax; an evaluation error of an expression that becomes constant (for example a division by zero after substitution); or an invalid processed module. Keys are checked in sorted order, so the same input reports the same key.
func Validate ¶
func Validate(module *ir.Module) ([]ir.ValidationError, error)
Validate validates an IR module for correctness with all capabilities enabled.
Validation checks include:
- Type consistency
- Reference validity (all handles point to valid objects)
- Control flow validity (structured control flow rules)
- Binding uniqueness (no duplicate @group/@binding)
For capability-restricted validation, use ir.ValidateWithCapabilities directly. Returns a slice of validation errors. If the slice is empty, validation passed.
Types ¶
type CompileOptions ¶
type CompileOptions struct {
// SPIRVVersion is the target SPIR-V version (default: 1.3)
SPIRVVersion spirv.Version
// Debug enables debug info in output (OpName, OpLine, etc.)
Debug bool
// Validate enables IR validation before code generation
Validate bool
// Capabilities controls which extended scalar types are allowed.
// Zero value rejects f64/i64/u64/f16 (matching Rust naga defaults).
// Use [CapFloat64], [CapShaderInt64], [CapShaderFloat16] to enable specific types,
// or [CapAll] to permit everything.
Capabilities ir.Capabilities
// BoundsCheckPolicies selects how the generated SPIR-V handles indices
// that are out of bounds. The zero value adds no checks. A WebGPU
// implementation needs at least Restrict for Index (and for Buffer and
// ImageLoad when the device has no robust buffer and image access), as
// Rust wgpu-hal's Vulkan backend configures naga.
BoundsCheckPolicies spirv.BoundsCheckPolicies
}
CompileOptions configures shader compilation.
func DefaultOptions ¶
func DefaultOptions() CompileOptions
DefaultOptions returns sensible default options.
type EntryPointSelector ¶ added in v0.20.1
type EntryPointSelector struct {
Stage ir.ShaderStage
Name string
}
EntryPointSelector selects one entry point by stage and name. It is not ir.EntryPoint.
type OverrideOptions ¶ added in v0.20.1
type OverrideOptions struct {
// Constants are the pipeline-constant values.
Constants PipelineConstants
// EntryPoint, if not nil, keeps only that entry point; only overrides it
// uses need a value.
EntryPoint *EntryPointSelector
}
OverrideOptions configure ProcessOverrides. The zero value processes every entry point with no pipeline constants: every override takes its default.
type PipelineConstantError ¶ added in v0.20.1
type PipelineConstantError struct {
Key string // the pipeline-constant key, or the override's identifier string
Err error
}
PipelineConstantError is an error about one pipeline constant or override (Rust naga's PipelineConstantError). Err is one of the ErrOverride* sentinels; Error is Rust's message.
func (*PipelineConstantError) Error ¶ added in v0.20.1
func (e *PipelineConstantError) Error() string
func (*PipelineConstantError) Unwrap ¶ added in v0.20.1
func (e *PipelineConstantError) Unwrap() error
Unwrap returns Err, for errors.Is.
type PipelineConstants ¶ added in v0.20.1
PipelineConstants are the values of pipeline-overridable constants (WebGPU GPUProgrammableStage.constants). A key is an override's @id as a decimal string, or its name if it has no @id; keys are compared exactly, as WGSL identifiers.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
dxilval
command
Command dxilval validates DXIL containers using Microsoft's IDxcValidator.
|
Command dxilval validates DXIL containers using Microsoft's IDxcValidator. |
|
dxilval/internal/run
Package run implements the dxilval CLI logic.
|
Package run implements the dxilval CLI logic. |
|
nagac
command
Command nagac is the naga shader compiler CLI.
|
Command nagac is the naga shader compiler CLI. |
|
spvdis
command
spvdis - SPIR-V disassembler Generates valid .spvasm text format
|
spvdis - SPIR-V disassembler Generates valid .spvasm text format |
|
texture_compile
command
|
|
|
Package dxil implements a DXIL (DirectX Intermediate Language) backend for the naga shader compiler.
|
Package dxil implements a DXIL (DirectX Intermediate Language) backend for the naga shader compiler. |
|
internal/bitcode
Package bitcode implements a bit-level writer for LLVM 3.7 bitcode format.
|
Package bitcode implements a bit-level writer for LLVM 3.7 bitcode format. |
|
internal/container
Package container implements the DXBC container format used to wrap DXIL shader bitcode.
|
Package container implements the DXBC container format used to wrap DXIL shader bitcode. |
|
internal/emit
Package emit implements naga IR to DXIL module lowering.
|
Package emit implements naga IR to DXIL module lowering. |
|
internal/module
Package module provides an in-memory representation of a DXIL module.
|
Package module provides an in-memory representation of a DXIL module. |
|
internal/passes/dce
Package dce implements dead code elimination for DXIL shader functions.
|
Package dce implements dead code elimination for DXIL shader functions. |
|
internal/passes/mem2reg
Package mem2reg promotes function-scope local variables of scalar type to SSA values, eliminating the corresponding alloca / load / store triples that the DXIL emitter would otherwise produce.
|
Package mem2reg promotes function-scope local variables of scalar type to SSA values, eliminating the corresponding alloca / load / store triples that the DXIL emitter would otherwise produce. |
|
internal/passes/sroa
Package sroa implements Scalar Replacement of Aggregates for DXIL emit.
|
Package sroa implements Scalar Replacement of Aggregates for DXIL emit. |
|
internal/viewid
Package viewid computes input→output dataflow dependencies for graphics entry points, producing the data that populates DXIL's `dx.viewIdState` metadata (ComputeViewIdState.cpp format) and the PSV0 dependency table (PSVDependencyTable layout).
|
Package viewid computes input→output dataflow dependencies for graphics entry points, producing the data that populates DXIL's `dx.viewIdState` metadata (ComputeViewIdState.cpp format) and the PSV0 dependency table (PSVDependencyTable layout). |
|
Package glsl provides a GLSL (OpenGL Shading Language) backend for naga.
|
Package glsl provides a GLSL (OpenGL Shading Language) backend for naga. |
|
Package hlsl provides HLSL (High-Level Shading Language) code generation from the naga intermediate representation.
|
Package hlsl provides HLSL (High-Level Shading Language) code generation from the naga intermediate representation. |
|
internal/codegen
Package hlsl implements HLSL expression generation for all IR expression types.
|
Package hlsl implements HLSL expression generation for all IR expression types. |
|
internal
|
|
|
backend
Package backend holds cross-backend constants and helpers shared between naga's text backends (HLSL) and binary backends (DXIL) that both target the D3D ecosystem.
|
Package backend holds cross-backend constants and helpers shared between naga's text backends (HLSL) and binary backends (DXIL) that both target the D3D ecosystem. |
|
cmd/corpussync
command
Command corpussync maintains the Rust naga test corpus vendored under snapshot/testdata (ADR-006).
|
Command corpussync maintains the Rust naga test corpus vendored under snapshot/testdata (ADR-006). |
|
consteval
Package consteval evaluates WGSL const-expressions: the shader-creation-time evaluation that the WGSL specification requires for const declarations and that naga also applies to constant operands in function bodies.
|
Package consteval evaluates WGSL const-expressions: the shader-creation-time evaluation that the WGSL specification requires for const declarations and that naga also applies to constant operands in function bodies. |
|
dxcvalidator
Package dxcvalidator wraps Microsoft's IDxcValidator (dxil.dll) so naga can run real DXIL validation against generated containers from Pure Go.
|
Package dxcvalidator wraps Microsoft's IDxcValidator (dxil.dll) so naga can run real DXIL validation against generated containers from Pure Go. |
|
dxcvalidator/bitcheck
Package bitcheck implements a minimal LLVM 3.7 bitstream reader that walks a DXIL container far enough to verify the `!dx.entryPoints` named metadata is well-formed — specifically that every entry-point tuple has a non-null function reference in operand 0.
|
Package bitcheck implements a minimal LLVM 3.7 bitstream reader that walks a DXIL container far enough to verify the `!dx.entryPoints` named metadata is well-formed — specifically that every entry-point tuple has a non-null function reference in operand 0. |
|
overrides
Package overrides replaces pipeline-overridable constants by their values: a port of Rust naga's back::pipeline_constants::process_overrides on the shared constant evaluator (ADR-008).
|
Package overrides replaces pipeline-overridable constants by their values: a port of Rust naga's back::pipeline_constants::process_overrides on the shared constant evaluator (ADR-008). |
|
registry
Package registry provides type deduplication for the naga IR.
|
Package registry provides type deduplication for the naga IR. |
|
testcorpus
Package testcorpus records and verifies the provenance of the test corpus under snapshot/testdata (ADR-006).
|
Package testcorpus records and verifies the provenance of the test corpus under snapshot/testdata (ADR-006). |
|
testtools
Package testtools gives tests one policy for external tools (spirv-val, spirv-dis, dxc, ...), in the spirit of Go's internal/testenv.
|
Package testtools gives tests one policy for external tools (spirv-val, spirv-dis, dxc, ...), in the spirit of Go's internal/testenv. |
|
textutil
Package textutil provides shared text writing utilities for naga codegen backends.
|
Package textutil provides shared text writing utilities for naga codegen backends. |
|
Package ir defines the intermediate representation for naga.
|
Package ir defines the intermediate representation for naga. |
|
Package msl implements Metal Shading Language (MSL) code generation for naga.
|
Package msl implements Metal Shading Language (MSL) code generation for naga. |
|
Package spirv provides SPIR-V code generation from naga IR.
|
Package spirv provides SPIR-V code generation from naga IR. |
|
internal/codegen
Package codegen implements SPIR-V code generation from naga IR.
|
Package codegen implements SPIR-V code generation from naga IR. |
|
Package wgsl provides WGSL (WebGPU Shading Language) parsing and lowering.
|
Package wgsl provides WGSL (WebGPU Shading Language) parsing and lowering. |