forked from leethater/ADS4_2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Expression.java
118 lines (91 loc) · 2.31 KB
/
Expression.java
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import java.util.List;
abstract class Expression{
public abstract int value(List<Identifier> m) throws DeclarationException;
public void checkNset(List<Identifier> map) throws DeclarationException{
}
}
class IntExpression extends Expression{
protected int value;
public IntExpression(int v){
this.value=v;
}
public int value(List<Identifier> list){
return value;
}
}
class ExpressionPlus extends Expression{
protected Expression expr1,expr2;
protected Token operator;
public ExpressionPlus(Expression e1,Expression e2,Token t){
expr1=e1;
expr2=e2;
operator=t;
}
public int value(List<Identifier> m) throws DeclarationException{
int a=expr1.value(m),b=expr2.value(m);
Sym sym=operator.getSym();
switch(sym){
case PLUS: return a+b;
case MINUS: return a-b;
case MULT: return a*b;
case DIV: return a/b;
case LESS: return Math.max(b-a,0);
case MORE: return Math.min(b-a,0);
case EQUALEQUALS: return (b==a)?1:0;
}
return Integer.MIN_VALUE;
}
}
class Identifier extends Expression{
protected Sym type;
protected String name;
protected Expression e;
public Identifier(String name){
this.name=name;
type=null;
e=null;
}
public Identifier(String name,Expression e,Sym type){
this.name=name;
this.e=e;
this.type=type;
}
public int value(List<Identifier> m) throws DeclarationException{
checkNset(m);
return e.value(m);
}
public Expression getExpression(){
return e;
}
public void setExpression(Expression e){
this.e=e;
}
public Sym getType(){
return type;
}
public void setType(Sym type){
this.type=type;
}
public String getName(){
return name;
}
public Identifier check(List<Identifier> list) throws DeclarationException{
for(Identifier i:list) {
if(i.getName().equals(this.name)) return i;
}
throw new DeclarationException(this.getName()+" has not been declared");
}
public Identifier checkYOLO(List<Identifier> list){
for(Identifier i:list) {
if(i.getName().equals(this.name)) return i;
}
return null;
}
public void checkNset(List<Identifier> list) throws DeclarationException{
Identifier i=check(list);
if(i!=null){
this.e=i.getExpression();
this.type=i.getType();
}
}
}