Advertisement
Guest User

Minipig Interpreter

a guest
Sep 20th, 2016
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. # An interpreter for MP, a.k.a. Minimalistic Pig
  2. # An MP source code file is .mp0
  3.  
  4. import copy
  5.  
  6. class Instr:
  7.     up = ["u","^"]
  8.     down = ["d","v"]
  9.     swap = ["s","/"] # swap the top two elements
  10.     switch = ["S",";"] # swap working stacks
  11.     one = ["l","1"]
  12.     minus = ["m","-"]
  13.     getnum = ["i","["]
  14.     getchar = ["I","{"]
  15.     printnum = ["o","]"]
  16.     printchar = ["O","}"]
  17.     flag = ["f","*"]
  18.     goto = ["g",">"]
  19.     reverse = ["r","%"]
  20.  
  21. with open("program.mp0") as f:
  22.     prog = f.read()
  23.  
  24. alt = []
  25. stack = []
  26.  
  27. def pop():
  28.     global stack, ip
  29.    
  30.     if len(stack) == 0:
  31.         print("There was an error on char {0}!".format(ip))
  32.     top = stack[-1]
  33.     del stack[-1]
  34.     return top
  35.    
  36. def push(x):
  37.     global stack
  38.     stack.append(x)
  39.  
  40. ip = 0
  41.  
  42. length = len(prog)
  43.  
  44. register = 0
  45.  
  46. while ip < length:
  47.    
  48.     c = prog[ip]
  49.    
  50.     if c in Instr.up:
  51.         register = pop()
  52.        
  53.     elif c in Instr.down:
  54.         push(register)
  55.        
  56.     elif c in Instr.swap:
  57.         a = pop()
  58.         b = pop()
  59.         push(a)
  60.         push(b)
  61.        
  62.     elif c in Instr.switch:
  63.         temp = copy.copy(stack)
  64.         stack = copy.copy(alt)
  65.         alt = copy.copy(temp)
  66.         del temp
  67.            
  68.     elif c in Instr.one:
  69.         push(1)
  70.        
  71.     elif c in Instr.minus:
  72.         a = pop()
  73.         b = pop()
  74.         push(b-a)
  75.        
  76.     elif c in Instr.getnum:
  77.         push(int(input()))
  78.    
  79.     elif c in Instr.getchar:
  80.         raise RuntimeError("error on {0} - { is not implemented".format(ip))
  81.        
  82.     elif c in Instr.printnum:
  83.         print(pop(), end="")
  84.        
  85.     elif c in Instr.printchar:
  86.         print(chr(pop()), end="")
  87.        
  88.     elif c in Instr.reverse:
  89.         stack.reverse()
  90.        
  91.     elif c in Instr.goto:
  92.         j = pop()
  93.         if j < 0:
  94.             for _ in range(-j):
  95.                 ip -= 1
  96.                 while prog[ip] not in Instr.flag:
  97.                     ip -= 1
  98.         elif j > 0:
  99.             for _ in range(j):
  100.                 ip += 1
  101.                 while prog[ip] not in Instr.flag:
  102.                     ip += 1
  103.                    
  104.     ip += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement