From e20ddf634b79d6d955bf341447ea16bf944c44a9 Mon Sep 17 00:00:00 2001
From: A404M <ahmadmahmoudiprogrammer@gmail.com>
Date: Tue, 28 Jan 2025 05:40:07 +0330
Subject: add more type checks

---
 src/compiler/ast-tree.c | 21 ++++++++++++++++++---
 src/compiler/ast-tree.h |  4 ++--
 2 files changed, 20 insertions(+), 5 deletions(-)

(limited to 'src/compiler')

diff --git a/src/compiler/ast-tree.c b/src/compiler/ast-tree.c
index f26d1b5..dcffecc 100644
--- a/src/compiler/ast-tree.c
+++ b/src/compiler/ast-tree.c
@@ -6,6 +6,11 @@
 #include <stdlib.h>
 #include <string.h>
 
+static const AstTree AST_TREE_U64_TYPE = {
+    .token = AST_TREE_TOKEN_TYPE_U64,
+    .metadata = NULL,
+};
+
 const char *AST_TREE_TOKEN_STRINGS[] = {
     "AST_TREE_TOKEN_FUNCTION",
 
@@ -673,7 +678,12 @@ AstTree *astTreeParsePrintU64(ParserNode *parserNode,
     return NULL;
   }
 
-  // TODO: check type to be u64
+  if (!hasTypeOf(operand, &AST_TREE_U64_TYPE)) {
+    printLog("operand = %s", AST_TREE_TOKEN_STRINGS[operand->token]);
+    printLog("Type mismatch");
+    astTreeDelete(operand);
+    return NULL;
+  }
 
   return newAstTree(AST_TREE_TOKEN_KEYWORD_PRINT_U64,
                     (AstTreeSingleChild *)operand);
@@ -721,7 +731,12 @@ RETURN_ERROR:
   return false;
 }
 
-bool hasTypeOf(AstTree *value, AstTree *type) {
+bool hasTypeOf(AstTree *value, const AstTree *type) {
+  if (value->token == AST_TREE_TOKEN_VARIABLE) {
+    AstTreeVariable *variable = value->metadata;
+    return typeIsEqual(variable->type, type);
+  }
+
   switch (type->token) {
   case AST_TREE_TOKEN_TYPE_TYPE:
     switch (value->token) {
@@ -821,7 +836,7 @@ AstTree *makeTypeOf(AstTree *value) {
   exit(1);
 }
 
-bool typeIsEqual(AstTree *type0, AstTree *type1) {
+bool typeIsEqual(const AstTree *type0, const AstTree *type1) {
   switch (type0->token) {
   case AST_TREE_TOKEN_FUNCTION:
   case AST_TREE_TOKEN_KEYWORD_PRINT_U64:
diff --git a/src/compiler/ast-tree.h b/src/compiler/ast-tree.h
index 7f3e3dc..c5f8dd5 100644
--- a/src/compiler/ast-tree.h
+++ b/src/compiler/ast-tree.h
@@ -118,6 +118,6 @@ bool astTreeParseConstant(ParserNode *parserNode,
                               AstTreeVariables **variables,
                               size_t variables_size);
 
-bool hasTypeOf(AstTree *value, AstTree *type);
+bool hasTypeOf(AstTree *value,const AstTree *type);
 AstTree *makeTypeOf(AstTree *value);
-bool typeIsEqual(AstTree *type0, AstTree *type1);
+bool typeIsEqual(const AstTree *type0, const AstTree *type1);
-- 
cgit v1.2.3