-
Notifications
You must be signed in to change notification settings - Fork 42
/
imports-function-early-exit.php
71 lines (56 loc) · 1.83 KB
/
imports-function-early-exit.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
declare(strict_types=1);
require_once __DIR__.'/../vendor/autoload.php';
class ExitCode extends Exception
{
public function __construct(int $code)
{
parent::__construct('Exit code', $code);
}
}
function earlyExit()
{
throw new ExitCode(1);
}
// Let's declare the Wasm module.
//
// We are using the text representation of the module here.
$wasmBytes = Wasm\Wat::wasm(<<<'WAT'
(module
(type $run_t (func (param i32 i32) (result i32)))
(type $early_exit_t (func (param) (result)))
(import "env" "early_exit" (func $early_exit (type $early_exit_t)))
(func $run (type $run_t) (param $x i32) (param $y i32) (result i32)
(call $early_exit)
(i32.add
local.get $x
local.get $y))
(export "run" (func $run)))
WAT);
// Create an Engine
$engine = Wasm\Engine::new();
// Create a Store
$store = Wasm\Store::new($engine);
echo 'Compiling module...'.PHP_EOL;
$module = Wasm\Module::new($store, $wasmBytes);
// Create an import object with the expected function.
$funcType = Wasm\Type\FuncType::new(new Wasm\Vec\ValType(), new Wasm\Vec\ValType());
$func = Wasm\Func::new($store, $funcType, 'earlyExit');
$extern = $func->asExtern();
$externs = new Wasm\Vec\Extern([$extern->inner()]);
echo 'Instantiating module...'.PHP_EOL;
$instance = Wasm\Instance::new($store, $module, $externs);
// Extracting export...
$exports = $instance->exports();
$run = (new Wasm\Extern($exports[0]))->asFunc();
$firstArg = Wasm\Val::newI32(1);
$secondArg = Wasm\Val::newI32(7);
$args = new Wasm\Vec\Val([$firstArg->inner(), $secondArg->inner()]);
echo 'Calling `run` function...'.PHP_EOL;
try {
$run($args);
echo '`run` did not error'.PHP_EOL;
exit(1);
} catch (ExitCode $exception) {
echo 'Exited early with: '.$exception->getMessage().' '.$exception->getCode().PHP_EOL;
}