Created
July 8, 2012 23:59
-
-
Save vgel/3073491 to your computer and use it in GitHub Desktop.
Tiny stack-based language in python.
This file contains hidden or 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
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