Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active August 25, 2018 08:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinSDK/4b0f151ff434b09bb70a14f20246f316 to your computer and use it in GitHub Desktop.
Save JustinSDK/4b0f151ff434b09bb70a14f20246f316 to your computer and use it in GitHub Desktop.
Byte Code ABC - 2
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