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 pathParser.java
More file actions
428 lines (368 loc) · 11.9 KB
/
Copy pathParser.java
File metadata and controls
428 lines (368 loc) · 11.9 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
package aether;
import aether.ast.*;
import aether.lexer.Token;
import aether.lexer.TokenType;
import java.util.ArrayList;
import java.util.List;
/**
* A recursive descent parser that parses a stream of Aether tokens
* into an Abstract Syntax Tree (AST) representing the program structure.
*/
public class Parser {
/**
* Special exception to unwind the parser stack upon encountering syntax errors.
*/
private static class ParseError extends RuntimeException {
}
/** The list of scanned tokens to be parsed. */
private final List<Token> tokens;
/** The index pointing to the current token being analyzed. */
private int current = 0;
/**
* Constructs a Parser with the given token stream.
*
* @param tokens the list of tokens to parse
*/
public Parser(List<Token> tokens) {
this.tokens = tokens;
}
/**
* Starts parsing the token stream into a list of AST statement nodes.
*
* @return a list of statement nodes representing the parsed program
*/
public List<AST.Stmt> parse() {
List<AST.Stmt> statements = new ArrayList<>();
while (!isAtEnd()) {
statements.add(declaration());
}
return statements;
}
/**
* Parses a declaration (variable declaration or standard statement).
* Attempts syntax recovery if a ParseError occurs.
*
* @return the parsed statement node, or null if an error was caught and synchronized
*/
private AST.Stmt declaration() {
try {
if (match(TokenType.MANIFEST)) return varDeclaration();
return statement();
} catch (ParseError error) {
synchronize();
return null;
}
}
/**
* Parses a variable declaration: "manifest" IDENTIFIER ("=" expression)? ";"
*
* @return the VarDecl statement node
*/
private AST.Stmt varDeclaration() {
Token name = consume(TokenType.IDENTIFIER, "Expect variable name.");
AST.Expr initializer = null;
if (match(TokenType.ASSIGN)) {
initializer = expression();
}
consume(TokenType.SEMICOLON, "Expect ';' after variable declaration.");
return new VarDecl(name, initializer);
}
/**
* Parses a single statement (if, print, while, block, or expression statement).
*
* @return the statement node
*/
private AST.Stmt statement() {
if (match(TokenType.FLUX)) return ifStatement();
if (match(TokenType.REVEAL)) return printStatement();
if (match(TokenType.CYCLE)) return whileStatement();
if (match(TokenType.LEFT_BRACE)) return new Block(block());
return expressionStatement();
}
/**
* Parses a block: "{" declaration* "}"
*
* @return a list of nested statements
*/
private List<AST.Stmt> block() {
List<AST.Stmt> statements = new ArrayList<>();
while (!check(TokenType.RIGHT_BRACE) && !isAtEnd()) {
statements.add(declaration());
}
consume(TokenType.RIGHT_BRACE, "Expect '}' after block.");
return statements;
}
/**
* Parses an if/conditional statement: "flux" "(" expression ")" statement ("else" statement)?
*
* @return the Flux statement node
*/
private AST.Stmt ifStatement() {
consume(TokenType.LEFT_PAREN, "Expect '(' after 'flux'.");
AST.Expr condition = expression();
consume(TokenType.RIGHT_PAREN, "Expect ')' after flux condition.");
AST.Stmt thenBranch = statement();
AST.Stmt elseBranch = null;
if (match(TokenType.ELSE)) {
elseBranch = statement();
}
return new Flux(condition, thenBranch, elseBranch);
}
/**
* Parses a print statement: "reveal" expression ";"
*
* @return the Reveal statement node
*/
private AST.Stmt printStatement() {
AST.Expr value = expression();
consume(TokenType.SEMICOLON, "Expect ';' after value.");
return new Reveal(value);
}
/**
* Parses a loop statement: "cycle" "(" expression ")" statement
*
* @return the Cycle statement node
*/
private AST.Stmt whileStatement() {
consume(TokenType.LEFT_PAREN, "Expect '(' after 'cycle'.");
AST.Expr condition = expression();
consume(TokenType.RIGHT_PAREN, "Expect ')' after cycle condition.");
AST.Stmt body = statement();
return new Cycle(condition, body);
}
/**
* Parses an expression statement: expression ";"
*
* @return the ExpressionStmt node
*/
private AST.Stmt expressionStatement() {
AST.Expr expr = expression();
consume(TokenType.SEMICOLON, "Expect ';' after expression.");
return new ExpressionStmt(expr);
}
/**
* Parses an expression. In our hierarchy, starts at assignment.
*
* @return the expression node
*/
private AST.Expr expression() {
return assignment();
}
/**
* Parses an assignment: IDENTIFIER "=" assignment | equality
*
* @return the assignment or equality node
*/
private AST.Expr assignment() {
AST.Expr expr = equality();
if (match(TokenType.ASSIGN)) {
Token equals = previous();
AST.Expr value = assignment();
if (expr instanceof Variable(Token name)) {
return new Assign(name, value);
}
error(equals, "Invalid assignment target.");
}
return expr;
}
/**
* Parses equality comparisons: comparison (("!=" | "==") comparison)*
*
* @return the parsed expression
*/
private AST.Expr equality() {
AST.Expr expr = comparison();
while (match(TokenType.BANG_EQUAL, TokenType.EQUAL_EQUAL)) {
Token operator = previous();
AST.Expr right = comparison();
expr = new Binary(expr, operator, right);
}
return expr;
}
/**
* Parses comparisons: term ((">" | ">=" | "<" | "<=") term)*
*
* @return the parsed expression
*/
private AST.Expr comparison() {
AST.Expr expr = term();
while (match(TokenType.GREATER, TokenType.GREATER_EQUAL, TokenType.LESS, TokenType.LESS_EQUAL)) {
Token operator = previous();
AST.Expr right = term();
expr = new Binary(expr, operator, right);
}
return expr;
}
/**
* Parses terms: factor (("-" | "+") factor)*
*
* @return the parsed expression
*/
private AST.Expr term() {
AST.Expr expr = factor();
while (match(TokenType.MINUS, TokenType.PLUS)) {
Token operator = previous();
AST.Expr right = factor();
expr = new Binary(expr, operator, right);
}
return expr;
}
/**
* Parses factors: unary (("/" | "*") unary)*
*
* @return the parsed expression
*/
private AST.Expr factor() {
AST.Expr expr = unary();
while (match(TokenType.SLASH, TokenType.STAR)) {
Token operator = previous();
AST.Expr right = unary();
expr = new Binary(expr, operator, right);
}
return expr;
}
/**
* Parses unary operators: ("!" | "-") unary | primary
*
* @return the parsed expression
*/
private AST.Expr unary() {
if (match(TokenType.BANG, TokenType.MINUS)) {
Token operator = previous();
AST.Expr right = unary();
return new Unary(operator, right);
}
return primary();
}
/**
* Parses primary expressions (literals, variables, grouping, or array literals).
*
* @return the parsed primary expression node
* @throws ParseError if no matching expression can be parsed
*/
private AST.Expr primary() {
if (match(TokenType.FALSE)) return new Literal(false);
if (match(TokenType.TRUE)) return new Literal(true);
if (match(TokenType.NIL)) return new Literal(null);
if (match(TokenType.NUMBER, TokenType.STRING)) {
return new Literal(previous().literal());
}
if (match(TokenType.IDENTIFIER)) {
return new Variable(previous());
}
if (match(TokenType.LEFT_PAREN)) {
AST.Expr expr = expression();
consume(TokenType.RIGHT_PAREN, "Expect ')' after expression.");
return expr;
}
if (match(TokenType.LEFT_BRACKET)) {
List<AST.Expr> elements = new ArrayList<>();
if (!check(TokenType.RIGHT_BRACKET)) {
do {
elements.add(expression());
} while (match(TokenType.COMMA));
}
consume(TokenType.RIGHT_BRACKET, "Expect ']' after array literal.");
return new ArrayLiteral(elements);
}
throw error(peek(), "Expect expression.");
}
/**
* Checks if the current token matches any of the specified types.
* Consumes the token if it matches.
*
* @param types the token types to check against
* @return true if matches and consumed, false otherwise
*/
private boolean match(TokenType... types) {
for (TokenType type : types) {
if (check(type)) {
advance();
return true;
}
}
return false;
}
/**
* Consumes the current token if it matches the expected type; otherwise throws an error.
*
* @param type the expected token type
* @param message the error message to display if not matched
* @return the consumed token
* @throws ParseError if not matched
*/
private Token consume(TokenType type, String message) {
if (check(type)) return advance();
throw error(peek(), message);
}
/**
* Checks if the current token matches the given type without consuming it.
*
* @param type the token type to check
* @return true if the token type matches, false otherwise
*/
private boolean check(TokenType type) {
if (isAtEnd()) return false;
return peek().type() == type;
}
/**
* Advances the pointer to the next token and returns the previous one.
*
* @return the previous token
*/
private Token advance() {
if (!isAtEnd()) current++;
return previous();
}
/**
* Checks if the parser has consumed all tokens in the stream.
*
* @return true if EOF reached, false otherwise
*/
private boolean isAtEnd() {
return peek().type() == TokenType.EOF;
}
/**
* Looks at the current token without consuming it.
*
* @return the current token
*/
private Token peek() {
return tokens.get(current);
}
/**
* Returns the token just consumed.
*
* @return the previous token
*/
private Token previous() {
return tokens.get(current - 1);
}
/**
* Logs a syntax error message and returns a ParseError exception.
*
* @param token the token at which the error occurred
* @param message the explanation of the error
* @return the ParseError exception to unwind stack
*/
private ParseError error(Token token, String message) {
System.err.printf("[Line %d] Error at '%s': %s%n", token.line(), token.lexeme(), message);
return new ParseError();
}
/**
* Synchronizes parser state after a syntax error to restart parsing at
* the next declaration boundary. Prevents cascading parser error messages.
*/
private void synchronize() {
advance();
while (!isAtEnd()) {
if (previous().type() == TokenType.SEMICOLON) return;
switch (peek().type()) {
case FLUX, CYCLE, REVEAL, MANIFEST -> {
return;
}
default -> advance();
}
}
}
}