This repository was archived by the owner on Jul 21, 2026. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterpreter.java
More file actions
Latest commit
380 lines (348 loc) · 11.4 KB
/
Copy pathInterpreter.java
File metadata and controls
380 lines (348 loc) · 11.4 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
packageaether;
importaether.ast.*;
importaether.lexer.Token;
importjava.util.ArrayList;
importjava.util.List;
/**
* Executes Aether programs by traversing the Abstract Syntax Tree (AST)
* utilizing the Visitor pattern. Resolves variables, evaluates expressions,
* and maintains environment scopes.
*/
publicclassInterpreterimplementsAST.Visitor<Object> {
/**
* The active execution scope holding variables and values.
*/
privateEnvironmentenvironment = newEnvironment();
/**
* Interprets a list of parsed statements, catching and logging runtime errors.
*
* @param statements the list of AST statements to execute
*/
publicvoidinterpret(List<AST.Stmt> statements) {
try {
for (AST.Stmtstatement : statements) {
if (statement != null) {
execute(statement);
}
}
} catch (RuntimeExceptionerror) {
System.err.println("Runtime Error: " + error.getMessage());
}
}
/**
* Helper method to execute a statement node.
*
* @param stmt the statement to execute
*/
privatevoidexecute(AST.Stmtstmt) {
stmt.accept(this);
}
/**
* Helper method to evaluate an expression node.
*
* @param expr the expression to evaluate
* @return the runtime value resulting from evaluation
*/
privateObjectevaluate(AST.Exprexpr) {
returnexpr.accept(this);
}
/**
* Visits a variable declaration statement. Evaluates the initializer if present
* and registers the variable in the environment.
*
* @param stmt the variable declaration statement
* @return null
*/
@Override
publicObjectvisitVarDeclStmt(VarDeclstmt) {
Objectvalue = null;
if (stmt.initializer() != null) {
value = evaluate(stmt.initializer());
}
environment.define(stmt.name().lexeme(), value);
returnnull;
}
/**
* Visits an expression statement. Evaluates the wrapped expression.
*
* @param stmt the expression statement
* @return null
*/
@Override
publicObjectvisitExpressionStmt(ExpressionStmtstmt) {
evaluate(stmt.expression());
returnnull;
}
/**
* Visits a block statement. Creates a nested local scope and executes all inner statements.
*
* @param stmt the block statement
* @return null
*/
@Override
publicObjectvisitBlockStmt(Blockstmt) {
executeBlock(stmt.statements(), newEnvironment(environment));
returnnull;
}
/**
* Executes a list of statements in the context of a specific Environment scope.
* Guarantees restoration of the original environment upon completion.
*
* @param statements the statements inside the block
* @param env the new local Environment scope
*/
publicvoidexecuteBlock(List<AST.Stmt> statements, Environmentenv) {
Environmentprevious = this.environment;
try {
this.environment = env;
for (AST.Stmtstatement : statements) {
if (statement != null) {
execute(statement);
}
}
} finally {
this.environment = previous;
}
}
/**
* Visits an if (flux) statement. Evaluates the condition and branches execution accordingly.
*
* @param stmt the flux statement
* @return null
*/
@Override
publicObjectvisitFluxStmt(Fluxstmt) {
if (isTruthy(evaluate(stmt.condition()))) {
if (stmt.thenBranch() != null) {
execute(stmt.thenBranch());
}
} elseif (stmt.elseBranch() != null) {
execute(stmt.elseBranch());
}
returnnull;
}
/**
* Visits a loop (cycle) statement. Executes the loop body repeatedly while the condition evaluates to truthy.
*
* @param stmt the cycle statement
* @return null
*/
@Override
publicObjectvisitCycleStmt(Cyclestmt) {
while (isTruthy(evaluate(stmt.condition()))) {
if (stmt.body() != null) {
execute(stmt.body());
}
}
returnnull;
}
/**
* Visits a reveal (print) statement. Outputs the stringified representation of the evaluated expression.
*
* @param stmt the reveal statement
* @return null
*/
@Override
publicObjectvisitRevealStmt(Revealstmt) {
Objectvalue = evaluate(stmt.expression());
System.out.println(stringify(value));
returnnull;
}
/**
* Visits an assignment expression. Evaluates the value and updates the variable in the environment.
*
* @param expr the assignment expression
* @return the assigned value
*/
@Override
publicObjectvisitAssignExpr(Assignexpr) {
Objectvalue = evaluate(expr.value());
environment.assign(expr.name(), value);
returnvalue;
}
/**
* Visits a variable lookup expression. Retrieves its value from the environment.
*
* @param expr the variable lookup expression
* @return the value of the variable
*/
@Override
publicObjectvisitVariableExpr(Variableexpr) {
returnenvironment.get(expr.name());
}
/**
* Visits a literal expression. Returns the literal value directly.
*
* @param expr the literal expression
* @return the literal value
*/
@Override
publicObjectvisitLiteralExpr(Literalexpr) {
returnexpr.value();
}
/**
* Visits an array literal expression. Evaluates all element expressions.
*
* @param expr the array literal expression
* @return a List containing evaluated element values
*/
@Override
publicObjectvisitArrayLiteralExpr(ArrayLiteralexpr) {
List<Object> elements = newArrayList<>();
for (AST.Exprelement : expr.elements()) {
elements.add(evaluate(element));
}
returnelements;
}
/**
* Visits a unary expression (! or -). Evaluates the right operand and applies the operator.
*
* @param expr the unary expression
* @return the evaluated unary result
*/
@Override
publicObjectvisitUnaryExpr(Unaryexpr) {
Objectright = evaluate(expr.right());
switch (expr.operator().type()) {
caseBANG -> {
return !isTruthy(right);
}
caseMINUS -> {
checkNumberOperand(expr.operator(), right);
return -(double) right;
}
default -> {
}
}
returnnull;
}
/**
* Visits a binary expression (+, -, *, /, comparisons, equalities).
* Evaluates both operands and applies the operation.
*
* @param expr the binary expression
* @return the evaluated binary result
*/
@Override
publicObjectvisitBinaryExpr(Binaryexpr) {
Objectleft = evaluate(expr.left());
Objectright = evaluate(expr.right());
switch (expr.operator().type()) {
caseGREATER -> {
checkNumberOperands(expr.operator(), left, right);
return (double) left > (double) right;
}
caseGREATER_EQUAL -> {
checkNumberOperands(expr.operator(), left, right);
return (double) left >= (double) right;
}
caseLESS -> {
checkNumberOperands(expr.operator(), left, right);
return (double) left < (double) right;
}
caseLESS_EQUAL -> {
checkNumberOperands(expr.operator(), left, right);
return (double) left <= (double) right;
}
caseBANG_EQUAL -> {
return !isEqual(left, right);
}
caseEQUAL_EQUAL -> {
returnisEqual(left, right);
}
caseMINUS -> {
checkNumberOperands(expr.operator(), left, right);
return (double) left - (double) right;
}
casePLUS -> {
if (leftinstanceofDoubled1 && rightinstanceofDoubled2) {
returnd1 + d2;
}
if (leftinstanceofStrings1 && rightinstanceofStrings2) {
returns1 + s2;
}
thrownewRuntimeException("Operands must be two numbers or two strings at line " + expr.operator().line() + ".");
}
caseSLASH -> {
checkNumberOperands(expr.operator(), left, right);
doubledivisor = (double) right;
if (divisor == 0) {
thrownewRuntimeException("Division by zero at line " + expr.operator().line() + ".");
}
return (double) left / divisor;
}
caseSTAR -> {
checkNumberOperands(expr.operator(), left, right);
return (double) left * (double) right;
}
default -> {
}
}
returnnull;
}
/**
* Checks if the evaluated value is truthy (non-null and not Boolean.FALSE).
*
* @param object the object to check
* @return true if truthy, false otherwise
*/
privatebooleanisTruthy(Objectobject) {
if (object == null) returnfalse;
if (objectinstanceofBooleanb) returnb;
returntrue;
}
/**
* Checks if two values are equal.
* Handles null values safely.
*
* @param a first operand
* @param b second operand
* @return true if equal, false otherwise
*/
privatebooleanisEqual(Objecta, Objectb) {
if (a == null && b == null) returntrue;
if (a == null) returnfalse;
returna.equals(b);
}
/**
* Validates that the operand is a number.
*
* @param operator the unary operator token (for line reporting)
* @param operand the operand to check
* @throws RuntimeException if operand is not a number
*/
privatevoidcheckNumberOperand(Tokenoperator, Objectoperand) {
if (operandinstanceofDouble) return;
thrownewRuntimeException("Operand must be a number at line " + operator.line() + ".");
}
/**
* Validates that both operands are numbers.
*
* @param operator the binary operator token
* @param left the left operand
* @param right the right operand
* @throws RuntimeException if either operand is not a number
*/
privatevoidcheckNumberOperands(Tokenoperator, Objectleft, Objectright) {
if (leftinstanceofDouble && rightinstanceofDouble) return;
thrownewRuntimeException("Operands must be numbers at line " + operator.line() + ".");
}
/**
* Converts a runtime object to its string representation for output.
* Truncates decimal parts (.0) for whole numbers.
*
* @param object the runtime value
* @return the stringified value
*/
privateStringstringify(Objectobject) {
if (object == null) return"nil";
if (objectinstanceofDoubled) {
Stringtext = d.toString();
if (text.endsWith(".0")) {
text = text.substring(0, text.length() - 2);
}
returntext;
}
returnobject.toString();
}
}