Skip to content

Instantly share code, notes, and snippets.

@ostcar
Created June 18, 2023 15:38
Show Gist options
  • Save ostcar/17c7cc0257734128a4b29c060d09887f to your computer and use it in GitHub Desktop.
Save ostcar/17c7cc0257734128a4b29c060d09887f to your computer and use it in GitHub Desktop.
Run roc with go
package main
import (
"context"
_ "embed"
"fmt"
"log"
"os"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
)
//go:embed rocLovesWebAssembly.wasm
var wasm []byte
func main() {
if err := run(); err != nil {
log.Println(err)
os.Exit(1)
}
}
func run() error {
ctx := context.Background()
runtime := wazero.NewRuntime(ctx)
defer runtime.Close(ctx)
wasi_snapshot_preview1.MustInstantiate(ctx, runtime)
// Instantiate a Go-defined module named "env" that exports a function to
// log to the console.
_, err := runtime.NewHostModuleBuilder("env").
NewFunctionBuilder().
WithFunc(logString).
Export("js_display_roc_string").
NewFunctionBuilder().
WithFunc(rocPanic).
Export("roc_panic").
Instantiate(ctx)
if err != nil {
return fmt.Errorf("create host module: %w", err)
}
// Instantiate a WebAssembly module that imports the "log" function defined
// in "env".
if _, err = runtime.Instantiate(ctx, wasm); err != nil {
return fmt.Errorf("instantiate: %w", err)
}
return nil
}
func logString(_ context.Context, m api.Module, offset, byteCount uint32) {
buf, ok := m.Memory().Read(offset, byteCount)
if !ok {
fmt.Printf("Memory.Read(%d, %d) out of range", offset, byteCount)
os.Exit(2)
}
fmt.Print(string(buf))
}
func rocPanic(_ context.Context, m api.Module, offset, byteCount uint32) {
panic("TODO")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment