ast

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2025 License: CC0-1.0 Imports: 1 Imported by: 0

Documentation

Overview

Package ast defines the Abstract Syntax Tree types for WGSL.

The AST is designed to be: - Complete: Represents all valid WGSL constructs - Efficient: Minimizes allocations and pointer chasing - Transformable: Supports in-place modifications for minification

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComputePureBuiltins

func ComputePureBuiltins() map[string]bool

ComputePureBuiltins returns a set of known pure WGSL built-in functions. These functions have no side effects and return deterministic results.

Types

type AccessMode

type AccessMode uint8

AccessMode represents WGSL access modes.

const (
	AccessModeNone AccessMode = iota
	AccessModeRead
	AccessModeWrite
	AccessModeReadWrite
)

func (AccessMode) String

func (a AccessMode) String() string

type AddressSpace

type AddressSpace uint8

AddressSpace represents WGSL address spaces.

const (
	AddressSpaceNone AddressSpace = iota
	AddressSpaceFunction
	AddressSpacePrivate
	AddressSpaceWorkgroup
	AddressSpaceUniform
	AddressSpaceStorage
	AddressSpaceHandle // For textures and samplers
)

func (AddressSpace) String

func (a AddressSpace) String() string

type AliasDecl

type AliasDecl struct {
	Loc  Loc
	Name Ref
	Type Type
}

AliasDecl represents: alias Name = Type;

type ArrayType

type ArrayType struct {
	Loc      Loc
	ElemType Type
	Size     Expr // nil for runtime-sized arrays
}

ArrayType represents array<T, N> or array<T>.

type AssignOp

type AssignOp uint8

AssignOp represents assignment operators.

const (
	AssignOpSimple AssignOp = iota // =
	AssignOpAdd                    // +=
	AssignOpSub                    // -=
	AssignOpMul                    // *=
	AssignOpDiv                    // /=
	AssignOpMod                    // %=
	AssignOpAnd                    // &=
	AssignOpOr                     // |=
	AssignOpXor                    // ^=
	AssignOpShl                    // <<=
	AssignOpShr                    // >>=
)

type AssignStmt

type AssignStmt struct {
	Loc   Loc
	Op    AssignOp
	Left  Expr
	Right Expr
}

AssignStmt represents: lhs = rhs; or lhs op= rhs;

type AtomicType

type AtomicType struct {
	Loc      Loc
	ElemType Type
}

AtomicType represents atomic<T>.

type Attribute

type Attribute struct {
	Loc  Loc
	Name string
	Args []Expr // nil for attributes without arguments
}

Attribute represents a WGSL attribute (@name or @name(args)).

type BinaryExpr

type BinaryExpr struct {
	Loc   Loc
	Op    BinaryOp
	Left  Expr
	Right Expr
	Flags ExprFlags // Purity flags
}

BinaryExpr represents a binary operation.

type BinaryOp

type BinaryOp uint8

BinaryOp represents binary operators.

const (
	BinOpAdd        BinaryOp = iota // +
	BinOpSub                        // -
	BinOpMul                        // *
	BinOpDiv                        // /
	BinOpMod                        // %
	BinOpAnd                        // &
	BinOpOr                         // |
	BinOpXor                        // ^
	BinOpShl                        // <<
	BinOpShr                        // >>
	BinOpLogicalAnd                 // &&
	BinOpLogicalOr                  // ||
	BinOpEq                         // ==
	BinOpNe                         // !=
	BinOpLt                         // <
	BinOpLe                         // <=
	BinOpGt                         // >
	BinOpGe                         // >=
)

type BreakIfStmt

type BreakIfStmt struct {
	Loc       Loc
	Condition Expr
}

BreakIfStmt represents: break if expr; (only in continuing block)

type BreakStmt

type BreakStmt struct {
	Loc Loc
}

BreakStmt represents: break;

type CallExpr

type CallExpr struct {
	Loc          Loc
	Func         Expr // IdentExpr for function name (nil if TemplateType is set)
	TemplateType Type // For templated constructors: array<T, N>, vec2<T>, etc.
	Args         []Expr
	Flags        ExprFlags // Purity flags
}

CallExpr represents a function call or type constructor.

type CallStmt

type CallStmt struct {
	Loc  Loc
	Call *CallExpr
}

CallStmt represents a function call as a statement.

type CompoundStmt

type CompoundStmt struct {
	Loc   Loc
	Stmts []Stmt
}

CompoundStmt represents a block of statements: { stmts }

type ConstAssertDecl

type ConstAssertDecl struct {
	Loc  Loc
	Expr Expr
}

ConstAssertDecl represents: const_assert expr;

type ConstDecl

type ConstDecl struct {
	Loc         Loc
	Name        Ref
	Type        Type // nil if inferred
	Initializer Expr
}

ConstDecl represents: const name [: type] = expr;

type ContinueStmt

type ContinueStmt struct {
	Loc Loc
}

ContinueStmt represents: continue;

type Decl

type Decl interface {
	// contains filtered or unexported methods
}

Decl represents a top-level or local declaration.

type DeclStmt

type DeclStmt struct {
	Decl Decl
}

DeclStmt wraps a declaration as a statement (for local const/let/var).

type DiagnosticDirective

type DiagnosticDirective struct {
	Loc      Loc
	Severity string
	Rule     string
}

DiagnosticDirective represents: diagnostic(severity, rule);

type Directive

type Directive interface {
	// contains filtered or unexported methods
}

Directive represents a top-level directive (enable, requires, diagnostic).

type DiscardStmt

type DiscardStmt struct {
	Loc Loc
}

DiscardStmt represents: discard; (fragment shader only)

type EnableDirective

type EnableDirective struct {
	Loc      Loc
	Features []string
}

EnableDirective represents: enable feature1, feature2;

type Expr

type Expr interface {
	// contains filtered or unexported methods
}

Expr represents an expression.

type ExprFlags

type ExprFlags uint8

ExprFlags are bitflags for expression properties.

const (
	// ExprFlagCanBeRemovedIfUnused marks an expression as removable if its
	// result is not used. This is set during the visit pass for pure expressions.
	ExprFlagCanBeRemovedIfUnused ExprFlags = 1 << iota

	// ExprFlagCallCanBeUnwrappedIfUnused marks a call expression where the
	// call target can be removed if unused, keeping only side-effecting args.
	ExprFlagCallCanBeUnwrappedIfUnused

	// ExprFlagIsConstant marks an expression that evaluates to a compile-time constant.
	ExprFlagIsConstant

	// ExprFlagFromPureFunction marks a call to a known pure built-in function.
	ExprFlagFromPureFunction
)

func (ExprFlags) Has

func (f ExprFlags) Has(flag ExprFlags) bool

Has returns true if the flag is set.

type ForStmt

type ForStmt struct {
	Loc       Loc
	Init      Stmt // VarDecl, LetDecl, assignment, or nil
	Condition Expr // nil for infinite loop
	Update    Stmt // Assignment or call, or nil
	Body      *CompoundStmt
}

ForStmt represents: for (init; cond; update) { }

type FunctionDecl

type FunctionDecl struct {
	Loc        Loc
	Attributes []Attribute
	Name       Ref
	Parameters []Parameter
	ReturnType Type        // nil for void
	ReturnAttr []Attribute // Return value attributes
	Body       *CompoundStmt
}

FunctionDecl represents a function declaration.

type IdentExpr

type IdentExpr struct {
	Loc   Loc
	Name  string
	Ref   Ref       // Resolved symbol reference
	Flags ExprFlags // Purity flags
}

IdentExpr represents an identifier reference.

type IdentType

type IdentType struct {
	Loc  Loc
	Name string
	Ref  Ref // Resolved reference (for user-defined types)
}

IdentType represents a type name (i32, f32, MyStruct, etc.)

type IfStmt

type IfStmt struct {
	Loc       Loc
	Condition Expr
	Body      *CompoundStmt
	Else      Stmt // nil, *IfStmt, or *CompoundStmt
}

IfStmt represents: if (cond) { } [else [if ...] { }]

type IncrDecrStmt

type IncrDecrStmt struct {
	Loc       Loc
	Expr      Expr
	Increment bool // true for ++, false for --
}

IncrDecrStmt represents: expr++; or expr--;

type Index32

type Index32 struct {
	// contains filtered or unexported fields
}

Index32 is an optional 32-bit index.

func MakeIndex32

func MakeIndex32(i uint32) Index32

MakeIndex32 creates a valid index.

func (Index32) GetIndex

func (i Index32) GetIndex() uint32

GetIndex returns the index value.

func (Index32) IsValid

func (i Index32) IsValid() bool

IsValid returns true if this index is valid.

type IndexExpr

type IndexExpr struct {
	Loc   Loc
	Base  Expr
	Index Expr
	Flags ExprFlags // Purity flags
}

IndexExpr represents array/vector indexing: base[index]

type LetDecl

type LetDecl struct {
	Loc         Loc
	Name        Ref
	Type        Type // nil if inferred
	Initializer Expr
}

LetDecl represents: let name [: type] = expr;

type LiteralExpr

type LiteralExpr struct {
	Loc   Loc
	Kind  lexer.TokenKind
	Value string    // Raw literal text
	Flags ExprFlags // Purity flags (always pure)
}

LiteralExpr represents a literal value.

type Loc

type Loc struct {
	Start int32 // Byte offset of start
}

Loc represents a location in source code.

type LoopStmt

type LoopStmt struct {
	Loc        Loc
	Body       *CompoundStmt
	Continuing *CompoundStmt // nil if no continuing block
}

LoopStmt represents: loop { [continuing { }] }

type MatType

type MatType struct {
	Loc       Loc
	Cols      uint8 // 2, 3, or 4
	Rows      uint8 // 2, 3, or 4
	ElemType  Type  // Element type (nil for shorthand)
	Shorthand string
}

MatType represents matCxR<T> or mat4x4f, etc.

type MemberExpr

type MemberExpr struct {
	Loc    Loc
	Base   Expr
	Member string
	Flags  ExprFlags // Purity flags
}

MemberExpr represents member access: base.member

type Module

type Module struct {
	// Source information
	Source     string // Original source text
	SourcePath string // File path (for error messages)

	// Top-level declarations in order
	Directives   []Directive
	Declarations []Decl

	// Symbol table
	Symbols []Symbol

	// Module-level scope
	Scope *Scope
}

Module represents a complete WGSL module.

type OverrideDecl

type OverrideDecl struct {
	Loc         Loc
	Attributes  []Attribute
	Name        Ref
	Type        Type // nil if inferred
	Initializer Expr // nil if no default
}

OverrideDecl represents: @id(n) override name [: type] [= expr];

type Parameter

type Parameter struct {
	Loc        Loc
	Attributes []Attribute
	Name       Ref
	Type       Type
}

Parameter represents a function parameter.

type ParenExpr

type ParenExpr struct {
	Loc   Loc
	Expr  Expr
	Flags ExprFlags // Purity flags (inherits from inner expr)
}

ParenExpr represents a parenthesized expression.

type PtrType

type PtrType struct {
	Loc          Loc
	AddressSpace AddressSpace
	ElemType     Type
	AccessMode   AccessMode
}

PtrType represents ptr<space, T, access>.

type PurityContext

type PurityContext struct {
	Symbols   []Symbol
	PureCalls map[string]bool // Known pure built-in functions
}

PurityContext provides context for purity analysis.

func NewPurityContext

func NewPurityContext(symbols []Symbol) *PurityContext

NewPurityContext creates a purity context with known pure functions.

func (*PurityContext) DeclCanBeRemovedIfUnused

