GPU.js ECMAScript Support in Kernel Functions
GPU.js enables developers to run accelerated JavaScript directly on the GPU by transpiling kernel functions into WebGL shader language (GLSL). While GPU.js uses an Abstract Syntax Tree (AST) parser capable of reading standard ECMAScript 6 (ES6 / ES2015) syntax, the execution environment inside a kernel does not support the full ECMAScript specification. Instead, GPU.js only supports a strict, mathematically focused subset of ES5 and ES6 features that can be directly converted into static shader instructions.
The Parsing vs. Compilation Boundary
When writing a GPU.js kernel, the library parses the JavaScript
function using modern ECMAScript standards, allowing developers to write
syntax introduced in ES6, such as let, const,
and basic arrow functions. However, during the compilation step to
WebGL/GLSL, only primitive operations can be translated. Consequently,
while the code looks like standard modern JavaScript, the
runtime behavior inside the kernel function is constrained by the strict
limitations of shader architectures.
Supported ECMAScript Features Inside Kernels
Within the kernel body, you can safely use:
- Variable Declarations: Standard ES5
varand ES6letandconst. - Basic Control Flow: Standard ES5 loops (primarily
fixed-range
forloops) and conditional statements (if,else if,else). - Arithmetic and Logical Operators: Standard
operators including
+,-,*,/,%,++,--,&&,||, and!. - Built-in Math Methods: Select static methods from
the JavaScript
Mathobject, such asMath.sin(),Math.cos(),Math.floor(),Math.sqrt(), andMath.pow(). - Basic Functions: ES5 named functions or ES6 arrow functions, provided they are declared cleanly without closures or external references.
Unsupported ECMAScript Features
Because GPU shaders require predictable memory layouts and parallel execution, the majority of the ECMAScript standard library cannot be executed inside a kernel:
- Complex Data Types: JavaScript Objects
(
{}), dynamic Arrays, Strings, Sets, and Maps cannot be instantiated or manipulated inside kernels. - Modern ES6+ Syntax: Features like template
literals, destructuring, the spread operator (
...), rest parameters, and default parameters are either unsupported or can cause transpile failures. - Asynchronous Features: Promises,
async/await, and generators (ES2017+) are strictly prohibited. - Higher-Order Functions: Array prototype methods
such as
.map(),.filter(),.reduce(), or.forEach()do not translate to GLSL and will fail. - Dynamic Memory & Recursion: Functions cannot be recursive, dynamically allocate memory, or use closures to capture dynamic outside variables.
To achieve maximum compatibility, GPU.js kernels should be treated as C-like computational loops rather than standard ECMAScript environments, limiting code to primitive numeric values and flat computational operations.