-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterpreter.java
388 lines (349 loc) · 12.5 KB
/
Interpreter.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
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
package SLox;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class Interpreter implements Expr.Visitor<Object>,
Stmt.Visitor<Void> {
// private Environment environment = new Environment();
final Environment globals = new Environment();
private Environment environment = globals;
private final Map<Expr, Integer> locals = new HashMap<>();
Interpreter() {
globals.define("clock", new LoxCallable() {
@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>"; }
});
}
private Boolean isRepl = false;
void interpret(List<Stmt> statements, boolean isRepl) {
this.isRepl = isRepl;
try {
for (Stmt statement : statements) {
execute(statement);
}
} catch (RuntimeError error) {
lox.runtimeError(error);
}
}
private void execute(Stmt stmt) {
stmt.accept(this);
}
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();
}
@Override
public Object visitLiteralExpr(Expr.Literal expr){
return expr.value;
}
@Override
public Object visitGroupingExpr(Expr.Grouping expr) {
return evaluate(expr.expression);
}
private Object evaluate(Expr expr) {
return expr.accept(this);
}
@Override
public Void visitExpressionStmt(Stmt.Expression stmt) {
Object rizz = evaluate(stmt.expression);
if(isRepl)
System.out.println(stringify(rizz));
return null;
}
// @Override
// public Void visitVariableExpr(com.craftinginterpreters.lox.Expr.Variable stmt) {
// return null;
// }
@Override
public Void visitPrintStmt(Stmt.Print stmt) {
Object value = evaluate(stmt.expression);
System.out.println(stringify(value));
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 Void visitVarStmt(Stmt.Var stmt) {
Object value = UndefinedClass.Instance;
if (stmt.initializer != null) {
value = evaluate(stmt.initializer);
}
environment.define(stmt.name.lexeme, value);
return null;
}
@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; //why ??
}
@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;
}
@Override
public Void visitClassStmt(Stmt.Class stmt) {
Object superclass = null;
if (stmt.superclass != null) {
superclass = evaluate(stmt.superclass);
if (!(superclass instanceof LoxClass)) {
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, LoxFunction> methods = new HashMap<>();
for (Stmt.Function method : stmt.methods) {
LoxFunction function = new LoxFunction(method, environment, method.name.lexeme.equals("init"), method.isGetter);
methods.put(method.name.lexeme, function);
}
LoxClass klass = new LoxClass(stmt.name.lexeme, (LoxClass)superclass, methods);
if (superclass != null) {
environment = environment.enclosing;
}
environment.assign(stmt.name, klass);
return null;
}
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;
}
}
@Override
public Object visitVariableExpr(Expr.Variable expr) {
Object O = lookUpVariable(expr.name, expr);
if (O instanceof UndefinedClass){
throw new RuntimeError(expr.name,"Variable is uninitialized " + expr.name.lexeme);
}
return O;
}
private boolean isTruthy(Object object) {
if (object == null) return false;
if (object instanceof Boolean) return (boolean)object;
return true;
}
@Override
public Void visitWhileStmt(Stmt.While stmt) {
//we cant execute once then put in while bcuz of increments
while (isTruthy(evaluate(stmt.condition))) {
execute(stmt.body);
}
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 visitBlockStmt(Stmt.Block stmt) {
executeBlock(stmt.statements, new Environment(environment));
return null;
}
@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 COMMA: return 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 SLASH:
checkNumberOperands(expr.operator, left, right);
return (double)left / (double)right;
case STAR:
checkNumberOperands(expr.operator, left, right);
return (double)left * (double)right;
case PLUS:
if (left instanceof Double && right instanceof Double) {
return (double)left + (double)right;
}
//CHALLENGE 2
if (left instanceof String || right instanceof String) {
//assert left instanceof String;
return stringify(left )+ stringify(right);
}
// if (left instanceof String && right instanceof Double) {
// String text = right.toString();
// if (right.toString().endsWith(".0")) {
// text = text.substring(0, text.length() - 2);
// }
// return (String)left + text;
// }
throw new RuntimeError(expr.operator,
"Operands must be two numbers or two strings.");
default:
break;
}
// Unreachable.
return null;
}
@Override
public Void visitReturnStmt(Stmt.Return stmt) {
Object value = null;
if (stmt.value != null) value = evaluate(stmt.value);
throw new Return(value);
}
@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 LoxCallable)) {
throw new RuntimeError(expr.paren,
"Can only call functions and classes.");
}
LoxCallable function = (LoxCallable) callee;
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 visitLambdaExpr(Expr.Lambda expr){
return new LoxLambda(expr, environment);
}
@Override
public Void visitFunctionStmt(Stmt.Function stmt) {
LoxFunction function = new LoxFunction(stmt, environment, false, stmt.isGetter);
environment.define(stmt.name.lexeme, function);
return null;
}
@Override
public Object visitGetExpr(Expr.Get expr) {
Object object = evaluate(expr.object);
if (object instanceof LoxInstance) {
Object member = ((LoxInstance) object).get(expr.name);
if(member instanceof LoxFunction && ((LoxFunction) member).GetisGetter()){
return ((LoxFunction) member).call(this,new ArrayList<>());}
return member;
}
throw new RuntimeError(expr.name,
"Only instances have properties.");
}
@Override
public Object visitSetExpr(Expr.Set expr) {
Object object = evaluate(expr.object);
if (!(object instanceof LoxInstance)) {
throw new RuntimeError(expr.name,
"Only instances have fields.");
}
Object value = evaluate(expr.value);
((LoxInstance)object).set(expr.name, value);
return value;
}
@Override
public Object visitAnaExpr(Expr.Ana expr) {
return lookUpVariable(expr.keyword, expr);
}
@Override
public Object visitSuperExpr(Expr.Super expr) {
int distance = locals.get(expr);
LoxClass superclass = (LoxClass)environment.getAt(
distance, "super");
LoxInstance object = (LoxInstance)environment.getAt(
distance - 1, "this");
LoxFunction method = superclass.findMethod(expr.method.lexeme);
if (method == null) {
throw new RuntimeError(expr.method,
"Undefined property '" + expr.method.lexeme + "'.");
}
return method.bind(object);
}
void resolve(Expr expr, int depth) {
locals.put(expr, depth);
}
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);
}
}
private boolean isEqual(Object a, Object b) {
if (a == null && b == null) return true;
if (a == null) return false;
return a.equals(b);
}
private void checkNumberOperand(Token operator, Object operand) {
if (operand instanceof Double) return;
throw new RuntimeError(operator, "Operand must be a number.");
}
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.");
}
}