Skip to content

Instantly share code, notes, and snippets.

@csaftoiu
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csaftoiu/20fe5fdcb897bb50193f to your computer and use it in GitHub Desktop.
Save csaftoiu/20fe5fdcb897bb50193f to your computer and use it in GitHub Desktop.
Interpreter for Clem, v1
import sys,os,copy as C
S=[];T=[]
n=[S]
def nest():n[:0]=[[]]
def endnest():
x=n.pop(0)
if len(x) == 1 and len(n)==1:n[0] += x
else:n[0] += [[0,0,x]]
def swap():S[-2::]=S[-1:-3:-1]
pop=lambda:S and S.pop()
def push(o):
if o!=S:n[0].append(o)
def dup():x=pop();push(x);push(C.deepcopy(x))
def rot():a,b,c=pop(),pop(),pop();push(a);push(c);push(b)
def add(d):
if S:
a=pop()
if a[0]:a=[1,a[1]+d,lambda:push(a)]
push(a)
def div():
a=pop();push(a)
if a!=S and a[0]-1 and len(a[2])>1:
r=a[2].pop(0);push(r)
def ccat():
b,a=pop(),pop()
if a!=S!=b:push([0,0,(a[2],[a])[a[0]]+(b[2],[b])[b[0]]])
else:push(a);push(b)
def write(f):
a=pop()
if a!=S and a[0]:os.write(1,(chr(a[1]%256),str(a[1]))[f])
def read():a=os.read(0,1);N[0]=ord(a)if a else-1;endnum()
def xec(f,X=0):f[2]()if f[0]+f[1]else([xec(z)for z in f[2]]if X else push(f))
def loop():
a=pop()
while a and S and S[-1][0]and S[-1][1]:xec(a,1)
D={'%':pop,'#':dup,
'$':swap,
'@':rot,
'+':lambda:add(1),'-':lambda:add(-1),
'/':div,'.':ccat,
'<':read,'>':lambda:write(0),'c':lambda:write(1),
'w':loop,'(':nest,')':endnest,
'X':lambda:xec(pop(),1)}
def proc(c):D[c]()if len(n)<2or c in'()'else push([0,1,D[c]])
N=['']
def procdigit(d):N[0]+=d
def endnum():
if'-'==N[0]:proc('-')
elif N[0]:a=[1,int(N[0]),lambda:push(a)];a[2]()
N[0]=''
I=open(sys.argv[1]).read()+' '
instr=com=""
for c in I:
if com:com=c!="\n";continue
if'"'==c:
endnum()
if instr:
for ch in instr[:0:-1]:N[0]=ord(ch);endnum()
instr=''
else:instr=c;continue
if instr:instr+=c;continue
if';'==c:endnum();com=1;continue
if'-'==c:endnum()
procdigit(c)if c in'-0123456789'else(endnum(),c in D and proc(c))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment