Guest User

Untitled

a guest
Jan 23rd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. def compile(program):
  2. memo = []
  3. for ast in program:
  4. memo += compile_one(ast)
  5. return memo
  6.  
  7. def compile_one(ast):
  8. inst = ast[0]
  9. if inst == 'assign':
  10. lhs = ast[1]
  11. rhs = ast[2]
  12. x = compile_one(rhs)
  13. return x + [('set', lhs)]
  14. elif inst == 'refer':
  15. return [('get', ast[1])]
  16. elif inst == 'value':
  17. return [('put', ast[1])]
  18. elif inst == 'plus':
  19. arg1 = ast[1]
  20. arg2 = ast[2]
  21. return compile_one(arg1) + compile_one(arg2) + [('plus',)]
  22. elif inst == 'print':
  23. name = ast[1]
  24. return compile_one(name) + [('print',)]
  25. elif inst == 'variables': #
  26. return [('variables',)]
  27. else:
  28. return 'omg: ' + inst
  29.  
  30.  
  31. def execute(bytecode):
  32. stack = []
  33. variables = {}
  34. for nme in bytecode:
  35. inst = nme[0]
  36. if inst == 'put':
  37. stack.append(nme[1])
  38. elif inst == 'set':
  39. name = nme[1]
  40. variables[name] = stack.pop()
  41. elif inst == 'get':
  42. name = nme[1]
  43. stack.append(variables[name])
  44. elif inst == 'plus':
  45. a = stack.pop()
  46. b = stack.pop()
  47. stack.append(a + b)
  48. elif inst == 'print':
  49. a = stack.pop()
  50. print a
  51. elif inst == 'variables':
  52. print variables
  53.  
  54. # a = 1
  55. # b = a + 2
  56. # print b
  57. program = [
  58. ('assign', 'a', ('value', 1)),
  59. ('assign', 'b', ('plus', ('refer', 'a'), ('value', 2))),
  60. ('print', ('refer', 'b')),
  61. ('variables',)]
  62. # put 1
  63. # set a
  64. # get a
  65. # put 2
  66. # plus
  67. # set b
  68. # get b
  69. # print
  70.  
  71. bytecode = compile(program)
  72. execute(bytecode)
Add Comment
Please, Sign In to add comment