From a212c671cfd42045a54de99aa23c6364eb7906b8 Mon Sep 17 00:00:00 2001 From: Nicholas Robinson <nwrobins@edu.uwaterloo.ca> Date: Wed, 1 Apr 2020 23:51:30 -0400 Subject: [PATCH] ExprNode LiteralNode codeGen - adding the simplest form of their functions - made it work --- AST.py | 7 +++++++ ExprPrimaryNodes.py | 24 ++++++++++++++++++++++++ UnitNodes.py | 10 ++++++++++ 3 files changed, 41 insertions(+) diff --git a/AST.py b/AST.py index 22eb331..0af7ec2 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 4d2c392..1e9e94d 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 c015457..881fff5 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) -- GitLab