Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Fish Code language interpreter
- Language specification at https://esolangs.org/wiki/Fish_Code
- Use like this:
- code
- !
- input
- """
- import re,sys
- INC,DEC,INPC,OUTC,INP,OUT,PUSH,POP,SWAP,JZ,JNZ,JMP,SET,SUB=0,1,2,3,4,5,6,7,8,9,10,11,12,13
- stacks=[[],[]]
- curstack=0
- reg=0
- def parse(c):
- """Parse a line of code"""
- res=[]
- while c:
- if c[0] in '+-,.:;?!~':
- res.append(('+-,.:;?!~'.index(c[0]),0))
- c=c[1:]
- elif re.match('\\(\\(\\(\\d*?\\)\\)\\)',c):
- matched=re.match('\\(\\(\\(\\d*?\\)\\)\\)',c)
- m=int(c[:matched.end()][3:-3])
- c=c[matched.end():]
- res.append((SUB,m))
- elif re.match('\\(\\(\\d*?\\)\\)',c):
- matched=re.match('\\(\\(\\d*?\\)\\)',c)
- m=int(c[:matched.end()][2:-2])
- c=c[matched.end():]
- res.append((SET,m))
- elif re.match('\\(\\d*?\\)',c):
- matched=re.match('\\(\\d*?\\)',c)
- m=int(c[:matched.end()][1:-1])
- c=c[matched.end():]
- res.append((JZ,m))
- elif re.match('\\[\\d*?\\]',c):
- matched=re.match('\\[\\d*?\\]',c)
- m=int(c[:matched.end()][1:-1])
- c=c[matched.end():]
- res.append((JNZ,m))
- elif re.match('\\{\\d*?\\}', c):
- matched = re.match('\\{\\d*?\\}', c)
- m = int(c[:matched.end()][1:-1])
- c = c[matched.end():]
- res.append((JMP, m))
- else:
- raise SyntaxError('Invalid command')
- return res
- def parse_whole(c):
- """Parse a whole program"""
- x=c.split('\n')
- res=[]
- for i in x:
- if not i:
- continue
- i=i.strip()
- if not re.match('\<.*?\>\<',i):
- raise SyntaxError('Invalid code')
- else:
- res.append(parse(i[1:-2]))
- return res
- def getchar():
- """Read a character"""
- c=sys.stdin.read(1)
- if not c:
- return 0
- return ord(c)&255
- def getint():
- """Read an integer"""
- try:
- x=int(input())
- except:
- return 0
- else:
- return x&255
- def interpret_line(c):
- """Interpret a line of code and return IP"""
- global stacks,curstack,reg
- for op,arg in c:
- if op==INC:
- reg+=1
- reg&=255
- elif op==DEC:
- reg-=1
- reg&=255
- elif op==INPC:
- reg=getchar()
- elif op==OUTC:
- sys.stdout.write(chr(reg))
- elif op==INP:
- reg=getint()
- elif op==OUT:
- print(reg)
- elif op==PUSH:
- stacks[curstack].append(reg)
- elif op==POP:
- reg=stacks[curstack].pop()
- elif op==SWAP:
- curstack=1-curstack
- elif op==JZ:
- if not reg:
- return arg
- elif op==JNZ:
- if reg:
- return arg
- elif op==JMP:
- return arg
- elif op==SET:
- reg=arg
- elif op==SUB:
- reg=(reg-arg)&255
- sys.exit()
- def interpret(c):
- """Interpret a whole program"""
- c=parse_whole(c)
- ip=0
- while 1:
- ip=interpret_line(c[ip])
- code=[]
- while 1:
- x=input()
- if x.strip()=='!':
- break
- code.append(x.strip())
- interpret('\n'.join(code))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement