compileModuleJs()
Function in CPU oracle
Compile a module for the CPU by generating JavaScript, returning the same CpuModule shape compileModule returns and the same results bit for bit.
import { compileModuleJs } from 'typeshade'
The signature, the description and the examples come from the compiler's own source at commit 26de7be8.
Syntax
function compileModuleJs( m: ModuleDecl, opts?: { gpuStubs?: boolean; precision?: CpuPrecision; consoleSink?: ConsoleSink },): CpuModuleParameters
mModuleDeclthe module to evaluate.
optsoptional{ gpuStubs?: boolean; precision?: CpuPrecision; consoleSink?: ConsoleSink }the same
precisionandgpuStubscompileModuletakes.
Return value
the compiled module: fns by name, and setBinding.
Exceptions
ValidationErrorErrorwhen the host forbidsnew Function, which is the case to catch and fall back tocompileModulefor. It also throwsValidationErrorwhen the module fails a core rule, and, once a function runs, the same errorscompileModuledocuments for a GPU-only intrinsic called withgpuStubsoff or a raw statement reached.
Description
Prefer it on any hot path.
Bit identity holds by construction: every operation calls the exact runtime helper the
interpreter calls, or, for a vector operand the IR types say it can and that nothing the
module does can leave missing (a helper’s discard, an element read past an array’s end),
the scalar operation that helper applies to each component, so the two cannot drift apart.
What differs is when the work happens. Instead of walking the IR node by node on every
invocation, this walks each function body once, emits a JavaScript source string and builds
it with new Function, so each call runs straight-line code with real local variables.
The interpreter is the reference and the fallback. A function body holding a shape this
generator cannot emit bit-identically (a raw statement, a placeholder statement, an
assignment target with no expression form) falls back to the interpreter for that function
alone, so a returned module can be part compiled and part interpreted with nothing to do at
the call site. Where new Function itself is unavailable, as on a host whose content
security policy forbids unsafe-eval, construction throws, and the caller catches it and
calls compileModule instead. Reach for the interpreter directly when debugging, too,
since it puts no generated source between you and the IR.
Examples
Example
import { compileModuleJs, compileModule } from 'typeshade'
const cpu = (() => { try { return compileModuleJs(MODULE) } catch { return compileModule(MODULE) // no new Function on this host }})()Targets
| Target | Support | Notes |
|---|---|---|
| WGSL (WebGPU) | Does not apply | |
| GLSL ES 3.00 (WebGL2) | Does not apply | |
| CPU oracle | Supported | Compiles the module to a JavaScript function that runs in f64. |
In the guide
See also
Source
src/core/cpu-codegen.ts, line 1926, at commit 26de7be8