Last active
August 29, 2015 14:06
-
-
Save csaftoiu/20fe5fdcb897bb50193f to your computer and use it in GitHub Desktop.
Interpreter for Clem, v1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys,os,copy as C | |
L=len | |
S=[] | |
n=[S] | |
Q=lambda:S and S.pop()or 0 | |
def P(o): | |
if o:n[0].append(o) | |
def X():x=Q();P(x);P(C.deepcopy(x)) | |
def W():S[-2::]=S[-1:-3:-1] | |
def R():a,b,c=Q(),Q(),Q();P(a);P(c);P(b) | |
def A(d): | |
a=Q() | |
if a and a[0]:a=[1,a[1]+d,lambda:P(a)] | |
P(a) | |
def V(): | |
a=Q();P(a) | |
if a and a[0]-1and L(a[2])>1:r=a[2].pop(0);P(r) | |
def T(): | |
b,a=Q(),Q() | |
if a!=b:P([0,0,(a[2],[a])[a[0]]+(b[2],[b])[b[0]]]) | |
else:P(a);P(b) | |
def r():a=os.read(0,1);F(ord(a)if a else-1) | |
def q(f): | |
a=Q() | |
if a and a[0]:os.write(1,(chr(a[1]%256),str(a[1]))[f]) | |
def e(f,x=0):f[2]()if f[0]+f[1]else([e(z)for z in f[2]]if x else P(f)) | |
def w(): | |
a=Q() | |
while a and S and S[-1][0]and S[-1][1]:e(a,1) | |
def Y():n[:0]=[[]] | |
def Z(): | |
x=n.pop(0) | |
if x:n[0]+=([[0,0,x]],x)[L(x)+L(n)==2] | |
D={'%':Q,'#':X,'$':W,'@':R,'+':lambda:A(1),'-':lambda:A(-1),'/':V,'.':T,'<':r,'>':lambda:q(0),'c':lambda:q(1),'w':w,'(':Y,')':Z} | |
def g(c):D[c]()if L(n)<2or c in'()'else P([0,1,D[c]]) | |
N=[''] | |
def F(x):a=[1,x,lambda:P(a)];a[2]() | |
def E(): | |
if'-'==N[0]:g('-') | |
elif N[0]:F(int(N[0])) | |
N[0]='' | |
s=j="" | |
for c in open(sys.argv[1]).read()+' ': | |
if j:j=c!="\n" | |
elif'"'==c:E();s and map(F,map(ord,s[:0:-1]));s=(c,'')[L(s)>0] | |
elif s:s+=c | |
elif';'==c:E();j=1 | |
else: | |
if'-'==c:E() | |
if c in'-0123456789':N[0]+=c | |
else:E();c in D and g(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment