go-interpreter / wagon

wagon, a WebAssembly-based Go interpreter, for Go.
BSD 3-Clause "New" or "Revised" License
903 stars 148 forks source link

wasm-run: execute expressions from argv #185

Open ktye opened 4 years ago

ktye commented 4 years ago

Currently wasm-run executes every exported function. I modified it to execute expressions given as command line arguments in post fix order. e.g.: wasm-run file.wasm 1 2 neg 3 add (where neg takes one and add takes 2 arguments).

var stack []uint64
    for i := range args {
        if u, e := strconv.ParseUint(args[i], 10, 64); e == nil {
            stack = append(stack, u)
        } else if args[i] == "dump" {
            dump(vm.Memory(), stack[len(stack)-2], stack[len(stack)-1])
            stack = stack[:len(stack)-2]
        } else {
            x, ok := m.Export.Entries[args[i]]
            if !ok {
                panic("unknown func: " + args[i])
            }
            fidx := m.Function.Types[x.Index]
            ftyp := m.Types.Entries[fidx]
            n := len(ftyp.ParamTypes)
            pop := make([]uint64, n)
            copy(pop, stack[len(stack)-n:])
            stack = stack[:len(stack)-n]
            res, e := vm.ExecCode(int64(x.Index), pop...)
            if e != nil {
                panic(e)
            }
            stack = append(stack, u64(res))
            fmt.Printf("%s %v: %v(%x)\n", args[i], pop, res, res)
        }
    }

Maybe you find it useful. (i use it in my wasm compiler for a custom language: https://github.com/ktye/i/tree/master/_/w)