diff --git a/AST.py b/AST.py index 22eb331d0f4514354fbe41ba53cb3cf393e848b0..0af7ec2d0ed906bbb94fd23a9cd1b1dec566cb48 100644 --- a/AST.py +++ b/AST.py @@ -85,6 +85,13 @@ class ASTNode(): c.codeGen() self.code += c.code + def codeGen(self): + res = "" + for c in self.children: + if c and hasattr(c, 'codeGen'): + res += c.codeGen() + return res + def printNodePretty(self, prefix=0): pp = pprint.PrettyPrinter(indent=prefix) pp.pprint(self.__class__.__name__) diff --git a/ExprPrimaryNodes.py b/ExprPrimaryNodes.py index 4d2c39220f4968f1b35b31b18aa348d273ad4918..1e9e94d4c9a883c371407099141f0925a29931a0 100644 --- a/ExprPrimaryNodes.py +++ b/ExprPrimaryNodes.py @@ -421,6 +421,30 @@ class ExprNode(ASTNode): raise Exception("ERROR: Incompatible types. Left of {} type can't be used with right of {} type on operation {}".format(self.left.myType.name, self.right.myType.name, self.op)) + def codeGen(self): + res = "" + + # Unary: + if not self.left: + return res + + res += self.left.codeGen() # get left output + res += p("push", "eax", None, None) + + res += self.right.codeGen() # get right output + res += p("pop", "ebx", None, None) + + if self.op in ['+', '-', '*', '/', '%']: + # operation -> generated code + ops = { + '+': "add", + '-': "sub" + } + res += p(ops[self.op], "ebx", "eax", " " + ops[self.op] + " left + right") + res += p("mov", "eax", "ebx", " move result to eax") + + return res + # returns True, False, Int or None (for non-constant expr) # children of exprNode is either exprNode or literalNode def getConstant(self): diff --git a/UnitNodes.py b/UnitNodes.py index c015457cf708cb5c1ba913c8b155b400d57db5af..881fff5203328532737acc07bc529c41940581d0 100644 --- a/UnitNodes.py +++ b/UnitNodes.py @@ -1,6 +1,7 @@ from AST import ASTNode, getParseTreeNodes from Environment import Env from TheTypeNode import TypeNode, TypeStruct +from CodeGenUtils import p # LiteralNode # ParamNode @@ -40,6 +41,15 @@ class LiteralNode(ASTNode): node = self.env.getNode(self.name, "type") self.myType = TypeStruct(self.name, node) + def codeGen(self): + res = "" + + # int + if self.name == 'int': + res += p("mov", "eax", self.getConstant(), " set to literal") + + return res + def getConstant(self): if self.name == 'int': return int(self.value)