Created
May 4, 2016 18:40
-
-
Save seantalts/15c8a64f8ed339216d7e3f8d72ca38a1 to your computer and use it in GitHub Desktop.
small terrible lisp ast parser
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 re | |
def lex(s): | |
return re.findall("(\(|\)|[\w\*\+\-]+)", s) | |
def get_ast(tokens): | |
ast = [] | |
while tokens: | |
t = tokens.pop(0) | |
if t == '(': | |
while t != ')' and tokens: | |
ast.append(get_ast(tokens)) | |
elif t == ')': | |
break | |
else: | |
if t.isdigit(): | |
ast.append(float(t)) | |
else: | |
ast.append(t) | |
if not ast: | |
raise SyntaxError("idk dude") | |
return ast | |
print get_ast(lex("(+ (* 2 4) 3)")) | |
# => [['+', ['*', 2.0, 4.0], [3.0]]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment