about summary refs log tree commit diff
path: root/pkg/lang/vm/text/op.go
blob: 2d6eb7e19393f3f9d840d80033811360e72bf997 (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
57
58
59
60
61
62
63
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.OpDrop:         "drop",
		code.OpGetGlobal:    "get_global",
		code.OpGetLocal:     "get_local",
		code.OpGetMember:    "get_member",
		code.OpGetEnv:       "get_env",
		code.OpSetEnv:       "set_env",
		code.OpAddToEnv:     "add_to_env",
		code.OpAdd:          "add",
		code.OpSub:          "sub",
		code.OpIndex:        "index",
		code.OpLte:          "lte",
		code.OpCall:         "call",
		code.OpJmp:          "jmp",
		code.OpJt:           "jt",
		code.OpJf:           "jf",
		code.OpRet:          "ret",

		code.OpTempArrPush: "temp_arr_push",
		code.OpTempArrLen:  "temp_arr_len",
	}
	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
}