-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASTAssign.java
More file actions
88 lines (73 loc) · 2.81 KB
/
Copy pathASTAssign.java
File metadata and controls
88 lines (73 loc) · 2.81 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
84
85
86
87
88
public class ASTAssign implements ASTNode {
ASTNode lhs, rhs;
public ASTAssign(ASTNode l, ASTNode r) {
lhs = l;
rhs = r;
}
@Override
public IValue eval(Environment<IValue> e) throws InterpreterError {
IValue rval = rhs.eval(e);
IValue lval = lhs.eval(e);
// addr(A)
if (lval instanceof MemoryManager.VAddress addr) {
try {
ASTLet.mem.memwrt(addr, rval);
return rval;
} catch (MemoryPanicError ex) {
throw new InterpreterError("addr: " + ex.getMessage());
}
}
// ref(A)
if (lval instanceof VCell cell) {
cell.setval(rval);
return rval;
}
// mut
if (lhs instanceof ASTId astId) {
IValue raw = astId.evalLValue(e);
if (raw instanceof VMut mut) {
try {
ASTLet.mem.memwrt(mut.getAddr(), rval);
return rval;
} catch (MemoryPanicError ex) {
throw new InterpreterError("mut: " + ex.getMessage());
}
}
}
throw new InterpreterError("left side of := must be a mutable, addr, 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 (defL instanceof ASTTAddr addr) {
if (!rvalType.subtypeOf(addr.getType(), e) || !addr.getType().subtypeOf(rvalType, e)) {
throw new TypeCheckError("Type mismatch in assignment to address: cannot assign " + rvalType.toStr() + " to " + defL.toStr());
}
return rvalType;
}
if (defL instanceof ASTTMut mut) {
if (!rvalType.subtypeOf(mut.getInner(), e)) {
throw new TypeCheckError(":=: type mismatch for mut variable - " + rvalType.toStr() + " is not a subtype of " + mut.getInner().toStr());
}
return rvalType;
}
if (defL instanceof ASTTRef ref) {
if (!rvalType.subtypeOf(ref.getType(), e)) {
throw new TypeCheckError(":=: type mismatch for ref - " + rvalType.toStr() + " is not a subtype of " + ref.getType().toStr());
}
return rvalType;
}
throw new TypeCheckError(":=: left side must be a ref or a mut variable");
}
@Override
public boolean isFreeOutsideLambda(String id) {
return lhs.isFreeOutsideLambda(id) || rhs.isFreeOutsideLambda(id);
}
}