-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASTCAssign.java
More file actions
83 lines (67 loc) · 2.64 KB
/
Copy pathASTCAssign.java
File metadata and controls
83 lines (67 loc) · 2.64 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public class ASTCAssign implements ASTNode {
ASTNode lhs, rhs;
public ASTCAssign(ASTNode l, ASTNode r) {
lhs = l;
rhs = r;
}
@Override
public IValue eval(Environment<IValue> e) throws InterpreterError {
IValue rval = rhs.eval(e);
if (!(rval instanceof VInt))
throw new InterpreterError("illegal right type to += operator");
if (lhs instanceof ASTId astId) {
IValue raw = astId.evalLValue(e);
if (raw instanceof VMut mut) {
try {
IValue old = ASTLet.mem.memrd(mut.getAddr());
if (!(old instanceof VInt))
throw new InterpreterError("illegal types to += operator");
ASTLet.mem.memwrt(mut.getAddr(), new VInt(((VInt)old).getval() + ((VInt)rval).getval()));
return old;
} catch (MemoryPanicError ex) {
throw new InterpreterError("mut: " + ex.getMessage());
}
}
}
IValue lval = lhs.eval(e);
if (lval instanceof VCell cell) {
IValue old = cell.getval();
if (!(old instanceof VInt))
throw new InterpreterError("illegal types to += operator");
cell.setval(new VInt(((VInt)old).getval() + ((VInt)rval).getval()));
return old;
}
throw new InterpreterError("+= : left side must be a mut or ref");
}
@Override
public ASTType typecheck(Environment<ASTType> e) throws TypeCheckError, InterpreterError {
ASTType rvalType = rhs.typecheck(e);
ASTType l;
if (lhs instanceof ASTId astId) {
l = astId.typecheckLValue(e);
} else {
l = lhs.typecheck(e);
}
ASTType defL = ASTTypeDef.unfold(l, e);
if (!rvalType.subtypeOf(ASTTInt.tint, e)) {
throw new TypeCheckError("+= : right side must be int, got" + rvalType.toStr());
}
if (defL instanceof ASTTMut mut) {
if (!mut.getInner().subtypeOf(ASTTInt.tint, e)) {
throw new TypeCheckError("+= : mut must contain int");
}
return ASTTInt.tint;
}
if (defL instanceof ASTTRef ref) {
if (!ref.getType().subtypeOf(ASTTInt.tint, e)) {
throw new TypeCheckError("+= : ref must contain int");
}
return ASTTInt.tint;
}
throw new TypeCheckError("+= : left side must be a ref or mut ");
}
@Override
public boolean isFreeOutsideLambda(String id) {
return lhs.isFreeOutsideLambda(id) || rhs.isFreeOutsideLambda(id);
}
}