From 5f77ea28928dd1bcb72e183e92c8eaf5ef122707 Mon Sep 17 00:00:00 2001
From: Xun Yang <x299yang@uwaterloo.ca>
Date: Sun, 12 Apr 2020 17:29:26 -0400
Subject: [PATCH] cast and instanceof

---
 ExprPrimaryNodes.py | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)

diff --git a/ExprPrimaryNodes.py b/ExprPrimaryNodes.py
index 6f74859..6fc1f92 100644
--- a/ExprPrimaryNodes.py
+++ b/ExprPrimaryNodes.py
@@ -303,6 +303,29 @@ class CastNode(ASTNode):
             return
         raise Exception("ERROR: Cannot cast type {} to type {}.".format(self.right.myType.name, self.left.myType.name))
 
+    def codeGen(self):
+        if hasattr(self, "code") and self.code != "":
+            return
+        self.code = ""
+
+        print(self.left.myType.name, self.typeName)
+        offset = self.left.myType.typePointer.subTypeOffset
+
+        # get object at right
+        self.code += "; casting\n"
+        self.right.codeGen()
+        self.code += self.right.code
+
+        # subtype test
+        self.code += p("mov", "ebx", "[eax]", "start subtype test") # access class tag of left object
+        self.code += p("mov", "ebx", "[ebx + 4]") # access subtype testing column
+        self.code += p("mov", "ebx", "[ebx + " + str(offset) + "]") # ebx has isSubtype
+
+        # exception if not subtype, else do nothing (object is already in eax)
+        self.code += p("cmp", "[G__Zero]", "ebx")
+        self.code += p("je", "H__Throw_Exception")
+        self.code += "; end of casting\n"
+
 ###################################################################################
 # unqualCreate NEW name LPAREN args RPAREN
 class ClassCreateNode(ASTNode):
@@ -475,6 +498,20 @@ class ExprNode(ASTNode):
             return
         self.code = ""
 
+        # instanceOf
+        if self.op == "instanceof":
+            offset = self.right.myType.typePointer.subTypeOffset
+            self.code += ("; evaluate instanceof\n")
+
+            self.left.codeGen()
+            self.code += self.left.code
+            self.code += p("mov", "eax", "[eax]") # access class tag of left object
+            self.code += p("mov", "eax", "[eax + 4]") # access subtype testing column
+            self.code += p("mov", "eax", "[eax + " + str(offset) + "]") # subType column stores 0 or 1 already
+
+            self.code += ("; end of instanceof\n")
+            return
+
         # Unary operations:
         if not self.left:
             # get right output
-- 
GitLab