compileModuleJs
On this page

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 },
): CpuModule

Parameters

m ModuleDecl

the module to evaluate.

optsoptional { gpuStubs?: boolean; precision?: CpuPrecision; consoleSink?: ConsoleSink }

the same precision and gpuStubs compileModule takes.

Return value

CpuModule

the compiled module: fns by name, and setBinding.

Exceptions

ValidationError

Error when the host forbids new Function, which is the case to catch and fall back to compileModule for. It also throws ValidationError when the module fails a core rule, and, once a function runs, the same errors compileModule documents for a GPU-only intrinsic called with gpuStubs off 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

TargetSupportNotes
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

Edit this page Report a problem