about summary refs log tree commit diff
path: root/pkg/lang/vm/text/op.go
blob: a8f3663c579c6bdabf03d30c0187eed6d933f08e (plain)
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
package text

import "jinx/pkg/lang/vm/code"

var (
	opToString = map[code.Op]string{
		code.OpNop:          "nop",
		code.OpHalt:         "halt",
		code.OpPushInt:      "push_int",
		code.OpPushFloat:    "push_float",
		code.OpPushString:   "push_string",
		code.OpPushTrue:     "push_true",
		code.OpPushFalse:    "push_false",
		code.OpPushNull:     "push_null",
		code.OpPushArray:    "push_array",
		code.OpPushFunction: "push_function",
		code.OpPushObject:   "push_object",
		code.OpGetGlobal:    "get_global",
		code.OpGetLocal:     "get_local",
		code.OpGetMember:    "get_member",
		code.OpGetArg:       "get_arg",
		code.OpGetEnv:       "get_env",
		code.OpAdd:          "add",
		code.OpSub:          "sub",
		code.OpIndex:        "index",
		code.OpCall:         "call",
		code.OpJmp:          "jmp",
		code.OpJez:          "jez",
		code.OpRet:          "ret",
	}
	stringToOp = reverseMap(opToString)
)

func OpToString(op code.Op) string {
	str, ok := opToString[op]
	if !ok {
		return "unknown"
	}
	return str
}

func StringToOp(str string) (code.Op, error) {
	op, ok := stringToOp[str]
	if !ok {
		return 0, ErrUnknownOp{Op: str}
	}
	return op, nil
}

func reverseMap[K comparable, V comparable](m map[K]V) map[V]K {
	r := make(map[V]K)
	for k, v := range m {
		r[v] = k
	}
	return r
}