forked from go-interpreter/wagon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
op.go
87 lines (71 loc) · 2.17 KB
/
op.go
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2017 The go-interpreter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package operators provides all operators used by WebAssembly bytecode,
// together with their parameter and return type(s).
package operators
import (
"fmt"
"github.com/ThinkiumGroup/wagon/wasm"
)
var (
ops [256]Op // an array of Op values mapped by wasm opcodes, used by New().
noReturn = wasm.ValueType(wasm.BlockTypeEmpty)
)
// Op describes a WASM operator.
type Op struct {
Code byte // The single-byte opcode
Name string // The name of the operator
// Whether this operator is polymorphic.
// A polymorphic operator has a variable arity. call, call_indirect, and
// drop are examples of polymorphic operators.
Polymorphic bool
Args []wasm.ValueType // an array of value types used by the operator as arguments, is nil for polymorphic operators
Returns wasm.ValueType // the value returned (pushed) by the operator, is 0 for polymorphic operators
}
func (o Op) IsValid() bool {
return o.Name != ""
}
func newOp(code byte, name string, args []wasm.ValueType, returns wasm.ValueType) byte {
if ops[code].IsValid() {
panic(fmt.Errorf("opcode %#x is already assigned to %s", code, ops[code].Name))
}
op := Op{
Code: code,
Name: name,
Polymorphic: false,
Args: args,
Returns: returns,
}
ops[code] = op
return code
}
func newPolymorphicOp(code byte, name string) byte {
if ops[code].IsValid() {
panic(fmt.Errorf("Opcode %#x is already assigned to %s", code, ops[code].Name))
}
op := Op{
Code: code,
Name: name,
Polymorphic: true,
}
ops[code] = op
return code
}
type InvalidOpcodeError byte
func (e InvalidOpcodeError) Error() string {
return fmt.Sprintf("Invalid opcode: %#x", byte(e))
}
// New returns the Op object for a valid given opcode.
// If code is invalid, an ErrInvalidOpcode is returned.
func New(code byte) (Op, error) {
var op Op
if int(code) >= len(ops) || internalOpcodes[code] {
return op, InvalidOpcodeError(code)
}
op = ops[code]
if !op.IsValid() {
return op, InvalidOpcodeError(code)
}
return op, nil
}