naga

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 4 Imported by: 4

README

naga

Pure Go Shader Compiler
WGSL to SPIR-V. Zero CGO.

CI codecov Go Reference Go Report Card License Go Version Zero CGO

Part of the GoGPU ecosystem

v0.3.0 — Let inference, array init, texture sampling. ~15K lines of pure Go.


Features

  • Pure Go — No CGO, no external dependencies
  • WGSL Frontend — Full lexer and parser (140+ tokens)
  • IR — Complete intermediate representation (expressions, statements, types)
  • Type Inference — Automatic type resolution for all expressions, including let bindings
  • Type Deduplication — SPIR-V compliant unique type emission
  • Array Initialization — array(1, 2, 3) shorthand with inferred type and size
  • Texture Sampling — textureSample, textureLoad, textureStore, textureDimensions
  • SPIR-V Backend — Vulkan-compatible bytecode generation with correct type handling
  • Validation — Type checking and semantic validation
  • CLI Tool — nagac command-line compiler

Installation

go get github.com/gogpu/naga

Usage

As Library

package main

import (
    "fmt"
    "log"

    "github.com/gogpu/naga"
)

func main() {
    source := `
@vertex
fn main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4<f32> {
    return vec4<f32>(0.0, 0.0, 0.0, 1.0);
}
`
    // Simple compilation
    spirv, err := naga.Compile(source)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Generated %d bytes of SPIR-V\n", len(spirv))
}

With Options

opts := naga.CompileOptions{
    SPIRVVersion: spirv.Version1_3,
    Debug:        true,   // Include debug names
    Validate:     true,   // Enable IR validation
}
spirv, err := naga.CompileWithOptions(source, opts)

CLI Tool

# Install
go install github.com/gogpu/naga/cmd/nagac@latest

# Compile shader
nagac shader.wgsl -o shader.spv

# With debug info
nagac -debug shader.wgsl -o shader.spv

# Show version
nagac -version

Individual Stages

// Parse WGSL to AST
ast, err := naga.Parse(source)

// Lower AST to IR
module, err := naga.Lower(ast)

// Validate IR
errors, err := naga.Validate(module)

// Generate SPIR-V
spirvOpts := spirv.Options{Version: spirv.Version1_3, Debug: true}
spirvBytes, err := naga.GenerateSPIRV(module, spirvOpts)

Architecture

naga/
├── wgsl/              # WGSL frontend
│   ├── token.go       # Token types (140+)
│   ├── lexer.go       # Tokenizer
│   ├── ast.go         # AST types
│   ├── parser.go      # Recursive descent parser (~1400 LOC)
│   └── lower.go       # AST → IR converter (~1100 LOC)
├── ir/                # Intermediate representation
│   ├── ir.go          # Core types (Module, Type, Function)
│   ├── expression.go  # 33 expression types (~520 LOC)
│   ├── statement.go   # 16 statement types (~320 LOC)
│   ├── validate.go    # IR validation (~750 LOC)
│   ├── resolve.go     # Type inference (~500 LOC) ← NEW
│   └── registry.go    # Type deduplication (~100 LOC) ← NEW
├── spirv/             # SPIR-V backend
│   ├── spirv.go       # SPIR-V constants and opcodes
│   ├── writer.go      # Binary module builder (~670 LOC)
│   └── backend.go     # IR → SPIR-V translator (~1800 LOC)
├── naga.go            # Public API
└── cmd/nagac/         # CLI tool

Supported WGSL Features

Types

  • Scalars: f32, f64, i32, u32, bool
  • Vectors: vec2<T>, vec3<T>, vec4<T>
  • Matrices: mat2x2<f32> ... mat4x4<f32>
  • Arrays: array<T, N>
  • Structs: struct { ... }
  • Textures: texture_2d<f32>, texture_3d<f32>, texture_cube<f32>
  • Samplers: sampler, sampler_comparison

Shader Stages

  • @vertex — Vertex shaders with @builtin(position) output
  • @fragment — Fragment shaders with @location(N) outputs
  • @compute — Compute shaders with @workgroup_size(X, Y, Z)

