-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBinaryOp.java
More file actions
68 lines (63 loc) · 1.3 KB
/
BinaryOp.java
File metadata and controls
68 lines (63 loc) · 1.3 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
class BinaryOp extends ExampleToken implements Token
{
Expr lhs, rhs;
String op;
public BinaryOp(Expr l, Expr r)
{
lhs = l;
rhs = r;
}
public BinaryOp(Expr l, String o, Expr r)
{
lhs = l;
op = o;
rhs = r;
}
public void setSym(String o)
{
op = o;
}
public String toString(int t)
{
return lhs.toString(t) + " " + op + " " + rhs.toString(t);
}
public FullType typeCheck() throws ExampleException
{
FullType l,r;
l = lhs.typeCheck();
r = rhs.typeCheck();
if (l.isArray || r.isArray || l.isFunction || r.isFunction)
throw new ExampleException("Error bad type for binary op");
if (l.baseType.equals("varf"))
return l;
return r;
}
public Object execute()
{
Object l;
Object r;
l = lhs.execute();
r = rhs.execute();
float lF, rF;
if (l instanceof Integer)
lF = (Integer)l;
else
lF = (Float)l;
if (r instanceof Integer)
rF = (Integer)r;
else
rF = (Float)r;
float res;
if (op.equals("+"))
res = lF + rF;
else if (op.equals("-"))
res = lF - rF;
else if (op.equals("*"))
res = lF * rF;
else
res = lF / rF;
if (l instanceof Float || r instanceof Float)
return new Float(res);
return new Integer((int)res);
}
}