-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASTPlus.java
More file actions
50 lines (40 loc) · 1.73 KB
/
Copy pathASTPlus.java
File metadata and controls
50 lines (40 loc) · 1.73 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
47
48
49
50
public class ASTPlus implements ASTNode {
ASTNode lhs, rhs;
public ASTPlus(ASTNode l, ASTNode r) {
lhs = l;
rhs = r;
}
@Override
public IValue eval(Environment<IValue> e) throws InterpreterError {
IValue v1 = lhs.eval(e);
IValue v2 = rhs.eval(e);
if (v1 == null || v2 == null) {
throw new InterpreterError("null value in + operator");
}
if (v1 instanceof VInt && v2 instanceof VInt) {
int i1 = ((VInt) v1).getval();
int i2 = ((VInt) v2).getval();
return new VInt(i1 + i2);
}
if (v1 instanceof VString || v2 instanceof VString) {
String s1 = v1.toStr();
String s2 = v2.toStr();
return new VString(s1 + s2);
}
throw new InterpreterError("illegal types to + operator");
}
@Override
public ASTType typecheck(Environment<ASTType> e) throws TypeCheckError, InterpreterError {
ASTType l = lhs.typecheck(e);
ASTType r = rhs.typecheck(e);
if (l instanceof ASTTInt && r instanceof ASTTInt)
return ASTTInt.tint;
if (l instanceof ASTTString || r instanceof ASTTString)
return ASTTString.tstring;
throw new TypeCheckError("+: arg types not int nor string");
}
@Override
public boolean isFreeOutsideLambda(String id) {
return lhs.isFreeOutsideLambda(id) || rhs.isFreeOutsideLambda(id);
}
}