func (ctx *PurityContext) DeclCanBeRemovedIfUnused(decl Decl) bool

DeclCanBeRemovedIfUnused returns true if the declaration can be removed when its symbol is not used.

func (*PurityContext) ExprCanBeRemovedIfUnused

func (ctx *PurityContext) ExprCanBeRemovedIfUnused(expr Expr) bool

ExprCanBeRemovedIfUnused returns true if the expression can be safely removed when its result is not used (i.e., it has no side effects).

func (*PurityContext) MarkExprPurity

func (ctx *PurityContext) MarkExprPurity(expr Expr)

MarkExprPurity sets the purity flags on an expression based on analysis.

func (*PurityContext) StmtCanBeRemovedIfUnused

func (ctx *PurityContext) StmtCanBeRemovedIfUnused(stmt Stmt) bool

StmtCanBeRemovedIfUnused returns true if the statement can be removed when none of its declared symbols are used.

type Range

type Range struct {
	Loc Loc
	Len int32
}

Range represents a range in source code.

type Ref

type Ref struct {
	SourceIndex uint32
	InnerIndex  uint32
}

Ref is a reference to a symbol in the symbol table. Using a struct with two indices allows efficient symbol table lookups while supporting multiple source files (future extension).

func InvalidRef

func InvalidRef() Ref

InvalidRef returns an invalid reference.

func (Ref) IsValid

func (r Ref) IsValid() bool

IsValid returns true if this is a valid reference.

type RequiresDirective

type RequiresDirective struct {
	Loc      Loc
	Features []string
}

RequiresDirective represents: requires feature1, feature2;

type ReturnStmt

type ReturnStmt struct {
	Loc   Loc
	Value Expr // nil for bare return
}

ReturnStmt represents: return [expr];

type SamplerType

type SamplerType struct {
	Loc        Loc
	Comparison bool
}

SamplerType represents sampler or sampler_comparison.

type Scope

type Scope struct {
	Parent   *Scope
	Children []*Scope
	Members  map[string]ScopeMember

	// For minification: whether this scope contains direct eval (always false in WGSL)
	// Kept for structural similarity with esbuild
	ContainsDirectEval bool
}

Scope represents a lexical scope.

func NewScope

func NewScope(parent *Scope) *Scope

NewScope creates a new scope with the given parent.

type ScopeMember

type ScopeMember struct {
	Ref Ref
	Loc int // Source position where declared (for text-order scoping)
}

ScopeMember represents a symbol in a scope with its declaration location.

type SideEffects

type SideEffects uint8

SideEffects indicates whether an expression has side effects.

const (
	// CouldHaveSideEffects means we can't prove the expression is pure.
	CouldHaveSideEffects SideEffects = iota
	// NoSideEffects means the expression is definitely pure.
	NoSideEffects
)

type Stmt

type Stmt interface {
	// contains filtered or unexported methods
}

Stmt represents a statement.

type StructDecl

type StructDecl struct {
	Loc     Loc
	Name    Ref
	Members []StructMember
}

StructDecl represents: struct Name { members }

type StructMember

type StructMember struct {
	Loc        Loc
	Attributes []Attribute
	Name       Ref
	Type       Type
}

StructMember represents a struct field.

type SwitchCase

type SwitchCase struct {
	Loc       Loc
	Selectors []Expr // nil for default
	Body      *CompoundStmt
}

SwitchCase represents a case clause in a switch.

type SwitchStmt

type SwitchStmt struct {
	Loc   Loc
	Expr  Expr
	Cases []SwitchCase
}

SwitchStmt represents: switch (expr) { cases }

type Symbol

type Symbol struct {
	// The original name as written in source
	OriginalName string

	// Location of the declaration
	Loc Loc

	// What kind of symbol this is
	Kind SymbolKind

	// Flags for special handling
	Flags SymbolFlags

	// For minification: the assigned slot for this symbol
	NestedScopeSlot Index32

	// Usage count for frequency-based renaming
	UseCount uint32
}

