Last active
August 25, 2018 08:01
-
-
Save JustinSDK/4b0f151ff434b09bb70a14f20246f316 to your computer and use it in GitHub Desktop.
Byte Code ABC - 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Num: | |
def __init__(self, value): | |
self.value = value | |
def bc_instructn(self, bytecodes): | |
bytecodes.append(f'push {self.value}') | |
return bytecodes | |
class Add: | |
def __init__(self, left, right): | |
self.left = left | |
self.right = right | |
def bc_instructn(self, bytecodes): | |
self.left.bc_instructn(bytecodes) | |
self.right.bc_instructn(bytecodes) | |
bytecodes.append('add _') | |
return bytecodes | |
class Mul: | |
def __init__(self, left, right): | |
self.left = left | |
self.right = right | |
def bc_instructn(self, bytecodes): | |
self.left.bc_instructn(bytecodes) | |
self.right.bc_instructn(bytecodes) | |
bytecodes.append('mul _') | |
return bytecodes | |
# Byte Code Instructions | |
def push(stack, value): | |
stack.append(int(value)) | |
def add(stack, _): | |
r = stack.pop() | |
l = stack.pop() | |
stack.append(l + r) | |
def mul(stack, _): | |
r = stack.pop() | |
l = stack.pop() | |
stack.append(l * r) | |
instructions = { | |
'push': push, | |
'add' : add, | |
'mul' : mul | |
} | |
def dis(bytecodes): | |
for i, code in enumerate(bytecodes): | |
print(f'{i} {code}') | |
def vm(bytecodes): | |
stack = [] | |
for code in bytecodes: | |
instruction, value = code.split(' ') | |
instructions[instruction](stack, value) | |
return stack | |
# 1 + 2 | |
print('\n# 1 + 2') | |
bytecodes = Add(Num(1), Num(2)).bc_instructn([]) | |
dis(bytecodes) | |
print(vm(bytecodes)) | |
# 1 + 2 + 3 | |
print('\n# 1 + 2 + 3') | |
bytecodes = Add(Add(Num(1), Num(2)), Num(3)).bc_instructn([]) | |
dis(bytecodes) | |
print(vm(bytecodes)) | |
# 5 + 2 * 3 | |
print('\n# 5 + 2 * 3') | |
bytecodes = Add(Num(5), Mul(Num(2), Num(3))).bc_instructn([]) | |
dis(bytecodes) | |
print(vm(bytecodes)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment