Skip to content

Commit

Permalink
feat(std/wasi): add support for initializing reactors (#8603)
Browse files Browse the repository at this point in the history
This adds another entry point to Context called initialize for 
spinning up style modules.

Reactors are modules that don't have a main function and 
basically run forever in the background.
  • Loading branch information
caspervonb authored Dec 3, 2020
1 parent 93d9f51 commit de036e1
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
33 changes: 33 additions & 0 deletions std/wasi/snapshot_preview1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1588,4 +1588,37 @@ export default class Context {

_start();
}

/**
* Attempt to initialize instance as a reactor by invoking its _initialize() export.
*
* If instance contains a _start() export, then an exception is thrown.
*
* The instance must also have a WebAssembly.Memory export named "memory"
* which will be used as the address space, if it does not an error will be
* thrown.
*/
initialize(instance: WebAssembly.Instance) {
const { _start, _initialize, memory } = instance.exports;

if (!(memory instanceof WebAssembly.Memory)) {
throw new TypeError("WebAsembly.instance must provide a memory export");
}

this.memory = memory;

if (typeof _start == "function") {
throw new TypeError(
"WebAssembly.Instance export _start must not be a function",
);
}

if (typeof _initialize != "function") {
throw new TypeError(
"WebAsembly.instance export _initialize must be a function",
);
}

_initialize();
}
}
42 changes: 42 additions & 0 deletions std/wasi/snapshot_preview1_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,45 @@ Deno.test("context_start", function () {
"export _start must be a function",
);
});

Deno.test("context_initialize", function () {
assertThrows(
() => {
const context = new Context({});
context.initialize({
exports: {
_initialize() {},
},
});
},
TypeError,
"must provide a memory export",
);

assertThrows(
() => {
const context = new Context({});
context.initialize({
exports: {
_start() {},
memory: new WebAssembly.Memory({ initial: 1 }),
},
});
},
TypeError,
"export _start must not be a function",
);

assertThrows(
() => {
const context = new Context({});
context.initialize({
exports: {
memory: new WebAssembly.Memory({ initial: 1 }),
},
});
},
TypeError,
"export _initialize must be a function",
);
});

0 comments on commit de036e1

Please sign in to comment.