jweinst1
12/4/2016 - 7:22 PM

ast.py

#abstract syntax tree

#Problem 1, math statements

#write a function that turns a list of scheme tokens into an abstract syntax tree.
#only the operations + - and * are supported

class ASTnode:


    def __init__(self, tokens, type=None):
        self.type = type
        self.children = []
        mode = "fn"
        current_child = []
        for i in range(len(tokens)):
            if mode == "fn":
                if tokens[i] == "+" or tokens[i] == "-" or tokens[i] == "*":
                    self.type = tokens[i]
                    mode = "s"
                else:
                    if tokens[i] == "(" or tokens[i] == ")":
                        self.children.append((tokens[i], "paren"))
                    else:
                        self.children.append((tokens[i], "int"))
            elif mode == "s":
                if tokens[i] == "(":
                    mode = "e"
                elif tokens[i] == ")":
                    mode = "fn"
                else:
                    self.children.append(ASTnode([tokens[i]]))
            elif mode == "e":
                if tokens[i] == ")":
                    self.children.append(ASTnode(current_child))
                else:
                    current_child.append(tokens[i])

    def __repr__(self):
        return "({0}) -> {1}".format(self.type, self.children)

print(ASTnode(["(", "+", "5", "7"]))
print(ASTnode(["(", "+", "5", "(", "-", "7", "1", ")", ")"]))