-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterpreter.java
More file actions
489 lines (418 loc) · 13.3 KB
/
Interpreter.java
File metadata and controls
489 lines (418 loc) · 13.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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class for interpreter
*/
public class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void>{
final Environment globals = new Environment();
private Environment environment = globals;
private final Map<Expr, Integer> locals = new HashMap<>();
Interpreter() {
globals.define("clock", new FeinCallable() {
@Override
public int arity() {
return 0;
}
@Override
public Object call(Interpreter interpreter, List<Object> arguments) {
return (double)System.currentTimeMillis() / 1000.0;
}
@Override
public String toString() { return "<native fn>"; }
});
}
/**
* Method to interpret the code
*
* @param statements List<Stmt>
*/
void interpret(List<Stmt> statements){
try{
for(Stmt statement : statements){
execute(statement);
}
} catch (RuntimeError error){
Fein.runtimeError(error);
}
}
@Override
public Object visitLiteralExpr(Expr.Literal expr){
return expr.value;
}
@Override
public Object visitGroupingExpr(Expr.Grouping expr){
return evaluate(expr.expression);
}
@Override
public Object visitUnaryExpr(Expr.Unary expr){
Object right = evaluate(expr.right);
switch (expr.operator.type){
case BANG:
return !isTruthy(right);
case MINUS:
checkNumberOperand(expr.operator, right);
return -(double)right;
}
// Unreachable.
return null;
}
/**
* Method to validate number operand
*
* @param operator Token
* @param operand Object
*/
private void checkNumberOperand(Token operator, Object operand) {
if(operand instanceof Double) return;
throw new RuntimeError(operator, "Operand must be a number");
}
@Override
public Object visitBinaryExpr(Expr.Binary expr){
Object left = evaluate(expr.left);
Object right = evaluate(expr.right);
switch (expr.operator.type){
case BANG_EQUAL: return !isEqual(left, right);
case EQUAL_EQUAL: return isEqual(left, right);
case GREATER:
checkNumberOperands(expr.operator, left, right);
return (double)left > (double)right;
case GREATER_EQUAL:
checkNumberOperands(expr.operator, left, right);
return (double)left >= (double)right;
case LESS:
checkNumberOperands(expr.operator, left, right);
return (double)left < (double)right;
case LESS_EQUAL:
checkNumberOperands(expr.operator, left, right);
return (double)left <= (double)right;
case MINUS:
checkNumberOperands(expr.operator, left, right);
return (double)left - (double)right;
case PLUS:
if (left instanceof Double && right instanceof Double) {
return (double)left + (double)right;
}
if (left instanceof String && right instanceof String) {
return left + (String)right;
}
if( left instanceof String && right instanceof Double){
return left + stringify(right);
}
if( left instanceof Double && right instanceof String ){
return stringify(left) + right;
}
throw new RuntimeError(expr.operator, "Operands must be numbers or strings.");
case SLASH:
checkNumberOperands(expr.operator, left, right);
if(right instanceof Double && (right.toString().startsWith("0"))){
throw new RuntimeError(expr.operator, "Cannot divide by 0.");
}
return (double)left / (double)right;
case STAR:
checkNumberOperands(expr.operator, left, right);
return (double)left * (double)right;
}
// Unreachable.
return null;
}
/**
* Method to visit expression statement
*
* @param stmt Stmt.Expression
* @return Void
*/
@Override
public Void visitExpressionStmt(Stmt.Expression stmt){
evaluate(stmt.expression);
return null;
}
/**
* Method to visit print stmt
*
* @param stmt Stmt.Print
* @return Void
*/
@Override
public Void visitPrintStmt(Stmt.Print stmt){
Object value = evaluate(stmt.expression);
System.out.println(stringify(value));
return null;
}
@Override
public Void visitReturnStmt(Stmt.Return stmt){
Object value = null;
if(stmt.value != null) value = evaluate(stmt.value);
throw new Return(value);
}
/**
* Method to evaluate variable statements
*
* @param stmt Stmt.Var
* @return Void
*/
@Override
public Void visitVarStmt(Stmt.Var stmt) {
Object value = null;
if(stmt.initializer != null){
value = evaluate(stmt.initializer);
}
environment.define(stmt.name.lexeme, value);
return null;
}
/**
* Method to process variable expression
*
* @param expr Expr.Variable
* @return Object
*/
@Override
public Object visitVariableExpr(Expr.Variable expr){
return lookUpVariable(expr.name, expr);
}
/**
* Method to look up variable
*
* @param name Token
* @param expr Expr
*
* @return Object
*/
private Object lookUpVariable(Token name, Expr expr) {
Integer distance = locals.get(expr);
if(distance != null) {
return environment.getAt(distance, name.lexeme);
} else {
return globals.get(name);
}
}
/**
* Method to process assignment
*
* @param expr Expr.Assign
* @return Object
*/
@Override
public Object visitAssignExpr(Expr.Assign expr){
Object value = evaluate(expr.value);
Integer distance = locals.get(expr);
if(distance != null) {
environment.assignAt(distance, expr.name, value);
} else {
globals.assign(expr.name, value);
}
return value;
}
@Override
public Void visitBlockStmt(Stmt.Block stmt){
executeBlock(stmt.statements, new Environment(environment));
return null;
}
@Override
public Void visitIfStmt(Stmt.If stmt){
if(isTruthy(evaluate(stmt.condition))){
execute(stmt.thenBranch);
} else if(stmt.elseBranch != null){
execute(stmt.elseBranch);
}
return null;
}
@Override
public Object visitLogicalExpr(Expr.Logical expr){
Object left = evaluate(expr.left);
if(expr.operator.type == TokenType.OR){
if(isTruthy(left)) return left;
} else {
if(!isTruthy(left)) return left;
}
return evaluate(expr.right);
}
@Override
public Void visitWhileStmt(Stmt.While stmt){
while(isTruthy(evaluate(stmt.condition))){
execute(stmt.body);
}
return null;
}
@Override
public Object visitCallExpr(Expr.Call expr){
Object callee = evaluate(expr.callee);
List<Object> arguments = new ArrayList<>();
for(Expr argument : expr.arguments){
arguments.add(evaluate(argument));
}
if(!(callee instanceof FeinCallable)){
throw new RuntimeError(expr.paren, "Can only call functions and classes.");
}
FeinCallable function = (FeinCallable) callee;
// Arity is the fancy term for the number of arguments a function or operation expects.
if(arguments.size() != function.arity()){
throw new RuntimeError(expr.paren, "Expected " +
function.arity() + " arguments but got " +
arguments.size() + ".");
}
return function.call(this, arguments);
}
@Override
public Object visitGetExpr(Expr.Get expr) {
Object object = evaluate(expr.object);
if(object instanceof FeinInstance) {
return ((FeinInstance) object).get(expr.name);
}
throw new RuntimeError(expr.name, "Only instances have properties.");
}
@Override
public Object visitSetExpr(Expr.Set expr) {
Object object = evaluate(expr.object);
if(!(object instanceof FeinInstance)) {
throw new RuntimeError(expr.name, "Only instances have fields.");
}
Object value = evaluate(expr.value);
((FeinInstance)object).set(expr.name, value);
return value;
}
@Override
public Object visitSuperExpr(Expr.Super expr) {
int distance = locals.get(expr);
FeinClass superclass = (FeinClass) environment.getAt(distance, "super");
FeinInstance object = (FeinInstance) environment.getAt(distance - 1, "this");
FeinFunction method = superclass.findMethod(expr.method.lexeme);
if(method == null) {
throw new RuntimeError(expr.method,
"Undefined property '" + expr.method.lexeme + "'.");
}
return method.bind(object);
}
@Override
public Object visitThisExpr(Expr.This expr) {
return lookUpVariable(expr.keyword, expr);
}
@Override
public Void visitFunctionStmt(Stmt.Function stmt){
FeinFunction function = new FeinFunction(stmt, environment, false);
environment.define(stmt.name.lexeme, function);
return null;
}
@Override
public Void visitClassStmt(Stmt.Class stmt) {
Object superclass = null;
if(stmt.superclass != null) {
superclass = evaluate(stmt.superclass);
if(!(superclass instanceof FeinClass)) {
throw new RuntimeError(stmt.superclass.name, "Superclass must be a class.");
}
}
environment.define(stmt.name.lexeme, null);
if(stmt.superclass != null) {
environment = new Environment(environment);
environment.define("super", superclass);
}
Map<String, FeinFunction> methods = new HashMap<>();
for(Stmt.Function method : stmt.methods) {
FeinFunction function = new FeinFunction(method, environment, method.name.lexeme.equals("init"));
methods.put(method.name.lexeme, function);
}
FeinClass klass = new FeinClass(stmt.name.lexeme, (FeinClass)superclass, methods);
if(superclass != null) {
environment = environment.enclosing;
}
environment.assign(stmt.name, klass);
return null;
}
/**
* Method to validate number operands
*
* @param operator Token
* @param left Object
* @param right Object
*/
private void checkNumberOperands(Token operator, Object left, Object right) {
if(left instanceof Double && right instanceof Double) return;
throw new RuntimeError(operator, "Operands must be numbers");
}
/**
* Method to check Truthy
* @param object Object
*
* @return boolean
*/
private boolean isTruthy(Object object){
if(object == null ) return false;
if(object instanceof Boolean) return (boolean) object;
return true;
}
/**
* Method to check equality
*
* @param a Object
* @param b Object
* @return boolean
*/
private boolean isEqual(Object a, Object b) {
if (a == null && b == null) return true;
if (a == null) return false;
return a.equals(b);
}
/**
* Method to stringfy the object
*
* @param object Object
*
* @return String
*/
private String stringify(Object object){
if(object == null) return "nil";
if(object instanceof Double){
String text = object.toString();
if(text.endsWith(".0")){
text = text.substring(0, text.length() - 2);
}
return text;
}
return object.toString();
}
/**
* Method to evaluate expression which calls interpreter's visitor implementation
*
* @param expr Expr
* @return Object
*/
private Object evaluate(Expr expr){
return expr.accept(this);
}
/**
* Method to execute statements
*
* @param stmt Stmt
*/
private void execute(Stmt stmt){
stmt.accept(this);
}
/**
* Method to execute block statments
*
* @param statements List<Stmt>
* @param environment Environment
*/
void executeBlock(List<Stmt> statements, Environment environment){
Environment previous = this.environment;
try{
this.environment = environment;
for(Stmt statement : statements){
execute(statement);
}
} finally {
this.environment = previous;
}
}
/**
* Method to resolve the expr
*
* @param expr Expr
* @param depth int
*/
void resolve(Expr expr, int depth) {
locals.put(expr, depth);
}
}