-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.ts
483 lines (388 loc) · 12.1 KB
/
Parser.ts
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
import {
Assign,
Binary,
Call,
Expr,
Get,
Grouping,
Literal,
Logical,
Set as SetExpr,
Super,
This as ThisExpr,
Unary,
Variable,
} from "./Expr.ts";
import Lox from "./Lox.ts";
import {
Block,
Class,
Expression,
Function,
If,
Print,
Return,
Stmt,
Var,
While,
} from "./Stmt.ts";
import Token from "./Token.ts";
import TokenType from "./TokenType.ts";
export default class Parser {
private current = 0;
private tokens: Token[];
constructor(tokens: Token[]) {
this.tokens = tokens;
}
parse(): Stmt[] {
try {
const statements: Stmt[] = [];
while (!this.isAtEnd()) {
statements.push(this.declaration());
}
return statements;
} catch (error: unknown) {
// @ts-expect-error //Needs to be worked upon
return null;
}
}
private declaration(): Stmt {
if (this.match(TokenType.CLASS)) return this.classDeclaration();
if (this.match(TokenType.FUN)) return this.function("function");
if (this.match(TokenType.VAR)) return this.varDeclaration();
return this.statement();
}
private classDeclaration(): Stmt {
const name: Token = this.consume(
TokenType.IDENTIFIER,
"Expect class name.",
);
let superclass: Variable | null = null;
if (this.match(TokenType.LESS)) {
this.consume(TokenType.IDENTIFIER, "Expect superclass name.");
superclass = new Variable(this.previous());
}
this.consume(TokenType.LEFT_BRACE, "Expect '{' before class body.");
const methods: Function[] = [];
while (!this.check(TokenType.RIGHT_BRACE) && !this.isAtEnd()) {
methods.push(this.function("method"));
}
this.consume(TokenType.RIGHT_BRACE, "Expect '}' after class body.");
return new Class(name, superclass, methods);
}
private varDeclaration(): Stmt {
const name: Token = this.consume(
TokenType.IDENTIFIER,
"Expect variable name.",
);
let initializer: Expr | null = null;
if (this.match(TokenType.EQUAL)) initializer = this.expression();
this.consume(TokenType.SEMICOLON, "Expect ';' after variable declaration.");
return new Var(name, initializer);
}
private statement(): Stmt {
if (this.match(TokenType.IF)) return this.ifStatement();
if (this.match(TokenType.PRINT)) return this.printStatement();
if (this.match(TokenType.RETURN)) return this.returnStatement();
if (this.match(TokenType.WHILE)) return this.whileStatement();
if (this.match(TokenType.FOR)) return this.forStatement();
if (this.match(TokenType.LEFT_BRACE)) return new Block(this.block());
return this.expressionStatement();
}
private ifStatement(): Stmt {
this.consume(TokenType.LEFT_PAREN, "Expect '(' after 'if'.");
const condition: Expr = this.expression();
this.consume(TokenType.RIGHT_PAREN, "Expect ')' after if condition.");
const thenBranch: Stmt = this.statement();
let elseBranch: Stmt | null = null;
if (this.match(TokenType.ELSE)) elseBranch = this.statement();
return new If(condition, thenBranch, elseBranch);
}
private printStatement(): Stmt {
const value: Expr = this.expression();
this.consume(TokenType.SEMICOLON, "Expect ';' after value.");
return new Print(value);
}
private returnStatement(): Stmt {
const keyword: Token = this.previous();
let value: Expr | null = null;
if (!this.check(TokenType.SEMICOLON)) {
value = this.expression();
}
this.consume(TokenType.SEMICOLON, "Expect ';' after return value.");
return new Return(keyword, value);
}
private whileStatement() {
this.consume(TokenType.LEFT_PAREN, "Expect '(' after 'while'.");
const condition: Expr = this.expression();
this.consume(TokenType.RIGHT_PAREN, "Expect ')' after condition.");
const body: Stmt = this.statement();
return new While(condition, body);
}
private forStatement(): Stmt {
this.consume(TokenType.LEFT_PAREN, "Expect '(' after 'for'.");
let initializer: Stmt | null;
if (this.match(TokenType.SEMICOLON)) {
initializer = null;
} else if (this.match(TokenType.VAR)) {
initializer = this.varDeclaration();
} else {
initializer = this.expressionStatement();
}
let condition: Expr | null = null;
if (!this.check(TokenType.SEMICOLON)) {
condition = this.expression();
}
this.consume(TokenType.SEMICOLON, "Expect ';' after loop condition.");
let increment: Expr | null = null;
if (!this.check(TokenType.RIGHT_PAREN)) {
increment = this.expression();
}
this.consume(TokenType.RIGHT_PAREN, "Expect ')' after for clauses.");
let body: Stmt = this.statement();
if (increment !== null) {
body = new Block([body, new Expression(increment)]);
}
if (condition === null) condition = new Literal(true);
body = new While(condition, body);
if (initializer !== null) {
body = new Block([initializer, body]);
}
return body;
}
private expressionStatement(): Stmt {
const expr: Expr = this.expression();
this.consume(TokenType.SEMICOLON, "Expect ';' after expression.");
return new Expression(expr);
}
private function(kind: string): Function {
const name: Token = this.consume(
TokenType.IDENTIFIER,
`Expect ${kind} name.`,
);
this.consume(TokenType.LEFT_PAREN, `Expect '(' after ${kind} name.`);
const parameters: Token[] = [];
if (!this.check(TokenType.RIGHT_PAREN)) {
do {
if (parameters.length >= 255) {
this.error(this.peek(), "Can't have more than 255 parameters");
}
parameters.push(
this.consume(TokenType.IDENTIFIER, "Expect parameter name."),
);
} while (this.match(TokenType.COMMA));
}
this.consume(TokenType.RIGHT_PAREN, "Expect ')' after parameters.");
this.consume(TokenType.LEFT_BRACE, `Expect '{' before ${kind} body`);
const body: Stmt[] = this.block();
return new Function(name, parameters, body);
}
private block(): Stmt[] {
const statements: Stmt[] = [];
while (!this.check(TokenType.RIGHT_BRACE) && !this.isAtEnd()) {
statements.push(this.declaration());
}
this.consume(TokenType.RIGHT_BRACE, "Expect '}' after block.");
return statements;
}
private expression(): Expr {
return this.assignment();
}
private assignment(): Expr {
const expr: Expr = this.or();
if (this.match(TokenType.EQUAL)) {
const equals: Token = this.previous();
const value: Expr = this.assignment();
if (expr instanceof Variable) {
const name: Token = expr.name;
return new Assign(name, value);
} else if (expr instanceof Get) {
return new SetExpr(expr.object, expr.name, value);
}
this.error(equals, "Invalid assignment target.");
}
return expr;
}
private or(): Expr {
let expr: Expr = this.and();
while (this.match(TokenType.OR)) {
const operator: Token = this.previous();
const right: Expr = this.and();
expr = new Logical(expr, operator, right);
}
return expr;
}
private and(): Expr {
let expr: Expr = this.equality();
while (this.match(TokenType.AND)) {
const operator: Token = this.previous();
const right: Expr = this.equality();
expr = new Logical(expr, operator, right);
}
return expr;
}
private equality(): Expr {
let expr: Expr = this.comparison();
while (this.match(TokenType.BANG_EQUAL, TokenType.EQUAL_EQUAL)) {
const operator: Token = this.previous();
const right: Expr = this.comparison();
expr = new Binary(expr, operator, right);
}
return expr;
}
private comparison(): Expr {
let expr: Expr = this.term();
while (
this.match(
TokenType.GREATER,
TokenType.GREATER_EQUAL,
TokenType.LESS,
TokenType.LESS_EQUAL,
)
) {
const operator: Token = this.previous();
const right: Expr = this.term();
expr = new Binary(expr, operator, right);
}
return expr;
}
private term(): Expr {
let expr: Expr = this.factor();
while (this.match(TokenType.MINUS, TokenType.PLUS)) {
const operator: Token = this.previous();
const right: Expr = this.factor();
expr = new Binary(expr, operator, right);
}
return expr;
}
private factor(): Expr {
let expr: Expr = this.unary();
while (this.match(TokenType.SLASH, TokenType.STAR)) {
const operator: Token = this.previous();
const right: Expr = this.unary();
expr = new Binary(expr, operator, right);
}
return expr;
}
private unary(): Expr {
if (this.match(TokenType.BANG, TokenType.MINUS)) {
const operator: Token = this.previous();
const right: Expr = this.unary();
return new Unary(operator, right);
}
return this.call();
}
private call(): Expr {
let expr: Expr = this.primary();
while (true) {
if (this.match(TokenType.LEFT_PAREN)) {
expr = this.finishCall(expr);
} else if (this.match(TokenType.DOT)) {
const name: Token = this.consume(
TokenType.IDENTIFIER,
"Expect property name after '.'",
);
expr = new Get(expr, name);
} else {
break;
}
}
return expr;
}
private finishCall(callee: Expr): Expr {
const args: Expr[] = [];
if (!this.check(TokenType.RIGHT_PAREN)) {
do {
if (args.length >= 255) {
this.error(this.peek(), "Can't have more than 255 arguments.");
}
args.push(this.expression());
} while (this.match(TokenType.COMMA));
}
const paren: Token = this.consume(
TokenType.RIGHT_PAREN,
"Expect ')' after arguments.",
);
return new Call(callee, paren, args);
}
private primary(): Expr {
if (this.match(TokenType.FALSE)) return new Literal(false);
if (this.match(TokenType.TRUE)) return new Literal(true);
if (this.match(TokenType.NIL)) return new Literal(null);
if (this.match(TokenType.NUMBER, TokenType.STRING)) {
return new Literal(this.previous().literal);
}
if (this.match(TokenType.SUPER)) {
const keyword: Token = this.previous();
this.consume(TokenType.DOT, "Expect '.' after 'super'.");
const method: Token = this.consume(TokenType.IDENTIFIER, "Expect superclass method name.");
return new Super(keyword, method);
}
if (this.match(TokenType.THIS)) {
return new ThisExpr(this.previous());
}
if (this.match(TokenType.IDENTIFIER)) {
return new Variable(this.previous());
}
if (this.match(TokenType.LEFT_PAREN)) {
const expr: Expr = this.expression();
this.consume(TokenType.RIGHT_PAREN, "Expect ')' after expression");
return new Grouping(expr);
}
throw this.error(this.peek(), "Expect expression.");
}
//todo: make use of this
private synchronize(): void {
this.advance();
while (!this.isAtEnd()) {
if (this.previous().type == TokenType.SEMICOLON) return;
switch (this.peek().type) {
case TokenType.CLASS:
case TokenType.FUN:
case TokenType.VAR:
case TokenType.FOR:
case TokenType.IF:
case TokenType.WHILE:
case TokenType.PRINT:
case TokenType.RETURN:
return;
}
this.advance();
}
}
private consume(type: TokenType, message: string): Token {
if (this.check(type)) return this.advance();
throw this.error(this.peek(), message);
}
private error(token: Token, message: string): ParseError {
Lox.error(token, message);
return new ParseError();
}
private match(...types: TokenType[]) {
for (const type of types) {
if (this.check(type)) {
this.advance();
return true;
}
}
return false;
}
private check(type: TokenType): boolean {
if (this.isAtEnd()) return false;
return this.peek().type == type;
}
private advance(): Token {
if (!this.isAtEnd()) this.current++;
return this.previous();
}
private isAtEnd(): boolean {
return this.peek().type == TokenType.EOF;
}
private peek(): Token {
return this.tokens[this.current];
}
private previous(): Token {
return this.tokens[this.current - 1];
}
}
class ParseError extends Error {}