-
-
Save ochafik/9eaa07b009d18b4ef11e262e0af8b6ce to your computer and use it in GitHub Desktop.
TypedFunction: a pure-JS typed function that can be serialized, parallelized, compiled to WASM or GLSL and more!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const f1 = typed(function(a = typed.i32(), | |
| b = typed.i32(), | |
| c = typed.capture.i32(x), | |
| d = typed.capture.i32(() => d, v => d = v)) { | |
| return typed.body(arguments, () => { | |
| }); | |
| await parallel([array1, array2], f1); | |
| await parallel([array1], typed((a = typed.i32(), c = typed.capture.f(f1)) => typed.body({ | |
| })); | |
| function multiply(lhs, rhs, out, N, K, M) { | |
| await parallelIndices([lhs, rhs], typed((i = typed.i32(), j = typed.i32(), | |
| N = typed.capture.i32(() => N), | |
| M = typed.capture.i32(() => M), | |
| K = typed.capture.i32(() => K), | |
| lhs = typed.capture(() => lhs), | |
| rhs = typed.capture(() => rhs), | |
| out = typed.capture(() => out)) => typed.body(() => { | |
| let sum = 0; | |
| for (let k = 0; k < K; k++) { | |
| sum += lhs[i * K + k] * rhs[k * K + j]; | |
| } | |
| out[i, j] = sum; | |
| }))); | |
| , | |
| d = typed.capture.i32(() => d, v => d = v)) => typed.body({ | |
| }); | |
| let fnIsAnalyzing = false; | |
| function fnImpl(f) { | |
| const ast = parse(f.toString()); | |
| const captures = findCaptures(ast); | |
| if (captures.length > 0) throw Please define fn.capture(...) parameters for each of the captured variables: ${captures.join(',')}; | |
| try { | |
| fnIsAnalyzing = true; | |
| assert(isFunction(ast)); | |
| Function(Function(ast.arguments, EmptyBody)); | |
| } finally { | |
| fnIsAnalyzing = false; | |
| } | |
| } | |
| const fn = Object.assign(function(f) { return f }, { | |
| required(x) { return x }, | |
| optional(x) { return x }, | |
| Int32(value = 0) {} | |
| }); | |
| const outer = 123; | |
| const outerCounter = new AtomicInt(0); | |
| f = typed((x = typed.arg('i32'), y = typed.arg('i32'), c = typed.capture('f32', 10.0)) => { | |
| outerCounter += i; | |
| }); | |
| f = fn((x = fn.required(fn.Int32()), y = fn.optional(fn.Int32(), 0), capture = fn.capture(outer), dynCapture = f.capture(() => outer)) => { | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment