-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgen_decoder.py
More file actions
252 lines (219 loc) · 7.27 KB
/
Copy pathgen_decoder.py
File metadata and controls
252 lines (219 loc) · 7.27 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import io
import sys
from dataclasses import dataclass
import csv
from pprint import pprint
@dataclass
class Argument:
signed: bool
size: int
name: str
@dataclass
class Instruction:
code: int
mnemonic: str
arguments_size: int
arguments: list[Argument]
def parse_arguments(types, arguments):
types = types.strip()
arguments = arguments.strip()
if not types:
assert not arguments
return 0, []
types = types.split(',')
arguments = arguments.split(',')
assert len(types) == len(arguments), (types, arguments)
total_size = 0
l = list(zip(types, arguments))
args = []
for i, (type, name) in enumerate(l):
signed = None
if type.startswith('v'):
assert i == (len(l) - 1), l
assert name == '_', name
total_size += int(type.removeprefix('v'))
continue
elif type.startswith('s'):
size = int(type.removeprefix('s'))
signed = True
elif type.startswith('u'):
size = int(type.removeprefix('u'))
signed = False
else:
assert False, (type, argument)
assert size in {1, 2, 4}
assert signed is not None
if name in {"byte", "branch", "_const"}:
assert signed == True, name
else:
assert signed == False, name
total_size += size
args.append(Argument(
signed=signed,
size=size,
name=name,
))
return total_size, args
def parse_row(row):
code, _, mnemonic, types, arguments = row
if types.strip() == '-1':
arguments_size = -1;
arguments = arguments.split(',')
else:
arguments_size, arguments = parse_arguments(types, arguments)
yield Instruction(
code=int(code),
mnemonic=mnemonic,
arguments_size=arguments_size,
arguments=arguments
)
def parse_opcode_table():
with open('opcodes.csv', 'r') as f:
reader = csv.reader(f, delimiter=",", quotechar='"')
instructions = [instruction for row in reader for instruction in parse_row(row)]
return instructions
opcode_table = list(sorted(parse_opcode_table(), key=lambda i: i.code))
sign_type_table = {
(True, 4): "_s4",
(True, 2): "_s2",
(True, 1): "_s1",
(False, 4): "_u4",
(False, 2): "_u2",
(False, 1): "_u1",
}
def generate_print_fixed_width_instruction(instruction):
offset = 1
for argument in instruction.arguments:
c_type = "int32_t" if argument.signed else "uint32_t"
conversion = sign_type_table[(argument.signed, argument.size)]
yield f"{c_type} {argument.name} = {conversion}(&code[pc + {offset}]);"
offset += argument.size
argument_format = ", ".join(
f"%{'d' if argument.signed else 'u'}"
for argument in instruction.arguments
)
argument_values = ", ".join(
argument.name
for argument in instruction.arguments
)
if argument_values:
argument_values = ", " + argument_values
mnemonic = instruction.mnemonic.ljust(13)
yield f'printf("%4d: {mnemonic} {argument_format}\\n", pc{argument_values});'
yield f"return pc + {1 + instruction.arguments_size};"
def generate_print_variable_width_instruction(instruction):
n = '' if instruction.mnemonic == "wide" else '\\n'
mnemonic = instruction.mnemonic.ljust(13)
yield f"{instruction.mnemonic.upper()}_ARGS;"
yield f'printf("%4d: {mnemonic} {{{n}", pc);'
yield f"{instruction.mnemonic.upper()}_PRINT_ARGS();"
yield f'printf("}}{n}\\n");'
yield f"return {instruction.mnemonic.upper()}_NEXT_PC;"
def generate_print_decoder():
yield "uint32_t decode_print_instruction(const uint8_t * code, uint32_t pc)"
yield "{"
yield "switch (code[pc]) {"
for instruction in opcode_table:
yield f"case {instruction.code}: // {instruction.mnemonic}"
yield "{"
if instruction.arguments_size == -1:
yield from generate_print_variable_width_instruction(instruction)
else:
yield from generate_print_fixed_width_instruction(instruction)
yield "}"
yield "default:"
yield "{"
yield "assert(false);"
yield "return pc;"
yield "}"
yield "}"
yield "}"
def generate_execute_fixed_width_instruction(instruction):
offset = 1
for argument in instruction.arguments:
c_type = "int32_t" if argument.signed else "uint32_t"
conversion = sign_type_table[(argument.signed, argument.size)]
yield f"{c_type} {argument.name} = {conversion}(&code[pc + {offset}]);"
offset += argument.size
yield f"vm->current_frame->next_pc = pc + {1 + instruction.arguments_size};"
argument_values = ", ".join(
argument.name
for argument in instruction.arguments
)
if argument_values:
argument_values = ", " + argument_values
yield f"op_{instruction.mnemonic}(vm{argument_values});"
def generate_execute_variable_width_instruction(instruction):
yield f"{instruction.mnemonic.upper()}_ARGS;"
argument_values = ", ".join(
argument
for argument in instruction.arguments
)
if instruction.mnemonic != "wide":
yield f"vm->current_frame->next_pc = {instruction.mnemonic.upper()}_NEXT_PC;"
if argument_values:
argument_values = ", " + argument_values
if instruction.mnemonic == "wide":
yield "WIDE_IMPL();"
else:
yield f"op_{instruction.mnemonic}(vm{argument_values});"
def generate_execute_decoder():
yield "void decode_execute_instruction(struct vm * vm, const uint8_t * code, uint32_t pc)"
yield "{"
yield "switch (code[pc]) {"
for instruction in opcode_table:
yield f"case {instruction.code}: // {instruction.mnemonic}"
yield "{"
if instruction.arguments_size == -1:
yield from generate_execute_variable_width_instruction(instruction)
else:
yield from generate_execute_fixed_width_instruction(instruction)
yield "break;"
yield "}"
yield "default:"
yield "{"
yield "assert(false);"
yield "break;"
yield "}"
yield "}"
yield "}"
def should_autonewline(line):
return (
"static_assert" not in line
and "extern" not in line
and (len(line.split()) < 2 or line.split()[1] != '=') # hacky; meh
)
def _render(out, lines):
indent = " "
level = 0
namespace = 0
for l in lines:
if l and (l[0] == "}" or l[0] == ")"):
level -= 2
if level < 0:
assert namespace >= 0
namespace -= 1
level = 0
if len(l) == 0:
out.write("\n")
else:
out.write(indent * level + l + "\n")
if l and (l[-1] == "{" or l[-1] == "("):
if l.startswith("namespace"):
namespace += 1
else:
level += 2
if level == 0 and l and l[-1] == ";":
if should_autonewline(l):
out.write("\n")
return out
def renderer():
out = io.StringIO()
def render(lines):
return _render(out, lines)
return render, out
if __name__ == "__main__":
render, out = renderer()
render(generate_print_decoder())
render(generate_execute_decoder())
sys.stdout.write(out.getvalue())