-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASTIf.java
More file actions
46 lines (38 loc) · 1.48 KB
/
Copy pathASTIf.java
File metadata and controls
46 lines (38 loc) · 1.48 KB
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
public class ASTIf implements ASTNode {
ASTNode cond, ifBranch, elseBranch;
public ASTIf(ASTNode cond, ASTNode ifBranch, ASTNode elseBranch) {
this.cond = cond;
this.ifBranch = ifBranch;
this.elseBranch = elseBranch;
}
@Override
public IValue eval(Environment<IValue> e) throws InterpreterError {
IValue condVal = cond.eval(e);
if (!(condVal instanceof VBool)) {
throw new InterpreterError("condition of if must be a boolean");
}
if (((VBool) condVal).getval()) {
return ifBranch.eval(e);
} else {
return elseBranch.eval(e);
}
}
@Override
public ASTType typecheck(Environment<ASTType> e) throws TypeCheckError, InterpreterError {
ASTType condType = cond.typecheck(e);
if (!(condType instanceof ASTTBool)) {
throw new TypeCheckError("if: condition not bool, got " + condType.toStr());
}
ASTType thenType = ifBranch.typecheck(e);
ASTType elseType = elseBranch.typecheck(e);
try {
return thenType.computeLUB(elseType, e);
} catch (TypeCheckError tce) {
throw new TypeCheckError("if: branches have incompatible types: " + thenType.toStr() + " vs " + elseType.toStr());
}
}
@Override
public boolean isFreeOutsideLambda(String id) {
return cond.isFreeOutsideLambda(id) || ifBranch.isFreeOutsideLambda(id) || elseBranch.isFreeOutsideLambda(id);
}
}