From 8e7089a5d6ba1f4f50a90133bb50bc5c6c554aff Mon Sep 17 00:00:00 2001
From: Santo Cariotti <santo@dcariotti.me>
Date: Thu, 13 Jun 2024 11:00:06 +0200
Subject: Set up visitor (#3)

Co-authored-by: geno <gabriele.genovese2@studio.unibo.it>
---
 src/ast/nodes/IfNode.java | 71 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 71 insertions(+)
 create mode 100644 src/ast/nodes/IfNode.java

(limited to 'src/ast/nodes/IfNode.java')

diff --git a/src/ast/nodes/IfNode.java b/src/ast/nodes/IfNode.java
new file mode 100644
index 0000000..a4f160d
--- /dev/null
+++ b/src/ast/nodes/IfNode.java
@@ -0,0 +1,71 @@
+package com.clp.project.ast.nodes;
+
+import java.util.ArrayList;
+
+import com.clp.project.semanticanalysis.SemanticError;
+import com.clp.project.semanticanalysis.SymbolTable;
+import com.clp.project.ast.types.*;
+
+/**
+ * Node for the `if` statement of the grammar.
+ */
+public class IfNode implements Node {
+    private Node guard;
+    private Node thenbranch;
+    private Node elsebranch;
+
+    public IfNode(Node guard, Node thenbranch, Node elsebranch) {
+        this.guard = guard;
+        this.thenbranch = thenbranch;
+        this.elsebranch = elsebranch;
+    }
+
+    @Override
+    public ArrayList<SemanticError> checkSemantics(SymbolTable ST, int _nesting) {
+        ArrayList<SemanticError> errors = new ArrayList<SemanticError>();
+
+        errors.addAll(guard.checkSemantics(ST, _nesting));
+        errors.addAll(thenbranch.checkSemantics(ST, _nesting));
+        if (elsebranch != null) {
+            errors.addAll(elsebranch.checkSemantics(ST, _nesting));
+        }
+
+        return errors;
+    }
+
+    // FIXME: fix the if statement
+    @Override
+    public Type typeCheck() {
+        if (guard.typeCheck() instanceof BoolType) {
+            Type thenexp = thenbranch.typeCheck();
+            Type elseexp = elsebranch.typeCheck();
+            if (thenexp.getClass().equals(elseexp.getClass()))
+                return thenexp;
+            else {
+                System.out.println("Type Error: incompatible types in then and else branches");
+                return new ErrorType();
+            }
+        } else {
+            System.out.println("Type Error: non boolean condition in if");
+            return new ErrorType();
+        }
+    }
+
+    // TODO: add code generation for if
+    @Override
+    public String codeGeneration() {
+        return "";
+    }
+
+    @Override
+    public String toPrint(String prefix) {
+        String str = prefix + "If\n" + guard.toPrint(prefix + "  ") + thenbranch.toPrint(prefix + "  ");
+
+        if (elsebranch != null) {
+            str += elsebranch.toPrint(prefix + "  ");
+        }
+
+        return str;
+    }
+
+}
-- 
cgit v1.2.3-18-g5258