Bindings

  • @builtin(position), @builtin(vertex_index), @builtin(instance_index)
  • @location(N) — Vertex attributes and fragment outputs
  • @group(G) @binding(B) — Resource bindings

Statements

  • Variable declarations: var, let
  • Control flow: if, else, for, while, loop
  • Loop control: break, continue
  • Functions: return, discard
  • Assignment: =, +=, -=, *=, /=

Built-in Functions (40+)

  • Math: sin, cos, tan, exp, log, pow, sqrt, abs, min, max, clamp
  • Geometric: dot, cross, length, distance, normalize, reflect
  • Interpolation: mix, step, smoothstep
  • Derivatives: dpdx, dpdy, fwidth

Roadmap

v0.1.0 ✅

  • WGSL lexer and parser
  • Complete IR (expressions, statements, types)
  • IR validation
  • SPIR-V binary writer
  • SPIR-V backend (types, constants, functions, expressions)
  • Control flow (if, loop, break, continue)
  • Built-in math functions (GLSL.std.450)
  • Public API and CLI tool

v0.2.0 ✅

  • Type inference for all expressions
  • Type deduplication (SPIR-V compliant)
  • Correct int/float/uint opcode selection
  • SPIR-V backend with proper type handling
  • 67+ unit tests

v0.3.0 (Current) ✅

  • Type inference for let bindings
  • Array initialization syntax (array(1, 2, 3))
  • Texture sampling operations (textureSample, textureLoad, textureStore)
  • SPIR-V image operations (OpImageSample*, OpImageFetch, OpImageQuery*)
  • 124 unit tests

v0.4.0 (Next)

  • Better error messages with source locations
  • Compute shader improvements
  • Storage buffer operations
  • Workgroup shared memory

v0.5.0 (Future)

  • GLSL backend output
  • Source maps for debugging
  • Optimization passes

v1.0.0 (Goal)

  • Full WGSL specification compliance
  • Production-ready stability
  • HLSL/MSL backends

References

Project Description
gogpu/gogpu Pure Go graphics framework
gogpu/wgpu Pure Go WebGPU types and HAL
go-webgpu/webgpu WebGPU FFI bindings

Contributing

We welcome contributions! Areas where help is needed:

  • Additional WGSL features (atomics, ray tracing)
  • Test cases from real shaders
  • GLSL backend implementation
  • Documentation improvements

License

MIT License — see LICENSE for details.


naga — Shaders in Pure Go

Documentation

Overview

Package naga provides a Pure Go shader compiler.

naga compiles WGSL (WebGPU Shading Language) source code to SPIR-V binary format for use with Vulkan and other graphics APIs. It provides a simple, high-level API for shader compilation as well as lower-level access to individual compilation stages.

Example usage:

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)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compile

func Compile(source string) ([]byte, error)

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:

  1. Parse WGSL source to AST
  2. Lower AST to IR (intermediate representation)
  3. Validate IR (if enabled)
  4. Generate SPIR-V binary

func GenerateSPIRV

func GenerateSPIRV(module *ir.Module, opts spirv.Options) ([]byte, error)

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

func Lower(ast *wgsl.Module) (*ir.Module, error)

Lower converts WGSL AST to IR (Intermediate Representation).

The IR is a lower-level representation that includes type information, resolved identifiers, and a simpler structure suitable for code generation.

func Parse

func Parse(source string) (*wgsl.Module, error)

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 Validate

func Validate(module *ir.Module) ([]ir.ValidationError, error)

Validate validates an IR module for correctness.

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)

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
}

CompileOptions configures shader compilation.

func DefaultOptions

func DefaultOptions() CompileOptions

DefaultOptions returns sensible default options.

Directories

Path Synopsis
cmd
nagac command
Command nagac is the naga shader compiler CLI.
Command nagac is the naga shader compiler CLI.
Package ir defines the intermediate representation for naga.
Package ir defines the intermediate representation for naga.
Package spirv provides SPIR-V code generation from naga IR.
Package spirv provides SPIR-V code generation from naga IR.
Package wgsl provides WGSL (WebGPU Shading Language) parsing.
Package wgsl provides WGSL (WebGPU Shading Language) parsing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL