Skip to content

Commit

Permalink
Fix instantiation with a Module
Browse files Browse the repository at this point in the history
This commit fixes the `init` function when passed a
`WebAssembly.Module`. Upon closer reading of the [spec] we see there's
two possible return values from `WebAssembly.instantiate`. If passed a
`Module`, it will return only the `Instance`. If passed a buffer source,
though, it'll return an object with the module/instance.

The fix here is to check the result value is an `Instance`, and if so
assume the input must have been a module so it's paired up in the
output.

Closes #1418

[spec]: http://webassembly.github.io/spec/js-api/index.html#webassembly-namespace
  • Loading branch information
alexcrichton committed Apr 2, 2019
1 parent fa674df commit e3473f5
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions crates/cli-support/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -903,12 +903,12 @@ impl<'a> Context<'a> {
let ts = Self::ts_for_init_fn(mem.import.is_some());
let js = format!(
"\
function init(module_or_path{init_memory_arg}) {{
function init(module{init_memory_arg}) {{
let result;
const imports = {{ './{module}': __exports }};
if (module_or_path instanceof URL || typeof module_or_path === 'string' || module_or_path instanceof Request) {{
if (module instanceof URL || typeof module === 'string' || module instanceof Request) {{
{init_memory2}
const response = fetch(module_or_path);
const response = fetch(module);
if (typeof WebAssembly.instantiateStreaming === 'function') {{
result = WebAssembly.instantiateStreaming(response, imports)
.catch(e => {{
Expand All @@ -928,9 +928,13 @@ impl<'a> Context<'a> {
}}
}} else {{
{init_memory1}
result = WebAssembly.instantiate(module_or_path, imports)
.then(instance => {{
return {{ instance, module: module_or_path }};
result = WebAssembly.instantiate(module, imports)
.then(result => {{
if (result instanceof WebAssembly.Instance) {{
return {{ instance: result, module }};
}} else {{
return result;
}}
}});
}}
return result.then(({{instance, module}}) => {{
Expand Down

0 comments on commit e3473f5

Please sign in to comment.