This reverts `Runtime.NewModule` back to `InstantiateModule` as it calls
more attention to the registration aspect of it, and also makes a chain
of `NewXX` more clear. This is particularly helpful as this change
introduces `ModuleBuilder` which is created by `NewModuleBuilder`.
`ModuleBuilder` is a way to define a WebAssembly 1.0 (20191205) in Go.
The first iteration allows setting the module name and exported
functions. The next PR will add globals.
Ex. Below defines and instantiates a module named "env" with one function:
```go
hello := func() {
fmt.Fprintln(stdout, "hello!")
}
_, err := r.NewModuleBuilder("env").ExportFunction("hello", hello).InstantiateModule()
```
If the same module may be instantiated multiple times, it is more efficient to separate steps. Ex.
```go
env, err := r.NewModuleBuilder("env").ExportFunction("get_random_string", getRandomString).Build()
_, err := r.InstantiateModule(env.WithName("env.1"))
_, err := r.InstantiateModule(env.WithName("env.2"))
```
Note: Builder methods do not return errors, to allow chaining. Any validation errors are deferred until Build.
Note: Insertion order is not retained. Anything defined by this builder is sorted lexicographically on Build.
Signed-off-by: Adrian Cole <adrian@tetrate.io>
39 lines
1.1 KiB
Go
39 lines
1.1 KiB
Go
package examples
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/tetratelabs/wazero"
|
|
)
|
|
|
|
// Test_AddInt shows how you can define a function in text format and have it compiled inline.
|
|
// See https://github.com/summerwind/the-art-of-webassembly-go/blob/main/chapter1/addint/addint.wat
|
|
func Test_AddInt(t *testing.T) {
|
|
module, err := wazero.NewRuntime().InstantiateModuleFromSource([]byte(`(module $test
|
|
(func $addInt ;; TODO: function module (export "AddInt")
|
|
(param $value_1 i32) (param $value_2 i32)
|
|
(result i32)
|
|
local.get 0 ;; TODO: instruction variables $value_1
|
|
local.get 1 ;; TODO: instruction variables $value_2
|
|
i32.add
|
|
)
|
|
(export "AddInt" (func $addInt))
|
|
)`))
|
|
require.NoError(t, err)
|
|
|
|
addInt := module.ExportedFunction("AddInt")
|
|
|
|
for _, c := range []struct {
|
|
value1, value2, expected uint64 // i32i32_i32 sig, but wasm.ExportedFunction params and results are uint64
|
|
}{
|
|
{value1: 1, value2: 2, expected: 3},
|
|
{value1: 5, value2: 5, expected: 10},
|
|
} {
|
|
results, err := addInt.Call(nil, c.value1, c.value2)
|
|
require.NoError(t, err)
|
|
require.Equal(t, c.expected, results[0])
|
|
}
|
|
}
|