-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter.jj
407 lines (369 loc) · 12.9 KB
/
Interpreter.jj
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class CMMInterpreterVisitor implements
CMMVisitor<CMMData, CMMEnvironment> {
/**
* Environment keeps track of variable bindings
*/
protected CMMEnvironment env;
public CMMInterpreterVisitor() {
env = new CMMEnvironment();
}
public CMMData visit(CMMASTNode node, CMMEnvironment data) {
return null;
}
public CMMData visit(CMMASTProgramNode node, CMMEnvironment data) {
return visitChildren(node, data);
}
// FunctionDefinition -> Type id ParameterList Block
public CMMData visit(CMMASTFunctionDefinitionNode node, CMMEnvironment data) {
String id = node.getChild(1).getValue();
env.bind(id, new CMMFunction(node));
if (id.equals("main")) {
return node.getChild(3).accept(this, data);
}
return null;
}
public CMMData visit(CMMASTParameterListNode node, CMMEnvironment data) {
return null;
}
public CMMData visit(CMMASTParameterNode node, CMMEnvironment data) {
return null;
}
public CMMData visit(CMMASTElementNode node, CMMEnvironment data) {
return visitChildren(node, data);
}
public CMMData visit(CMMASTExpressionListNode node, CMMEnvironment data) {
return visitChildren(node, data);
}
public CMMData visit(CMMASTSimpleStatementNode node, CMMEnvironment data) {
return visitChildren(node, data);
}
public CMMData visit(CMMASTConstantNode node, CMMEnvironment data) {
return visitChildren(node, data);
}
// Assignment -> Logical (gets Logical)?
public CMMData visit(CMMASTAssignmentNode node, CMMEnvironment data) {
if (node.numChildren() > 1) {
CMMASTNode n = node.getChild(0); // Element
if (!n.getName().equals("Element") || n.numChildren() != 1)
throw new RuntimeException("Assigning to non-lvalue");
n = n.getChild(0); // ElementPlus
if (!n.getName().equals("ElementPlus") || n.numChildren() != 1)
throw new RuntimeException("Assigning to non-lvalue");
n = n.getChild(0); // Token
if (!n.getName().equals("id"))
throw new RuntimeException("Assigning to non-lvalue");
String id = n.getValue();
if (env.lookup(id) == null)
throw new RuntimeException("Assigning to undeclared variable " + id);
CMMData res = node.getChild(2).accept(this, data);
if (res.getClass() != env.lookup(id).getClass())
throw new RuntimeException("Type mismatch on assignment "
+ res.getClass() + " vs. " + env.lookup(id).getClass());
env.assign(id, res);
return res;
} else {
return visitChildren(node, data);
}
}
// Logical -> Comparison ((and|or) Comparison)* [>1]
public CMMData visit(CMMASTLogicalNode node, CMMEnvironment data) {
CMMData x = node.getChild(0).accept(this, data);
if (!(x instanceof CMMBoolean)) {
throw new RuntimeException("Invalid operand to logical operator");
}
CMMBoolean a = (CMMBoolean)x;
for (int i = 1; i < node.numChildren(); i += 2) {
CMMData y = node.getChild(i+1).accept(this, data);
String op = node.getChild(i).getName();
if (!(y instanceof CMMBoolean)) {
throw new RuntimeException("Invalid operand to logical operator");
}
CMMBoolean b = (CMMBoolean)y;
if (op.equals("and")) {
a = new CMMBoolean(a.value() && b.value());
} else if (op.equals("or")) {
a = new CMMBoolean(a.value() || b.value());
} else {
throw new RuntimeException("Unknown operator:" + op);
}
}
return a;
}
// Comparison -> Sum ((lt|gt|eq|le|ge|ne) Sum)? [>1]
public CMMData visit(CMMASTComparisonNode node, CMMEnvironment data) {
CMMData x = node.getChild(0).accept(this, data);
CMMData y = node.getChild(2).accept(this, data);
if (!(x instanceof CMMNumber) || !(y instanceof CMMNumber)) {
throw new RuntimeException("Invalid operand to comparison operator");
}
CMMNumber a = (CMMNumber)x;
CMMNumber b = (CMMNumber)y;
String op = node.getChild(1).getName();
if (op.equals("lt")) {
return new CMMBoolean(a.value < b.value);
} else if (op.equals("gt")) {
return new CMMBoolean(a.value > b.value);
} else if (op.equals("le")) {
return new CMMBoolean(a.value <= b.value);
} else if (op.equals("ge")) {
return new CMMBoolean(a.value >= b.value);
} else if (op.equals("eq")) {
return new CMMBoolean(a.value == b.value);
} else if (op.equals("ne")) {
return new CMMBoolean(a.value != b.value);
} else {
throw new RuntimeException("Unknown operator:" + op);
}
}
// Sum -> Term ((plus|minus) Term)* [>1]
public CMMData visit(CMMASTSumNode node, CMMEnvironment data) {
CMMData x = node.getChild(0).accept(this, data);
if (!(x instanceof CMMNumber)) {
throw new RuntimeException("Invalid operand to numerical operator");
}
CMMNumber a = (CMMNumber)x;
for (int i = 1; i < node.numChildren(); i += 2) {
CMMData y = node.getChild(i+1).accept(this, data);
String op = node.getChild(i).getName();
if (!(y instanceof CMMNumber)) {
throw new RuntimeException("Invalid operand to numerical operator +/-");
}
CMMNumber b = (CMMNumber)y;
if (op.equals("plus")) {
a = new CMMNumber(a.value() + b.value());
} else if (op.equals("minus")) {
a = new CMMNumber(a.value() - b.value());
} else {
throw new RuntimeException("Unknown operator:" + op);
}
}
return a;
}
// Term -> Exp ((multiply|divide|mod) Exp)* [>1]
public CMMData visit(CMMASTTermNode node, CMMEnvironment data) {
CMMData x = node.getChild(0).accept(this, data);
if (!(x instanceof CMMNumber)) {
throw new RuntimeException("Invalid operand to numerical operator +/-");
}
CMMNumber a = (CMMNumber)x;
for (int i = 1; i < node.numChildren(); i += 2) {
CMMData y = node.getChild(i+1).accept(this, data);
String op = node.getChild(i).getName();
if (!(y instanceof CMMNumber)) {
throw new RuntimeException("Invalid operand to numerical operator +/-");
}
CMMNumber b = (CMMNumber)y;
if (op.equals("multiply")) {
a = new CMMNumber(a.value() * b.value());
} else if (op.equals("divide")) {
a = new CMMNumber(a.value() / b.value());
} else if (op.equals("mod")) {
a = new CMMNumber(a.value() % b.value());
} else {
throw new RuntimeException("Unknown operator:" + op);
}
}
return a;
}
// Exp -> Element (exp Element)* [>1]
public CMMData visit(CMMASTExpNode node, CMMEnvironment data) {
CMMData x = node.getChild(0).accept(this, data);
if (!(x instanceof CMMNumber)) {
throw new RuntimeException("Invalid operand to numeric operator");
}
CMMNumber a = (CMMNumber)x;
for (int i = 1; i < node.numChildren(); i += 2) {
CMMData y = node.getChild(i+1).accept(this, data);
String op = node.getChild(i).getName();
if (!(y instanceof CMMNumber)) {
throw new RuntimeException("Invalid operand to numeric operator");
}
CMMNumber b = (CMMNumber)y;
if (op.equals("exp")) {
a = new CMMNumber(Math.pow(a.value(), b.value()));
} else {
throw new RuntimeException("Unknown operator:" + op);
}
}
return a;
}
// ElementPlus -> id ArgumentList?
public CMMData visit(CMMASTElementPlusNode node, CMMEnvironment data) {
if (node.numChildren() == 1) { // just an identifier
return node.getChild(0).accept(this, data);
} else { // a function call
String fname = node.getChild(0).getValue();
if (fname.equals("print")) {
CMMData res = visitChildren(node.getChild(1), data);
System.out.print(res);
return res;
}
if (fname.equals("println")) {
CMMData res = visitChildren(node.getChild(1), data);
System.out.println(res);
return res;
}
CMMData f = env.lookup(fname);
if (!(f instanceof CMMFunction)) {
throw new RuntimeException("Attempt to call non-function "+ fname);
}
CMMFunction fn = (CMMFunction)f;
env.pushFrame(); // add a frame for the parameters
env.bind("11this", fn);
env.bind("22returned", new CMMBoolean(false));
env.bind("22retval", null);
node.getChild(1).accept(this, data);
fn.value().getChild(3).accept(this, data); // visit the block now
CMMData res = env.lookup("22retval");
if (res == null)
throw new RuntimeException("Function not returning a value " + fname);
// TODO: typecheck return value
env.popFrame();
return res;
}
}
// ArgumentList -> lparen (Assignment (listsep Assignment)*)? rparen
public CMMData visit(CMMASTArgumentListNode node, CMMEnvironment data) {
CMMFunction fn = (CMMFunction)env.lookup("11this");
CMMASTParameterListNode pl = (CMMASTParameterListNode)fn.value().getChild(2);
if (pl.numChildren() != node.numChildren()) {
throw new RuntimeException("Calling function with wrong number of arguments");
}
for (int i = 1; i < node.numChildren()-1; i += 2) {
CMMData value = node.getChild(i).accept(this, data);
String id = pl.getChild(i).getChild(1).getValue();
env.bind(id, value);
}
return null;
}
// WhileLoop -> while Condition Block
public CMMData visit(CMMASTWhileLoopNode node, CMMEnvironment data) {
CMMData cont = node.getChild(1).accept(this, data);
if (!(cont instanceof CMMBoolean)) {
throw new RuntimeException("Invalid (non-boolean) condition in while loop");
}
CMMData res = null;
CMMBoolean cb = (CMMBoolean)cont;
while (cb.value()) {
res = node.getChild(2).accept(this, data);
cb = (CMMBoolean)node.getChild(1).accept(this, data);
}
return res;
}
public CMMData visit(CMMASTConditionNode node, CMMEnvironment data) {
return visitChildren(node, data);
}
// DoLoop -> do Block while Condition eol
public CMMData visit(CMMASTDoLoopNode node, CMMEnvironment data) {
throw new UnsupportedOperationException();
}
//@Override
public CMMData visit(CMMASTStatementNode node, CMMEnvironment data) {
return visitChildren(node, data);
}
//@Override
public CMMData visit(CMMASTTypeNode node, CMMEnvironment data) {
return null;
}
//@Override
public CMMData visit(CMMASTIfStatementNode node, CMMEnvironment data) {
throw new UnsupportedOperationException();
}
//@Override
/*
* Declaration -> Type Identifier (listsep Identifier)* eol
*/
public CMMData visit(CMMASTDeclarationNode node, CMMEnvironment data) {
CMMASTNode type = node.getChild(0);
String stype = type.getChild(0).getName();
if (stype.equals("number_t")) {
for (int i = 1; i < node.numChildren(); i += 2)
env.bind(node.getChild(i).getValue(), new CMMNumber(0));
} else if (stype.equals("string_t")) {
for (int i = 1; i < node.numChildren(); i += 2)
env.bind(node.getChild(i).getValue(), new CMMString(""));
} else if (stype.equals("boolean_t")) {
for (int i = 1; i < node.numChildren(); i += 2)
env.bind(node.getChild(i).getValue(), new CMMBoolean(false));
}
return null;
}
public CMMData visit(CMMASTBlockNode node, CMMEnvironment data) {
env.pushFrame();
CMMData res = visitChildren(node, data);
env.popFrame();
return res;
}
public CMMData visit(CMMASTToken node, CMMEnvironment data) {
if (node.getName().equals("number")) {
return new CMMNumber(Double.parseDouble(node.getValue()));
} else if (node.getName().equals("string")) {
return new CMMString(node.getValue());
} else if (node.getName().equals("boolean")) {
return new CMMBoolean(Boolean.parseBoolean(node.getValue()));
} else if (node.getName().equals("id")) {
String id = node.getValue();
if (env.lookup(id) == null)
throw new RuntimeException("Reference to undefined variable " + id);
return env.lookup(id);
}
return null;
}
//@Override
public CMMData visit(CMMASTReturnStatementNode node, CMMEnvironment data) {
CMMData r = node.getChild(1).accept(this, data);
env.assign("22retval", r);
env.assign("22returned", new CMMBoolean(true));
return null;
}
protected CMMData visitChildren(CMMASTNode node, CMMEnvironment data) {
CMMData last = null;
for (int i = 0; i < node.numChildren(); i++) {
CMMBoolean returned = (CMMBoolean)env.lookup("22returned");
if (returned != null && returned.value()) return null;
CMMData tmp = node.getChild(i).accept(this, data);
if (tmp != null) last = tmp;
}
return last;
}
//@Override
public CMMData visit(CMMASTNottedElementNode node, CMMEnvironment data) {
throw new RuntimeException("Boolean negation not yet implemented");
}
public static void main(String[] args) {
Reader r = null;
if (args.length == 0) {
r = new InputStreamReader(System.in);
} else {
try {
r = new FileReader(args[0]);
} catch (IOException e) {
System.err.println("Error occurred while opening input file " + args[0]);
System.err.println(e);
System.exit(-1);
}
}
CMMTokenizer t = new CMMTokenizer(r);
CMMParser p = new CMMParser(t);
CMMASTNode n = null;
try {
n = p.parse();
} catch (CMMTokenizerException e) {
System.err.println("A tokenizer exception occured:" + e);
System.exit(-1);
} catch (CMMParserException e) {
System.err.println("A parse exception occured:" + e);
System.exit(-1);
}
System.out.println("Program parsed successfully - attempting to run");
System.out.println("Program output:");
CMMInterpreterVisitor v = new CMMInterpreterVisitor();
CMMData res = n.accept(v, null);
System.out.print("Program value: ");
System.out.println(res);
}
}