Symbol represents a declared name in WGSL.

type SymbolFlags

type SymbolFlags uint16

SymbolFlags are bitflags for symbol properties.

const (
	// MustNotBeRenamed prevents minification of this symbol.
	// Used for entry points, API-facing names, etc.
	MustNotBeRenamed SymbolFlags = 1 << iota

	// IsEntryPoint marks entry point functions.
	IsEntryPoint

	// IsAPIFacing marks names visible to the WebGPU API.
	IsAPIFacing

	// IsBuiltin marks built-in functions and types.
	IsBuiltin

	// IsExternalBinding marks uniform/storage variables that are bound via @group/@binding.
	// These keep their original names in declarations but get aliased before use.
	IsExternalBinding

	// IsLive marks symbols that are reachable from entry points.
	// Used by dead code elimination to filter unused declarations.
	IsLive
)

func (SymbolFlags) Has

func (f SymbolFlags) Has(flag SymbolFlags) bool

Has returns true if the flag is set.

type SymbolKind

type SymbolKind uint8

SymbolKind indicates what a symbol represents.

const (
	SymbolUnbound   SymbolKind = iota // Not yet resolved
	SymbolConst                       // const declaration
	SymbolOverride                    // override declaration
	SymbolLet                         // let declaration
	SymbolVar                         // var declaration
	SymbolFunction                    // fn declaration
	SymbolStruct                      // struct declaration
	SymbolAlias                       // type alias
	SymbolParameter                   // function parameter
	SymbolBuiltin                     // built-in function/type
	SymbolMember                      // struct member
)

type TextureDimension

type TextureDimension uint8

TextureDimension indicates texture dimensionality.

const (
	Texture1D TextureDimension = iota
	Texture2D
	Texture2DArray
	Texture3D
	TextureCube
	TextureCubeArray
)

type TextureKind

type TextureKind uint8

TextureKind indicates the texture category.

const (
	TextureSampled TextureKind = iota
	TextureMultisampled
	TextureStorage
	TextureDepth
	TextureDepthMultisampled
	TextureExternal
)

type TextureType

type TextureType struct {
	Loc         Loc
	Kind        TextureKind
	Dimension   TextureDimension
	SampledType Type   // For sampled textures
	TexelFormat string // For storage textures
	AccessMode  AccessMode
}

TextureType represents texture types.

type Type

type Type interface {
	// contains filtered or unexported methods
}

Type represents a WGSL type.

type UnaryExpr

type UnaryExpr struct {
	Loc     Loc
	Op      UnaryOp
	Operand Expr
	Flags   ExprFlags // Purity flags
}

UnaryExpr represents a unary operation.

type UnaryOp

type UnaryOp uint8

UnaryOp represents unary operators.

const (
	UnaryOpNeg    UnaryOp = iota // -
	UnaryOpNot                   // !
	UnaryOpBitNot                // ~
	UnaryOpDeref                 // *
	UnaryOpAddr                  // &
)

type VarDecl

type VarDecl struct {
	Loc          Loc
	Attributes   []Attribute
	AddressSpace AddressSpace
	AccessMode   AccessMode
	Name         Ref
	Type         Type
	Initializer  Expr // nil if no initializer
}

VarDecl represents: @group(g) @binding(b) var<space, access> name [: type] [= expr];

type VecType

type VecType struct {
	Loc       Loc
	Size      uint8  // 2, 3, or 4
	ElemType  Type   // Element type (nil for shorthand like vec3f)
	Shorthand string // "vec3f", "vec4i", etc. (empty if using template)
}

VecType represents vec2<T>, vec3<T>, vec4<T> or vec2f, etc.

type WhileStmt

type WhileStmt struct {
	Loc       Loc
	Condition Expr
	Body      *CompoundStmt
}

WhileStmt represents: while (cond) { }

Jump to

Keyboard shortcuts

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