Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def compile(program):
- memo = []
- for ast in program:
- memo += compile_one(ast)
- return memo
- def compile_one(ast):
- inst = ast[0]
- if inst == 'assign':
- lhs = ast[1]
- rhs = ast[2]
- x = compile_one(rhs)
- return x + [('set', lhs)]
- elif inst == 'refer':
- return [('get', ast[1])]
- elif inst == 'value':
- return [('put', ast[1])]
- elif inst == 'plus':
- arg1 = ast[1]
- arg2 = ast[2]
- return compile_one(arg1) + compile_one(arg2) + [('plus',)]
- elif inst == 'print':
- name = ast[1]
- return compile_one(name) + [('print',)]
- elif inst == 'variables': #
- return [('variables',)]
- else:
- return 'omg: ' + inst
- def execute(bytecode):
- stack = []
- variables = {}
- for nme in bytecode:
- inst = nme[0]
- if inst == 'put':
- stack.append(nme[1])
- elif inst == 'set':
- name = nme[1]
- variables[name] = stack.pop()
- elif inst == 'get':
- name = nme[1]
- stack.append(variables[name])
- elif inst == 'plus':
- a = stack.pop()
- b = stack.pop()
- stack.append(a + b)
- elif inst == 'print':
- a = stack.pop()
- print a
- elif inst == 'variables':
- print variables
- # a = 1
- # b = a + 2
- # print b
- program = [
- ('assign', 'a', ('value', 1)),
- ('assign', 'b', ('plus', ('refer', 'a'), ('value', 2))),
- ('print', ('refer', 'b')),
- ('variables',)]
- # put 1
- # set a
- # get a
- # put 2
- # plus
- # set b
- # get b
- # print
- bytecode = compile(program)
- execute(bytecode)
Add Comment
Please, Sign In to add comment