wgsl#
the WGSL compiler: lexer, parser, semantic checker, constant evaluation, the typed IR, the SPIR-V back end, pipeline constants and checks, the benchmark shaders as WGSL -- crate root lib/wgsl/lib.rs
wgsl -- JFLib's WGSL compiler: source text -> a checked, fully typed module (the front end,
step G2a of the GPU plan) -> SPIR-V through lib/shader (the back end, G2c; docs/WGSL.md);
the browser path (G4) hands the same text to WebGPU. The reference is the W3C WGSL
Candidate Recommendation (2026-10-26); where Chrome's Tint differs, the docs say so.
parse(src) -> (Ast, Vec<Diagnostic>) the syntax tree of everything that parsed and
the lexer / parser errors (several per run)
check(src) -> Result<Module, Vec<Diagnostic>> parse + semantic check with the default
Options; Ok carries the warnings in
Module::warnings
check_with(src, &Options) the same with a chosen set of language features
print(&ast) -> String the AST as WGSL text (parse -> print -> parse
gives the same tree)
lex::tokens(src) the tokens (template lists discovered)
ir the checked module: types with layout, globals,
overrides, functions (expression arenas,
statements), entry points with their interface
Diagnostic 1-based line, column in characters, end column,
error / warning, German message, notes
bench the six benchmark shaders of docs/SHADER.md
as WGSL text
Diagnostic::render(&src) with the source line and a caret span
analyze_uniformity(&module, src, &Options) the uniformity analysis alone (uniformity.rs)
compile(src, &CompileOptions) -> Result<Output, Vec<Diagnostic>> check + lower to
SPIR-V, one module per entry point (spirv.rs)
Output::constants / workgroup_size / check_pipeline, check_interface, Limits
pipeline constants and WebGPU's pipeline
checks (pipeline.rs)
Never panics on any input: nesting deeper than parse::MAX_DEPTH is an error, constant
values are capped in size (consteval::MAX_ELEMS), every count is checked.
wgsl crate root#
struct Notea note attached to a diagnostic: where the related declaration isline: u32col: u32end_col: u32msg: String
struct Diagnostica message for the editor: position (1-based; columns count characters, end_col is exclusive and on the same line), error, warning or info (errorandinfoboth false: a warning), German text; start / end: the byte range in the source; notes point at related places ("hier deklariert")line: u32col: u32end_col: u32error: boolinfo: bool-- a message of severity info (diagnostic(info, ...)); it is neither error nor warningmsg: Stringstart: u32end: u32notes: Vec<Note>
impl Diagnostic
fn render(&self, src: &str) -> Stringthe message with its source line and a caret span under the place, and each note the same way, for a terminal:4:29: Fehler: `workgroupBarrier` darf nur in uniformem Kontrollfluss aufgerufen werden 4 | fn g(c: u32) { if c == 0u { workgroupBarrier(); } } | ^^^^^^^^^^^^^^^^struct Optionswhat the checker accepts beyond core WGSLfeatures: u32-- feature::* bits: the language extensions the implementation supports (they apply withoutrequires, as in a browser) and the enable-extensions the device offers (they apply only afterenable)
fn parse(src: &str) -> (Ast, Vec<Diagnostic>)the syntax tree and the syntax errors (empty when the source parses)fn check(src: &str) -> Result<Module, Vec<Diagnostic>>parse and check with the default options: the module (warnings in Module::warnings) or every error found (and the warnings)fn check_with(src: &str, opt: &Options) -> Result<Module, Vec<Diagnostic>>parse and check with the given optionsfn analyze_uniformity(m: &Module, src: &str, opt: &Options) -> Vec<Diagnostic>the uniformity analysis of a checked module alone (check runs it already; for tools and measurements): the diagnostics it givesstruct LineMapthe start of every line (byte offsets); line breaks as WGSL defines them: LF, VT, FF, CR (alone or before LF), NEL, LS, PS
impl LineMap
fn new(src: &str) -> LineMapthe line starts of a sourcefn pos(&self, src: &str, at: u32) -> (u32, u32)1-based line and character column of a byte offsetfn diag(&self, src: &str, start: u32, end: u32, error: bool, msg: String) -> Diagnostica diagnostic for the byte range start..end (end_col stays on the first line)fn line_text<'s>(&self, src: &'s str, line: u32) -> &'s strthe text of a 1-based line without its line breakfn note(&self, src: &str, start: u32, end: u32, msg: String) -> Notea note for the byte range start..end
mod feature
the language extensions (requires) and enable extensions this front end implements; a
module may use an extension only when its bit is set here (Options::features)
/// storage textures with read and read_write access, textureBarrier
READONLY_AND_READWRITE_STORAGE_TEXTURES: u32 = 1 << 0
/// dot4U8Packed, dot4I8Packed, pack4xI8 ... unpack4xU8
PACKED_4X8_INTEGER_DOT_PRODUCT: u32 = 1 << 1
/// pointer parameters in storage / uniform / workgroup, to parts of variables
UNRESTRICTED_POINTER_PARAMETERS: u32 = 1 << 2
/// p.x and p[i] on pointers
POINTER_COMPOSITE_ACCESS: u32 = 1 << 3
/// uniform buffers with the storage layout rules
UNIFORM_BUFFER_STANDARD_LAYOUT: u32 = 1 << 4
/// let of texture and sampler type
TEXTURE_AND_SAMPLER_LET: u32 = 1 << 5
/// the further storage texel formats (r8unorm, rg16float ...)
TEXTURE_FORMATS_TIER1: u32 = 1 << 6
/// @builtin(global_invocation_index) and @builtin(workgroup_index)
LINEAR_INDEXING: u32 = 1 << 7
/// var<immediate> (push constants)
IMMEDIATE_ADDRESS_SPACE: u32 = 1 << 8
/// @builtin(frag_depth, less | greater)
FRAGMENT_DEPTH: u32 = 1 << 9
/// v.xy = ... (swizzle views)
SWIZZLE_ASSIGNMENT: u32 = 1 << 10
/// a uniformity scope of its own for the subgroup and quad functions
SUBGROUP_UNIFORMITY: u32 = 1 << 11
/// @builtin(subgroup_id) and @builtin(num_subgroups)
SUBGROUP_ID: u32 = 1 << 12
/// enable-extensions the device may offer (the WebGPU features)
F16: u32 = 1 << 16
/// enable clip_distances: @builtin(clip_distances)
CLIP_DISTANCES: u32 = 1 << 17
/// enable dual_source_blending: @blend_src
DUAL_SOURCE_BLENDING: u32 = 1 << 18
/// enable primitive_index: @builtin(primitive_index)
PRIMITIVE_INDEX: u32 = 1 << 19
/// enable atomic_vec2u_min_max: atomicStoreMin / Max on atomic<vec2<u32>>
ATOMIC_VEC2U_MIN_MAX: u32 = 1 << 20
/// enable subgroups: the subgroup and quad built-in functions and values
SUBGROUPS: u32 = 1 << 21
/// enable subgroup_size_control: @subgroup_size (turns subgroups on too)
SUBGROUP_SIZE_CONTROL: u32 = 1 << 22
/// what a browser offers and this front end implements: the language features of Chrome
/// 156 except buffer_view (and without fragment_depth, which Chrome offers only with
/// --enable-unsafe-webgpu: implemented, opt-in), the enable-extensions
ALL: u32 = (0x1fff & !FRAGMENT_DEPTH) | 0x7f << 16
const fn for_device(f16: bool, subgroups: bool, subgroup_size_control: bool) -> u32ALL for a device: the enable-extensions it lacks are off, as WebGPU gates them on the features of the device (lib/gpu: Features::shader_f16, subgroups_webgpu, subgroup_size_control)
/// (name, bit, is a language extension) for every extension name WGSL defines; bit 0:
/// known but not implemented here
NAMES: &[(&str, u32, bool)] = &[ ("readonly_and_readwrite_storage_textures", READONLY_A ...
wgsl/ast.rs#
Source: lib/wgsl/ast.rs
ast -- the syntax tree of a WGSL module, every node with its byte span
Ast { directives, decls } the module in source order
Decl fn, var, const, override, alias, struct, const_assert
Stmt / StmtKind every statement of spec section 9 (for and while stay as
written; the IR desugars them)
Expr / ExprKind expressions; a type is an expression too (an identifier
with an optional template list: `array<vec4<f32>, 4>`)
Attr `@name(args)`; @diagnostic keeps its two names
Literals keep their text (the printer writes it back unchanged) and their decoded value.
struct Spana byte range in the sourcestart: u32end: u32
impl Span
fn new(start: u32, end: u32) -> Spanstart..endfn to(self, b: Span) -> Spanfrom the start of self to the end of bfn contains(self, b: Span) -> boolb lies inside selfstruct Identa name with its placename: Stringspan: Span
struct Asta parsed module: directives, then declarations in source orderdirectives: Vec<Directive>decls: Vec<Decl>
enum DirectiveKindenable / requires / diagnosticEnable(Vec<Ident>)Requires(Vec<Ident>)Diagnostic(DiagnosticControl)
struct Directivea directive with its rangekind: DirectiveKindspan: Span
struct DiagnosticControl(severity, rule)or(severity, a.b)severity: Identrule: Identrule2: Option<Ident>
impl DiagnosticControl
fn rule_span(&self) -> Spanthe place of the whole rule nameenum AttrKindthe arguments of an attributePlain { args: Vec<Expr>, parens: bool }-- @name or @name(args)Diagnostic(DiagnosticControl)
struct Attran attribute@name(args)name: Identkind: AttrKindspan: Span
impl Attr
fn args(&self) -> &[Expr]the arguments (none for @diagnostic)struct Parama function parameterattrs: Vec<Attr>name: Identty: Exprspan: Span
struct FnDecla function declarationattrs: Vec<Attr>name: Identparams: Vec<Param>ret: Option<(Vec<Attr>, Expr)>-- the return type and its attributesbody: Block
struct Membera struct memberattrs: Vec<Attr>name: Identty: Exprspan: Span
enum VarKindvar, let, const and override declarationsVarLetConstOverride
struct VarDecla var / let / const / override declarationkind: VarKindattrs: Vec<Attr>templ: Option<Vec<Expr>>-- var<...>: address space and access mode as writtenname: Identty: Option<Expr>init: Option<Expr>span: Span
enum DeclKindthe module-scope declarationsFn(FnDecl)Var(VarDecl)Alias { name: Ident, ty: Expr }Struct { name: Ident, members: Vec<Member> }ConstAssert(Expr)
struct Decla module-scope declaration with its rangekind: DeclKindspan: Span
impl Decl
fn name(&self) -> Option<&Ident>the declared name (None for const_assert)struct Blocka compound statement (attributes, statements)attrs: Vec<Attr>stmts: Vec<Stmt>span: Span
enum CaseSela case selectorDefault(Span)Expr(Expr)
struct Clausea switch clausesels: Vec<CaseSel>default_alone: bool--default:alone (nocase)body: Blockspan: Span
struct ElseIfan else-if clausecond: Exprbody: Blockspan: Span
struct Continuingthe continuing block of a loop, with its optional break-ifbody: Blockbreak_if: Option<Expr>span: Span
enum AssignOp= and the compound assignment operatorsAssignAddSubMulDivRemAndOrXorShrShl
impl AssignOp
fn text(self) -> &'static strthe spellingfn binary(self) -> Option<BinOp>the binary operator of a compound assignmentenum StmtKindthe statementsEmpty--;Block(Block)Return(Option<Expr>)If { attrs: Vec<Attr>, cond: Expr, then: Block, else_ifs: Vec<ElseIf>, else_: Option<Block> }-- if / else if / else (the else-if clauses in order)Switch { attrs: Vec<Attr>, selector: Expr, body_attrs: Vec<Attr>, clauses: Vec<Clause>, body_span: Span }Loop { attrs: Vec<Attr>, body: Block, continuing: Option<Continuing> }For { attrs: Vec<Attr>, init: Option<Box<Stmt>>, cond: Option<Expr>, update: Option<Box<Stmt>>, body: Block }While { attrs: Vec<Attr>, cond: Expr, body: Block }BreakContinueDiscardCall(Expr)-- a function call statement (the expression is a Call)Decl(VarDecl)Assign { lhs: Expr, op: AssignOp, rhs: Expr }Phony(Expr)--_ = eIncr(Expr)Decr(Expr)ConstAssert(Expr)
struct Stmta statement with its rangekind: StmtKindspan: Span
enum UnOpunary operatorsNegNotBitNotDerefAddrOf
impl UnOp
fn text(self) -> &'static strthe spellingenum BinOpbinary operatorsAddSubMulDivRemAndOrXorShlShrLogAndLogOrEqNeLtLeGtGe
impl BinOp
fn text(self) -> &'static strthe spellingfn is_comparison(self) -> bool== != < <= > >=enum ExprKindthe expressionsBool(bool)Int(String, i64, Suffix)-- text, value, suffixFloat(String, f64, Suffix)Ident(Ident, Option<Vec<Expr>>)-- a name with an optional template list (also a type)Call(Ident, Option<Vec<Expr>>, Vec<Expr>)-- callee (a function, a type or a type-generator), template args, argumentsParen(Box<Expr>)Unary(UnOp, Box<Expr>)Binary(BinOp, Box<Expr>, Box<Expr>)Index(Box<Expr>, Box<Expr>)Member(Box<Expr>, Ident)--.name(a member or a swizzle)Error-- what the parser put where an expression failed
struct Expran expression (a type is one too) with its range and heightkind: ExprKindspan: Spandepth: u32-- the height of the tree (a leaf is 1); every pass over it recurses this deep
impl Expr
fn error(span: Span) -> Exprthe placeholder of a failed expressionfn new(kind: ExprKind, span: Span) -> Expra node with its height computed from the children
wgsl/bench.rs#
Source: lib/wgsl/bench.rs
bench -- the six shaders of the GPU benchmark scene as WGSL (lib/wgsl/bench/*.wgsl): the
same bindings and data contract as the SPIR-V shaders of lib/shader/bench.rs (docs/SHADER.md
"Benchmark-Vertrag"); G2c compiles them and compares them with those.
MOVE, CULL, CULL_RESET, VS_INSTANCED, VS_SINGLE, FS_LAMBERT the source texts
ALL (name, text) of all six
The push constants are `var<immediate> pc: Push` (language extension
immediate_address_space, which Chrome supports): 20 bytes at offset 0 as before, so
vs_single keeps reading pc.object_index and move / cull keep their parameters. Every
entry point is `main`; each file is a complete module.
/// move.wgsl
MOVE: &str = include_str!("bench/move.wgsl")
/// cull.wgsl
CULL: &str = include_str!("bench/cull.wgsl")
/// cull_reset.wgsl
CULL_RESET: &str = include_str!("bench/cull_reset.wgsl")
/// vs_instanced.wgsl
VS_INSTANCED: &str = include_str!("bench/vs_instanced.wgsl")
/// vs_single.wgsl
VS_SINGLE: &str = include_str!("bench/vs_single.wgsl")
/// fs_lambert.wgsl
FS_LAMBERT: &str = include_str!("bench/fs_lambert.wgsl")
/// (name, source) of the six shaders
ALL: [(&str, &str); 6] = [ ("move", MOVE), ("cull", CULL), ("cull_reset", CULL_RES ...
wgsl/check.rs#
Source: lib/wgsl/check.rs
check -- the semantic checker, module level: directives, the module-scope declarations in
dependency order, name resolution, types, attributes, structs with layout, global
variables, overrides, consts, function signatures, const_assert; then check_expr.rs (the
expressions), check_stmt.rs (function bodies, behaviors) and entry.rs (entry points)
check(src, &ast, &opts) -> Result<Module, Vec<Diagnostic>>
Order: every module-scope declaration's dependencies (the module-scope names it mentions,
respecting local scopes) are collected first; an iterative depth-first search orders them
(callees before callers) and reports cycles ("zyklische Abhängigkeit"), so no check
recurses from one declaration into another. Errors: each failing construct reports once
and yields E; whatever depends on it fails silently. At most MAX_ERRORS errors are kept.
impl ir::ExprKind
fn children(&self, out: &mut Vec<ExprId>)push the child expressions
wgsl/ir.rs#
Source: lib/wgsl/ir.rs
ir -- the checked module: what the back end (G2c) lowers to SPIR-V without re-deriving
anything (docs/WGSL.md, "Das IR")
Module types (interned: equal types have equal TypeIds), structs with their
layout, globals, overrides, functions (callees before callers), entry
points with their interface, the module-scope expression arena, enabled
extensions, diagnostic filters (read by the uniformity analysis)
Type Scalar / Vector / Matrix / Atomic / Array (count, stride) / Struct /
Pointer / Reference / SwizzleView / Sampler / Texture
Expr / ExprKind one arena per function (Function::exprs) and one for module scope
(Module::exprs); every node has its concrete type
Stmt structured statements; for and while are desugared to Loop
Value a folded constant (the value of every const-expression)
Conventions:
* Every const-expression is folded into ExprKind::Const with a concrete type; abstract
types (AbstractInt, AbstractFloat) never appear in function or module arenas.
* References are explicit: Global(g) and Local(var) have Reference type; Load(e) reads
one; AddrOf / Deref convert between Reference and Pointer. Index and Member on a
reference give a reference; on a value they give a value. p.x on a pointer
(pointer_composite_access) is written Member(Deref(p), 0).
* Swizzle(base, comps, n): on a value: a vector value; on a reference with read_write
access (swizzle_assignment) the node has SwizzleView type -- Load reads the vector,
Assign / Compound write the listed components. A single-letter swizzle is Member(base,
component).
* Binary operands have equal types except: matrix * scalar, scalar * matrix, matrix *
vector, vector * matrix, matrix * matrix, float vector * float scalar (both orders, for
OpVectorTimesScalar), the shifts (right operand u32 / vecN<u32>), and comparisons
(bool result). Other mixed scalar / vector arithmetic gets an explicit Splat.
* Builtin(f, args): the arguments already have the types of the chosen overload; the
overload is determined by f and the argument types.
* Construct: vectors from scalars and vectors (as written), matrices from column vectors
(scalar arguments are grouped into Construct columns), arrays and structs from
elements / members. Convert: numeric conversion (scalar, vector or matrix); identity
conversions are removed.
* Overrides stay symbolic: Override(i) leaves inside expressions; override-expressions
at module scope (override initializers, private var initializers, workgroup sizes,
override-sized array counts) live in Module::exprs.
* Compound assignment and ++ / -- evaluate the left side once: Compound { lhs, op, rhs }
(++ is Compound with op Add and the constant 1).
type TypeId = u32an index into Module::types (equal types have equal ids)type ExprId = u32an index into an expression arena (Function::exprs or Module::exprs)
// the scalar TypeIds (interned first, in this order)
BOOL: TypeId = 0
/// AbstractInt (never in a checked module's arenas)
AINT: TypeId = 1
/// AbstractFloat (never in a checked module's arenas)
AFLOAT: TypeId = 2
/// i32
I32: TypeId = 3
/// u32
U32: TypeId = 4
/// f32
F32: TypeId = 5
/// f16
F16: TypeId = 6
/// the type of a call without a result (Call / Builtin nodes of void functions)
VOID: TypeId = 7
enum Scalarthe scalar types (AbstractInt / AbstractFloat only for analysis)BoolAbstractIntAbstractFloatI32U32F32F16
impl Scalar
const ALL: [Scalar; 7] = [Scalar::Bool, Scalar::AbstractInt, Scalar::AbstractFloat ...every scalar in TypeId orderfn name(self) -> &'static strthe WGSL spellingfn id(self) -> TypeIdthe TypeId of the scalarfn is_abstract(self) -> boolAbstractInt or AbstractFloatfn is_float(self) -> boolAbstractFloat, f32, f16fn is_int(self) -> boolAbstractInt, i32, u32fn is_numeric(self) -> boolnot boolfn size(self) -> u32byte size in memory (bool: 4)enum AddressSpacethe address spaces (Handle: textures and samplers)FunctionPrivateWorkgroupUniformStorageImmediateHandle
impl AddressSpace
fn name(self) -> &'static strthe WGSL spellingenum Accessaccess modes of memory viewsReadWriteReadWrite
impl Access
fn name(self) -> &'static strthe WGSL spellingfn readable(self) -> boolread or read_writefn writable(self) -> boolwrite or read_writeenum ArrayCountthe element count of an array typeFixed(u32)Override(u32)-- an identifier naming an override (Module::overrides index)Expr(ExprId)-- another override-expression (Module::exprs; every such type is distinct)Runtime
enum TexDimtexture dimensionalitiesD1D2D2ArrayD3CubeCubeArray
impl TexDim
fn suffix(self) -> &'static strthe type-name suffix ("2d_array")fn coords(self) -> u8coordinate components (cube: the direction vector)fn arrayed(self) -> bool2d_array or cube_arrayenum TexelFormatthe texel formats of storage textures (spec 6.6.1)Rgba8unormRgba8snormRgba8uintRgba8sintRgba16unormRgba16snormRgba16uintRgba16sintRgba16floatRg8unormRg8snormRg8uintRg8sintRg16unormRg16snormRg16uintRg16sintRg16floatR32uintR32sintR32floatRg32uintRg32sintRg32floatRgba32uintRgba32sintRgba32floatBgra8unormR8unormR8snormR8uintR8sintR16unormR16snormR16uintR16sintR16floatRgb10a2unormRgb10a2uintRg11b10ufloat
/// (name, format, needs texture_formats_tier1)
TEXEL_FORMATS: [(&str, TexelFormat, bool); 40] = [ ("rgba8unorm", TexelFormat::Rgba8unorm, false), ("rgba8 ...
impl TexelFormat
fn name(self) -> &'static strthe WGSL spellingfn channel(self) -> Scalarthe channel type in the shader: f32, i32 or u32enum TexKindtexture kinds (with the sampled type, format and access where they have one)Sampled(Scalar)-- texture_1d<T> ... texture_cube_array<T>; T is f32, i32 or u32Multisampled(Scalar)DepthDepthMultisampledStorage(TexelFormat, Access)External
enum Typea type (see the module comment)Scalar(Scalar)Vector(u8, Scalar)Matrix(u8, u8, Scalar)-- columns, rows, element (f32, f16 or AbstractFloat)Atomic(TypeId)-- atomic<i32>, atomic<u32> or atomic<vec2<u32>> (the TypeId of the inner type)Array { elem: TypeId, count: ArrayCount, stride: u32 }-- stride: roundUp(align, size) of the element (0 for abstract elements)Struct(u32)-- Module::structs indexPointer { space: AddressSpace, store: TypeId, access: Access }Reference { space: AddressSpace, store: TypeId, access: Access }SwizzleView { space: AddressSpace, elem: Scalar, n: u8, k: u8 }-- swizzle<AS, S, N, K>: K components of a vecN<S> in memory (swizzle_assignment)Sampler { comparison: bool }Texture(TexDim, TexKind)Void-- no value: the type of a call to a function without result type (TypeId VOID)
enum BuiltinStructthe predeclared structures of built-in resultsFrexp(u8, Scalar)-- frexp: (vector width or 1, fract scalar type)Modf(u8, Scalar)-- modf: (vector width or 1, scalar type)AtomicCompareExchange(Scalar)-- atomicCompareExchangeWeak: old_value type (i32 / u32)
enum BuiltinValuethe built-in values of @builtin(...)VertexIndexInstanceIndexClipDistancesPositionFrontFacingFragDepthPrimitiveIndexSampleIndexSampleMaskLocalInvocationIdLocalInvocationIndexGlobalInvocationIdGlobalInvocationIndexWorkgroupIdWorkgroupIndexNumWorkgroupsSubgroupInvocationIdSubgroupSizeSubgroupIdNumSubgroups
/// (name, value) of every built-in value
BUILTIN_VALUES: [(&str, BuiltinValue); 20] = [ ("vertex_index", BuiltinValue::VertexIndex), ("instance ...
impl BuiltinValue
fn name(self) -> &'static strthe WGSL spellingenum InterpType@interpolate typesPerspectiveLinearFlat
enum InterpSampling@interpolate samplingsCenterCentroidSampleFirstEither
enum DepthModethe depth mode of @builtin(frag_depth, less | greater) (fragment_depth)LessGreater
struct Iothe IO attributes of a parameter, return type or struct memberbuiltin: Option<BuiltinValue>depth_mode: Option<DepthMode>location: Option<u32>blend_src: Option<u32>interpolate: Option<(InterpType, Option<InterpSampling>)>-- as written (None: not written)invariant: bool
struct StructMembera member with its layout and IO attributesname: Stringty: TypeIdoffset: u32-- byte offset, size (@size or the type's), alignment (@align or the type's)size: u32align: u32io: Iospan: Span
struct Structa structure with its layout (the same in every address space)name: Stringmembers: Vec<StructMember>align: u32size: u32-- roundUp(align, end of the last member); with a runtime-sized last member: the size without its elementsruntime_sized: boolbuiltin: Option<BuiltinStruct>span: Span
enum Valuea folded constant; Zero is the zero value of whatever type the node hasBool(bool)AInt(i64)AFloat(f64)I32(i32)U32(u32)F32(f32)F16(f32)-- an f16 value (exactly representable in f16), held as f32Comp(Vec<Value>)-- vector, matrix (columns), array or struct componentsZero
fn f16_bits(x: f32) -> u16the bits of an f16 value held as f32enum UnaryOpunary operators (&, * are AddrOf / Deref)NegNot-- logical not (bool, vecN<bool>)BitNot
enum Builtinthe built-in functions (spec section 17; no buffer views)AllAnySelectArrayLengthAbsAcosAcoshAsinAsinhAtanAtanhAtan2CeilClampCosCoshCountLeadingZerosCountOneBitsCountTrailingZerosCrossDegreesDeterminantDistanceDotDot4U8PackedDot4I8PackedExpExp2ExtractBitsFaceForwardFirstLeadingBitFirstTrailingBitFloorFmaFractFrexpInsertBitsInverseSqrtLdexpLengthLogLog2MaxMinMixModfNormalizePowQuantizeToF16RadiansReflectRefractReverseBitsRoundSaturateSignSinSinhSmoothstepSqrtStepTanTanhTransposeTruncDpdxDpdxCoarseDpdxFineDpdyDpdyCoarseDpdyFineFwidthFwidthCoarseFwidthFineTextureDimensionsTextureGatherTextureGatherCompareTextureLoadTextureNumLayersTextureNumLevelsTextureNumSamplesTextureSampleTextureSampleBiasTextureSampleCompareTextureSampleCompareLevelTextureSampleGradTextureSampleLevelTextureSampleBaseClampToEdgeTextureStoreAtomicLoadAtomicStoreAtomicAddAtomicSubAtomicMaxAtomicMinAtomicAndAtomicOrAtomicXorAtomicExchangeAtomicCompareExchangeWeakAtomicStoreMinAtomicStoreMaxPack4x8snormPack4x8unormPack4xI8Pack4xU8Pack4xI8ClampPack4xU8ClampPack2x16snormPack2x16unormPack2x16floatUnpack4x8snormUnpack4x8unormUnpack4xI8Unpack4xU8Unpack2x16snormUnpack2x16unormUnpack2x16floatStorageBarrierTextureBarrierWorkgroupBarrierWorkgroupUniformLoadSubgroupAddSubgroupExclusiveAddSubgroupInclusiveAddSubgroupAllSubgroupAndSubgroupAnySubgroupBallotSubgroupBroadcastSubgroupBroadcastFirstSubgroupElectSubgroupMaxSubgroupMinSubgroupMulSubgroupExclusiveMulSubgroupInclusiveMulSubgroupOrSubgroupShuffleSubgroupShuffleDownSubgroupShuffleUpSubgroupShuffleXorSubgroupXorQuadBroadcastQuadSwapDiagonalQuadSwapXQuadSwapY
enum ExprKindexpression nodes (see the module comment for the conventions)Const(Value)Override(u32)Global(u32)Local(u32)Param(u32)Load(ExprId)AddrOf(ExprId)Deref(ExprId)Index(ExprId, ExprId)Member(ExprId, u32)-- struct member or vector component (constant index)Swizzle(ExprId, [u8; 4], u8)-- base, components, count (2..4)Unary(UnaryOp, ExprId)Binary(BinOp, ExprId, ExprId)Construct(Vec<ExprId>)Splat(ExprId)Convert(ExprId)Bitcast(ExprId)Call(u32, Vec<ExprId>)-- Module::functions index, argumentsBuiltin(Builtin, Vec<ExprId>)
struct Expran expression node with its concrete type and source rangekind: ExprKindty: TypeIdspan: Span
struct Casea switch clauseselectors: Vec<i64>-- the selector values (i32 or u32, as i64)default: boolbody: Vec<Stmt>
enum Stmtstatements (for and while are desugared to Loop)Block(Vec<Stmt>)Var { local: u32, init: Option<ExprId> }Let { local: u32, init: ExprId }Assign { lhs: ExprId, rhs: ExprId }Compound { lhs: ExprId, op: BinOp, rhs: ExprId }Phony(ExprId)--_ = e: evaluate and dropCall(ExprId)-- a call whose result (if any) is droppedIf { cond: ExprId, then: Vec<Stmt>, else_: Vec<Stmt> }Switch { selector: ExprId, cases: Vec<Case> }Loop { body: Vec<Stmt>, continuing: Vec<Stmt>, break_if: Option<ExprId> }BreakContinueReturn(Option<ExprId>)Discard
enum LocalKindwhat a local isVar-- a function-scope variable: Local(i) is a reference to tyLet-- a let: Local(i) is the value (ty may be a pointer, texture or sampler)
struct Locala function-scope var or letname: Stringty: TypeIdkind: LocalKindspan: Span
struct Parama function parameter (io: the IO attributes of an entry point parameter)name: Stringty: TypeIdio: Iospan: Span
enum Stageshader stagesVertexFragmentCompute
impl Stage
fn name(self) -> &'static strthe WGSL spellingstruct Functiona checked functionname: Stringparams: Vec<Param>ret: Option<TypeId>ret_io: Iostage: Option<Stage>must_use: boollocals: Vec<Local>exprs: Vec<Expr>body: Vec<Stmt>calls: Vec<u32>-- the functions called directlyglobals: Vec<u32>-- module-scope variables and overrides used, including by callees (ascending)overrides: Vec<u32>uses_discard: bool-- discard reachable from here (callees included)span: Span
struct Binding@group / @binding of a resourcegroup: u32binding: u32
struct Globala module-scope variablename: Stringspace: AddressSpaceaccess: Accessty: TypeId-- the store typebinding: Option<Binding>init: Option<ExprId>-- Module::exprs (private variables: a Const or an override-expression)std140: bool-- uniform buffers: the type also satisfies the strict uniform layout rules (16-byte array strides and struct alignment, std140-compatible); always true elsewherespan: Span
struct Overridea pipeline-overridable constantname: Stringid: Option<u16>-- @id(n)ty: TypeId-- a concrete scalar typeinit: Option<ExprId>-- the default (Module::exprs)span: Span
struct Consta module-scope const (folded; kept for tools, the IR never refers to it)name: Stringty: TypeIdvalue: Valuespan: Span
enum WgSizeone workgroup_size dimensionConst(u32)Override(ExprId)-- an override-expression in Module::exprs
enum IoKindhow a stage input / output is boundBuiltin(BuiltinValue)Location { location: u32, blend_src: Option<u32>, interp: Option<(InterpType, InterpSampling)> }-- location, blend_src, interpolation with the defaults applied (None for integer vertex inputs and fragment outputs, where it does not apply)
struct IoVarone shader stage input or outputname: String-- "param" or "param.member" (outputs: "return" or "return.member")ty: TypeIdparam: Option<u32>-- the parameter (inputs; None for outputs)member: Option<u32>-- the struct member when the parameter / return type is a structkind: IoKindinvariant: booldepth_mode: Option<DepthMode>
struct EntryPointan entry point and its interfacename: Stringfunc: u32-- Module::functions indexstage: Stageworkgroup_size: Option<[WgSize; 3]>-- compute onlysubgroup_size: Option<WgSize>-- @subgroup_size (compute only, subgroup_size_control)inputs: Vec<IoVar>outputs: Vec<IoVar>globals: Vec<u32>-- every module-scope variable statically accessed (ascending)resources: Vec<(u32, Binding)>-- the resource variables among them with their (group, binding)overrides: Vec<u32>-- the overrides statically accessed (also through initializers, array sizes and the workgroup size)immediate: Option<u32>-- the immediate data variable, if one is used
enum Severitydiagnostic filter severitiesErrorWarningInfoOff
struct DiagnosticFiltera diagnostic filter: the affected range (the whole module for global ones)severity: Severityrule: String-- "derivative_uniformity", "a.b"range: Spanglobal: bool
struct Modulethe checked moduletypes: Vec<Type>structs: Vec<Struct>globals: Vec<Global>overrides: Vec<Override>consts: Vec<Const>functions: Vec<Function>entry_points: Vec<EntryPoint>exprs: Vec<Expr>-- module-scope expressions (override-expressions and folded initializers)enables: u32-- feature::* bits enabled withenableand named inrequiresrequires: u32diagnostic_filters: Vec<DiagnosticFilter>warnings: Vec<Diagnostic>
impl Module
fn ty(&self, t: TypeId) -> &Typethe type of a TypeIdfn type_name(&self, t: TypeId) -> Stringthe WGSL spelling of a type ("vec3<f32>", "ptr<storage, S, read>")fn function(&self, name: &str) -> Option<&Function>a function by namefn entry_point(&self, name: &str) -> Option<&EntryPoint>an entry point by namefn global(&self, name: &str) -> Option<&Global>a module-scope variable by namefn struct_named(&self, name: &str) -> Option<&Struct>a structure by namefn type_name(types: &[Type], structs: &[Struct], t: TypeId) -> Stringsee Module::type_name
wgsl/lex.rs#
Source: lib/wgsl/lex.rs
lex -- the tokens of WGSL (spec section 3) and template list discovery (3.9)
tokens(src) -> (Vec<Token>, Vec<Diagnostic>) every token (no blankspace, no comments),
ending with Eof; never fails: a bad character, an
unterminated comment, a reserved word or a malformed
number becomes an Error token (or a Reserved one) plus
a diagnostic
discover_templates(src) the byte offsets of every '<' that starts and every '>'
that ends a template list (the spec's algorithm, code
point by code point); tokens() turns them into
TemplateStart / TemplateEnd
int_value(text) / float_value(text) decode a literal token (range rules of 3.5.2)
round_bits(m, e, sticky, fmt) m * 2^e rounded to f16 / f32 / f64 (nearest even)
Blankspace is Pattern_White_Space (space, tab, LF, VT, FF, CR, NEL, LRM, RLM, LS, PS);
block comments nest; identifiers are XID_Start (or _) + XID_Continue (xid.rs); `_` alone
is the Underscore token, `__x` is an error. Punctuation is matched longest first except
where discovery found a template delimiter. Splitting `--` / `&&` where the grammar wants
two tokens (`a--b` is `a - -b`) is the parser's job.
enum Toktoken kinds: identifiers, literals, keywords, syntactic tokens, template delimitersIdentIntFloatReserved-- a reserved word (reported; the parser takes it as an identifier)ErrorEofAliasBreakCaseConstConstAssertContinueContinuingDefaultDiagnosticDiscardElseEnableFalseFnForIfLetLoopOverrideRequiresReturnStructSwitchTrueVarWhileAndAndAndArrowAtSlashBangLBracketRBracketLBraceRBraceColonCommaEqEqEqNotEqGtGeShrLtLeShlPercentMinusMinusMinusDotPlusPlusPlusOrOrOrLParenRParenSemiStarTildeUnderscoreXorPlusEqMinusEqStarEqSlashEqPercentEqAndEqOrEqXorEqShrEqShlEqTemplateStartTemplateEnd
/// the keywords of spec section 16.1
KEYWORDS: [(&str, Tok); 26] = [ ("alias", Tok::Alias), ("break", Tok::Break), ("case", ...
/// the reserved words of spec section 16.2, sorted
RESERVED: &[&str] = &[ "NULL", "Self", "abstract", "active", "alignas", "alig ...
impl Tok
fn text(self) -> &'static strthe spelling for messages (";", "Bezeichner")fn is_keyword(self) -> boolone of KEYWORDSstruct Tokena token: kind and byte rangekind: Tokstart: u32end: u32
fn is_blank(c: char) -> boolPattern_White_Spacefn scan_number(src: &str, i: usize) -> Option<(usize, bool)>the end of the numeric literal starting at i (longest match of the literal regexes), and whether it is a float; None when no literal starts herefn scan_ident(src: &str, i: usize) -> Option<usize>the end of an ident_pattern_token at i (also_alone)fn discover_templates(src: &str) -> (Vec<u32>, Vec<u32>)the template list delimiters (spec 3.9): (starts, ends), ascending byte offsetsfn word_kind(w: &str) -> Toka keyword, a reserved word or an identifierfn tokens(src: &str) -> (Vec<Token>, Vec<Diagnostic>)see the module commentenum Suffixthe suffix of a numeric literalNoneIUFH
fn int_value(text: &str) -> Result<(i64, Suffix), String>an integer literal's value and suffix; Err: a German message (out of range)enum Fmtthe format a float literal is rounded toF16F32F64
fn round_bits(m: u128, e: i64, sticky: bool, fmt: Fmt) -> Option<(f64, bool)>m * 2^e (plus a sticky bit for nonzero digits beyond m) rounded to nearest even in fmt: Some((value, exact)), None on overflow; the value is returned as f64 (exact for every fmt)fn f64_parts(x: f64) -> (u128, i64, bool)decompose a finite f64 into (mantissa, exponent) with x = m * 2^efn round_f64(x: f64, fmt: Fmt) -> Option<f64>round a finite f64 to f16 / f32 (nearest even): None on overflowfn float_value(text: &str) -> Result<(f64, Suffix), String>a float literal's value (in f64; exact for the suffix's type) and suffix; Err: a German message (overflow, an inexact hexadecimal f / h literal)
wgsl/parse.rs#
Source: lib/wgsl/parse.rs
parse -- the WGSL parser: recursive descent over the tokens of lex.rs (the grammar of spec
section 18), with error recovery
parse(src) -> (Ast, Vec<Diagnostic>) the tree of everything that parsed and the errors
of lexer and parser (the first error of a
statement or declaration; at most MAX_ERRORS)
Expressions follow the grammar exactly, including what it forbids: `&`, `|` and `^` take
unary operands and do not mix with each other or with other operators; a shift takes
unary operands; comparisons do not chain; `&&` and `||` do not mix. Each of these gets
its own message ("`&` und `|` dürfen nicht ohne Klammern gemischt werden").
Tokens are split where the grammar needs the shorter one: `a--b` is `a - (-b)`, `&&x` is
`&(&x)` (spec 3.1: the longest token valid in the parser state).
Recovery: an error ends the statement; the parser skips to the next `;` or `}` of the
same brace level (inside a function) or to the next declaration keyword at brace level 0.
Stack: nesting deeper than MAX_DEPTH (blocks, statements, parentheses, template lists,
unary operators, and the links of operator, postfix and else-if chains -- every later
pass recurses over them) is an error, never a stack overflow.
/// nesting limit (see the module comment)
MAX_DEPTH: u32 = 128
/// braces inside a function (the function body counts; WGSL guarantees 127)
MAX_BRACES: u32 = 127
/// the height of an expression tree (operator chains included)
MAX_EXPR_DEPTH: u32 = 256
/// the parser stops after this many errors
MAX_ERRORS: usize = 25
fn parse(src: &str) -> (Ast, Vec<Diagnostic>)see the module comment
wgsl/pipeline.rs#
Source: lib/wgsl/pipeline.rs
pipeline -- what WebGPU checks when it creates a pipeline from a compiled entry point
(docs/WGSL.md "Overrides" and "Pipeline-Prüfungen")
output.constants(entry, &[(key, value)]) -> Result<Vec<(u32, f64)>, String>
the pipeline constants for lib/gpu (gpu::Constant { id, value }): keys as in WebGPU's
GPUProgrammableStage.constants (the override's name, or its @id as a decimal number
when it has one), values converted the way WebGPU converts them; every override the
entry point uses is then evaluated on the CPU (initializers with the front end's
constant evaluator) and every specialization constant of the module gets its final
value, the hidden ones (workgroup sizes, array counts) too. Errors as WebGPU
reports them: an unknown key, a value out of the type's range, an override without
initializer left unset, an evaluation error (division by zero ...), a workgroup size
or array count of 0
output.workgroup_size(entry, constants) -> Result<[u32; 3], String>
output.check_pipeline(entry, constants, &Limits) -> Result<(), String> the above plus the
limits (workgroup size and invocations, workgroup memory, colour targets, inter-stage
locations, immediate bytes), the storage texture formats WebGPU's core allows and the
function bodies the entry point reaches: with the overrides' values an expression may
become a constant that is an error (1 / a, sqrt(a), v[a], x << a, clamp(x, a, b) ...)
check_interface(vertex, fragment) -> Result<(), String> every fragment input has a vertex
output at its location with the same component type and count (at least)
Limits::WEBGPU WebGPU's default limits (what a browser gives without requiredLimits)
struct Limitsthe limits a pipeline is checked againstmax_compute_invocations: u32max_workgroup_size: [u32; 3]max_workgroup_storage: u32max_color_attachments: u32max_inter_stage_variables: u32max_immediate_size: u32bgra8unorm_storage: bool-- the device offers bgra8unorm-storagetexture_formats_tier2: bool-- texture-formats-tier2: read_write storage textures of more formatssubgroup_min_size: u32-- the sizes @subgroup_size may ask for (subgroupMinSize, subgroupMaxSize of the adapter)subgroup_max_size: u32
impl Limits
const WEBGPU: Limits = Limits { max_compute_invocations: 256, max_workgroup_size ...WebGPU's default limits (Chrome 156 without requiredLimits)
impl Output
fn constants(&self, entry: &str, given: &[(&str, f64)]) -> Result<Vec<(u32, f64)>, String>the pipeline constants (SpecId, value) of an entry point for WebGPU-style constants (see the module comment); pass them to lib/gpu as Constant { id, value }fn workgroup_size(&self, entry: &str, given: &[(&str, f64)]) -> Result<[u32; 3], String>the workgroup size of a compute entry point with these pipeline constantsfn subgroup_size(&self, entry: &str, given: &[(&str, f64)]) -> Result<Option<u32>, String>the @subgroup_size of a compute entry point with these pipeline constants (None: it has none)fn check_pipeline(&self, entry: &str, given: &[(&str, f64)], lim: &Limits) -> Result<(), String>what WebGPU checks when it creates a pipeline from this entry point (module comment)fn check_interface(m: &Module, vs: &EntryOut, fs: &EntryOut) -> Result<(), String>WebGPU's inter-stage rules for a vertex and a fragment entry point: every fragment input at a location has a vertex output there with the same component type, at least as many components and the same interpolation
wgsl/print.rs#
Source: lib/wgsl/print.rs
print -- the AST as WGSL text: four-space indentation, one statement per line, literals as
written, parentheses exactly where the tree has Paren nodes (so parse(print(ast)) gives
the same tree, spans aside; comments are not kept)
print(&ast) -> String
fn print(ast: &Ast) -> Stringsee the module comment
wgsl/spirv.rs#
Source: lib/wgsl/spirv.rs
spirv -- the back end (step G2c of the GPU plan; docs/WGSL.md "Back-End"): the checked IR
lowered to SPIR-V with lib/shader, one SPIR-V module per entry point
compile(src, &CompileOptions) -> Result<Output, Vec<Diagnostic>> check + lower
compile_module(&Module, &CompileOptions) the same for a module checked before
Output { entries, overrides, module, warnings }
EntryOut: name, stage, words, workgroup size (with the defaults), resources with
(group, binding, kind, minimum size), immediate bytes, stage inputs / outputs, the
device features the module needs, the specialization constants it declares
output.constants(entry, &[(key, value)]) the pipeline constants for lib/gpu (pipeline.rs)
Levels: CompileOptions::minor = shader::BASIS (SPIR-V 1.3, Vulkan 1.1) or shader::VOLL
(SPIR-V 1.6, Vulkan 1.3).
Types: every WGSL type has a value type (function, private and workgroup memory, SSA values)
and, when it is host-shareable, a laid-out type (Offset, ArrayStride, MatrixStride; uniform,
storage and push-constant memory). SPIR-V 1.4+ (Vulkan's VUID-StandaloneSpirv-None-10684)
forbids explicit layouts outside those storage classes: at Voll the two are different types and
loads and stores of composites convert with OpCopyLogical; at Basis (1.3) the laid-out type
is the value type too. Buffers: the store type is wrapped in a Block struct { inner } unless
it is a struct with a runtime-sized array (that struct is the Block: Vulkan allows runtime
arrays only as the last member of the Block itself).
Overrides: by default every override an entry point uses is a specialization constant
(SpecId = @id, or OVERRIDE_BASE + its index without @id); override-expressions that size a
workgroup or an array are hidden u32 specialization constants (HIDDEN_BASE + the expression).
Output::constants evaluates every override on the CPU (the front end's constant evaluator)
and returns the values of all of them, so derived overrides need no OpSpecConstantOp.
CompileOptions::constants substitutes the values instead (Tint's way): no specialization
constants at all.
The function bodies: spirv_func.rs (statements, expressions, memory, calls, the entry
point wrapper), spirv_builtin.rs (the built-in functions and textures).
/// the SpecId of an override without @id: OVERRIDE_BASE + its index in Module::overrides
OVERRIDE_BASE: u32 = 0x1_0000
/// the SpecId of a hidden constant (a workgroup size or array count from an override-expression):
/// HIDDEN_BASE + the expression's index in Module::exprs
HIDDEN_BASE: u32 = 0x2_0000
struct CompileOptions<'a>what compile doesminor: u32-- shader::BASIS (SPIR-V 1.3, Vulkan 1.1) or shader::VOLL (SPIR-V 1.6, Vulkan 1.3); 4 and 5 work as wellentry: Option<&'a str>-- one entry point (None: every entry point of the module)constants: Option<&'a [(&'a str, f64)]>-- None: overrides become specialization constants (set them with Output::constants); Some: the pipeline constants as WebGPU takes them (key: the override's name, or its @id as a decimal number), substituted as constantsfeatures: u32-- the front end's features (Options::features)robust: bool-- WebGPU's robustness: indices clamped to the array, vector, matrix, runtime array (arrayLength) and texture bounds, out-of-bounds texture stores skippedexact: bool-- NoContraction on every float addition, subtraction, multiplication, division and product: no fused multiply-add, results as the operations are written (WGSL itself lets an implementation contract)
impl CompileOptions<'_>
const fn new(minor: u32) -> CompileOptions<'static>levelminor, every entry point, specialization constants, robust, contraction allowedenum ResourceKindwhat a binding holdsUniformBufferStorageBuffer { read_only: bool }Texture { dim: TexDim, kind: TexKind }-- texture_1d<T> ... texture_cube_array<T>, texture_multisampled_2d, the depth texturesStorageTexture { dim: TexDim, format: TexelFormat, access: Access }Sampler { comparison: bool }ExternalTexture-- texture_external: a plain 2D float texture here
struct Resourcea resource of an entry point (lib/gpu: one Binding per resource)group: u32binding: u32name: Stringkind: ResourceKindmin_size: u64-- buffers: the smallest binding size the shader may access (a runtime-sized array with one element; WebGPU's minBindingSize); 0 otherwise
struct StageVarone stage input or outputname: Stringkind: IoKindty: TypeId-- the WGSL type (Module::types)
struct Needsdevice features a module needs beyond the level's coref16: bool-- f16 arithmetic (shaderFloat16)storage16: bool-- f16 in storage buffers / uniform buffers / push constants (the 16-bit storage features)uniform16: boolpush16: booluniform_standard_layout: bool-- a uniform buffer whose layout is not std140 (uniformBufferStandardLayout)demote: bool-- OpDemoteToHelperInvocation (Voll: discard)int64_atomics: bool-- 64-bit atomics (atomicStoreMin / Max on atomic<vec2<u32>>)storage_without_format: bool-- storage textures without a format in the shader (bgra8unorm)primitive_index: bool-- @builtin(primitive_index): the Geometry capability (geometryShader)clip_distance: bool-- @builtin(clip_distances) (shaderClipDistance)sample_rate_shading: bool-- @interpolate(.., sample), @builtin(sample_index) (sampleRateShading)subgroup_extended_types: bool-- subgroup operations on f16 (shaderSubgroupExtendedTypes)subgroup_ops: u32-- the subgroup operations a module uses (SUBGROUP_* of lib/gpu's Features::subgroup_ops): 1 basic, 2 vote, 4 arithmetic, 8 ballot, 16 shuffle, 32 shuffle relative, 128 quad
enum SpecSourcewhere a specialization constant's value comes fromOverride(u32)-- an override (Module::overrides index)Expr(ExprId)-- a module-scope override-expression as u32 (Module::exprs index)
struct EntryOutan entry point compiledname: Stringstage: Stagewords: Vec<u32>-- the SPIR-V module of this entry point (its entry point has the same name)workgroup_size: Option<[u32; 3]>-- compute: the workgroup size with the overrides' defaults (None: an override without default decides it; Output::workgroup_size computes it for pipeline constants)subgroup_size: Option<u32>-- @subgroup_size with the overrides' defaults (None: not written, or an override without default; Output::subgroup_size computes it for pipeline constants)resources: Vec<Resource>immediate_size: u32-- bytes of the var<immediate> block (0: none); lib/gpu: PipelineLayoutDesc::push_constantsinputs: Vec<StageVar>outputs: Vec<StageVar>needs: Needsspec: Vec<(u32, SpecSource)>-- the specialization constants declared: (SpecId, source)overrides: Vec<u32>-- the overrides the entry point uses (Module::overrides indices)
struct OverrideInfoan override of the modulename: Stringid: u32-- the SpecId (= @id when written)explicit_id: bool-- whether @id was written (then WebGPU keys the constant by the number, not the name)ty: Scalarhas_default: bool-- it has an initializer (else a pipeline must set it)
struct Outputthe result of compileentries: Vec<EntryOut>overrides: Vec<OverrideInfo>module: Module-- the checked module (Output::constants evaluates its overrides)warnings: Vec<Diagnostic>minor: u32
impl Output
fn entry(&self, name: &str) -> Option<&EntryOut>an entry point by namefn compile(src: &str, opt: &CompileOptions) -> Result<Output, Vec<Diagnostic>>check and compile WGSL source (see the module comment)fn compile_module(m: &Module, opt: &CompileOptions) -> Result<Output, Vec<Diagnostic>>compile a checked modulefn compile_library(src: &str, opt: &CompileOptions) -> Result<Output, Vec<Diagnostic>>compile every function of a module without entry points (a library: the functions are lowered with value and pointer parameters, uncalled, beside an empty compute entry pointlibrary; functions with texture or sampler parameters are left out). For tests: SPIR-V validators check every function of a module.
wgsl/xid.rs#
Source: lib/wgsl/xid.rs
xid -- XID_Start / XID_Continue for WGSL identifiers (UAX #31), generated by
tools/gen_xid.py from Python's Unicode 15.1.0 database; do not edit
class(c) -> 0 (no identifier character), 1 (XID_Continue only), 2 (XID_Start)
/// the Unicode version of the table
UNICODE_VERSION: &str = "15.1.0"
fn class(c: char) -> u8the identifier class of a character (see the module comment)fn is_start(c: char) -> boolXID_Startfn is_continue(c: char) -> boolXID_Continue