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>
43 lines
1.1 KiB
Go
43 lines
1.1 KiB
Go
package wazero
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/tetratelabs/wazero/wasm"
|
|
)
|
|
|
|
func TestStartWASICommand_UsesStoreContext(t *testing.T) {
|
|
type key string
|
|
config := NewRuntimeConfig().WithContext(context.WithValue(context.Background(), key("wa"), "zero"))
|
|
r := NewRuntimeWithConfig(config)
|
|
|
|
// Define a function that will be re-exported as the WASI function: _start
|
|
var calledStart bool
|
|
start := func(ctx wasm.Module) {
|
|
calledStart = true
|
|
require.Equal(t, config.ctx, ctx.Context())
|
|
}
|
|
|
|
_, err := r.NewModuleBuilder("").ExportFunction("start", start).Instantiate()
|
|
require.NoError(t, err)
|
|
|
|
_, err = r.InstantiateModule(WASISnapshotPreview1())
|
|
require.NoError(t, err)
|
|
|
|
decoded, err := r.DecodeModule([]byte(`(module $wasi_test.go
|
|
(import "" "start" (func $start))
|
|
(memory 1)
|
|
(export "_start" (func $start))
|
|
(export "memory" (memory 0))
|
|
)`))
|
|
require.NoError(t, err)
|
|
|
|
// Start the module as a WASI command. This will fail if the context wasn't as intended.
|
|
_, err = StartWASICommand(r, decoded)
|
|
require.NoError(t, err)
|
|
require.True(t, calledStart)
|
|
}
|