Skip to content

Instantly share code, notes, and snippets.

@vndmtrx
Forked from vgel/tinystackr3.py
Created July 19, 2012 18:46
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 vndmtrx/3145935 to your computer and use it in GitHub Desktop.
Save vndmtrx/3145935 to your computer and use it in GitHub Desktop.
Tiny stack-based language in python.
stack = []
compileStacks = []
words = {}
builtins = {}
lambdaType = type(lambda x: x) #cannot compare against the function type directly for some reason
def prn(o):
print(o)
def clr(l):
del l[:]
def is_num(x):
try:
float(x)
return True
except:
return False
def can_hash(x):
try:
x in {}
return True
except:
return False
def is_str(x):
return type(x) is str and len(x) > 2 and x.startswith("\"") and x.endswith("\"")
def unquote(x):
return x[1:len(x) - 1]
def wreduce(word):
if word == ":":
compileStacks.append([])
return []
elif word == ";":
compileStacks[len(compileStacks) - 2].append(compileStacks.pop())
return []
elif type(word) is str and word.startswith("$"):
words[word[1:]] = compileStacks[len(compileStacks) - 1].pop()
return []
elif is_num(word):
return [float(word)]
elif is_str(word):
return [word]
elif can_hash(word):
if word in words:
return words[word]
elif word in builtins:
return [builtins[word]]
print("wred unknown word " + str(word))
def lcompile(line):
for word in line.split(" "):
compileStacks[len(compileStacks) - 1].extend(wreduce(word))
def run(l):
for w in l:
if isinstance(w, float) or isinstance(w, list):
stack.append(w)
elif is_str(w):
stack.append(unquote(w))
elif type(w) == lambdaType:
w(stack)
else:
print("unknown word " + str(w))
builtins["."] = lambda stack: prn(stack[len(stack) - 1])
builtins[".s"] = lambda stack: prn(str(stack))
builtins["pop"] = lambda stack: stack.pop()
builtins["cls"] = lambda stack: clr(stack)
builtins["dup"] = lambda stack: stack.append(stack[len(stack) - 1])
builtins["swap"] = lambda stack: stack.append(stack.pop(len(stack) - 2))
builtins["+"] = lambda stack: stack.append(stack.pop() + stack.pop())
builtins["-"] = lambda stack: stack.append(-(stack.pop() - stack.pop()))
builtins["*"] = lambda stack: stack.append(stack.pop() * stack.pop())
builtins["/"] = lambda stack: stack.append(1/(stack.pop() / stack.pop()))
builtins["call"] = lambda stack: run(stack.pop())
builtins["bra"] = lambda stack: (run(stack.pop()) if stack.pop() else stack.pop())
while True:
if len(compileStacks) == 0:
compileStacks.append([])
lcompile(raw_input())
if len(compileStacks) == 1:
run(compileStacks[0])
clr(compileStacks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment