-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
38 lines (32 loc) · 1013 Bytes
/
run.py
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
#!/usr/bin/python3
import argparse
import code
def run(bytecode):
stack = list()
it = iter(bytecode)
for byte in it:
if byte == code.CMD_PUSH:
byte = next(it)
stack.append(byte)
else:
op = {
code.CMD_ADD: lambda a, b: a + b,
code.CMD_SUB: lambda a, b: a - b,
code.CMD_MUL: lambda a, b: a * b,
code.CMD_DIV: lambda a, b: a / b,
code.CMD_POW: lambda a, b: a ** b,
}[byte]
b = stack.pop()
a = stack.pop()
res = int(op(a, b)) & 0xFF
stack.append(res)
return stack.pop()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Exec bytecode.')
parser.add_argument('input', help='Input bytecode file')
args = parser.parse_args()
with open(args.input, 'rb') as input:
bytecode = bytes(input.read())
result = run(bytecode)
print(result)