Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # An interpreter for MP, a.k.a. Minimalistic Pig
- # An MP source code file is .mp0
- import copy
- class Instr:
- up = ["u","^"]
- down = ["d","v"]
- swap = ["s","/"] # swap the top two elements
- switch = ["S",";"] # swap working stacks
- one = ["l","1"]
- minus = ["m","-"]
- getnum = ["i","["]
- getchar = ["I","{"]
- printnum = ["o","]"]
- printchar = ["O","}"]
- flag = ["f","*"]
- goto = ["g",">"]
- reverse = ["r","%"]
- with open("program.mp0") as f:
- prog = f.read()
- alt = []
- stack = []
- def pop():
- global stack, ip
- if len(stack) == 0:
- print("There was an error on char {0}!".format(ip))
- top = stack[-1]
- del stack[-1]
- return top
- def push(x):
- global stack
- stack.append(x)
- ip = 0
- length = len(prog)
- register = 0
- while ip < length:
- c = prog[ip]
- if c in Instr.up:
- register = pop()
- elif c in Instr.down:
- push(register)
- elif c in Instr.swap:
- a = pop()
- b = pop()
- push(a)
- push(b)
- elif c in Instr.switch:
- temp = copy.copy(stack)
- stack = copy.copy(alt)
- alt = copy.copy(temp)
- del temp
- elif c in Instr.one:
- push(1)
- elif c in Instr.minus:
- a = pop()
- b = pop()
- push(b-a)
- elif c in Instr.getnum:
- push(int(input()))
- elif c in Instr.getchar:
- raise RuntimeError("error on {0} - { is not implemented".format(ip))
- elif c in Instr.printnum:
- print(pop(), end="")
- elif c in Instr.printchar:
- print(chr(pop()), end="")
- elif c in Instr.reverse:
- stack.reverse()
- elif c in Instr.goto:
- j = pop()
- if j < 0:
- for _ in range(-j):
- ip -= 1
- while prog[ip] not in Instr.flag:
- ip -= 1
- elif j > 0:
- for _ in range(j):
- ip += 1
- while prog[ip] not in Instr.flag:
- ip += 1
- ip += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement