Skip to content

Commit

Permalink
Use WebAssembly.Function constructor if available (#9908)
Browse files Browse the repository at this point in the history
With the type reflection proposal, we will get a way more efficient way
to convert a JS function into a wasm exported function. Use that if
available.
  • Loading branch information
backes authored and kripken committed Nov 27, 2019
1 parent 5486c4a commit 0f848e0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -441,3 +441,4 @@ a license to everyone to use it as detailed in LICENSE.)
* Gergely Nagy <[email protected]>
* Jan Habermann <[email protected]>
* John Granström <[email protected]>
* Clemens Backes <[email protected]> (copyright owned by Google, Inc.)
24 changes: 21 additions & 3 deletions src/support.js
Original file line number Diff line number Diff line change
Expand Up @@ -661,14 +661,32 @@ var functionPointers = new Array({{{ RESERVED_FUNCTION_POINTERS }}});

#if WASM
// Wraps a JS function as a wasm function with a given signature.
// In the future, we may get a WebAssembly.Function constructor. Until then,
// we create a wasm module that takes the JS function as an import with a given
// signature, and re-exports that as a wasm function.
function convertJsFunctionToWasm(func, sig) {
#if WASM2JS
return func;
#else // WASM2JS

// If the type reflection proposal is available, use the new
// "WebAssembly.Function" constructor.
// Otherwise, construct a minimal wasm module importing the JS function and
// re-exporting it.
if (typeof WebAssembly.Function === "function") {
var typeNames = {
'i': 'i32',
'j': 'i64',
'f': 'f32',
'd': 'f64'
};
var type = {
parameters: [],
results: sig[0] == 'v' ? [] : [typeNames[sig[0]]]
};
for (var i = 1; i < sig.length; ++i) {
type.parameters.push(typeNames[sig[i]]);
}
return new WebAssembly.Function(type, func);
}

// The module is static, with the exception of the type section, which is
// generated based on the signature passed in.
var typeSection = [
Expand Down

0 comments on commit 0f848e0

Please sign in to comment.