summaryrefslogtreecommitdiff
path: root/src/ast/nodes/IfNode.java
blob: 223dffbfe58495236aeea716b637ff1ec719449f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package ast.nodes;

import ast.types.*;
import java.util.ArrayList;
import semanticanalysis.SemanticError;
import semanticanalysis.SymbolTable;

/**
 * Node for the `if` statement of the grammar.
 */
public class IfNode implements Node {

    private final Node guard;
    private final Node thenbranch;
    private final 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<>();

        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;
    }

}