-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.cpp
510 lines (463 loc) · 11.6 KB
/
parser.cpp
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/*
* File: parser.cpp
* -----------------
* This file implements a parser for a custom language. The parser takes a vector of tokens
* as input and generates an abstract syntax tree (AST) as output. The AST is a hierarchical
* representation of the source code, which can be used for further processing such as
* interpretation or compilation.
*
* The parser uses recursive descent parsing, a top-down parsing technique that starts with
* the highest level of the grammar and recursively breaks it down into its constituent parts.
*
* The parser supports various language constructs such as expressions, statements, functions,
* classes, and control flow structures. Each construct is parsed by a separate method, and
* these methods call each other recursively to parse nested constructs.
*
* The parser also includes error handling. If a syntax error is detected, an exception is
* thrown and the parser attempts to synchronize with the next valid position in the source
* code.
*/
#include <stdexcept>
#include <vector>
#include "parser.h"
#include "error.h"
Parser::Parser(std::vector<Token> tokens)
{
this->tokens = tokens;
}
std::vector<Stmt *> Parser::Parse()
{
std::vector<Stmt *> statements;
while (!IsAtEnd())
{
statements.push_back(Declaration());
}
return statements;
}
void Parser::Synchronize()
{
Advance();
while (!IsAtEnd())
{
if (Previous().type == SEMICOLON)
return;
switch (Peek().type)
{
case CLASS:
case FUN:
case VAR:
case FOR:
case IF:
case WHILE:
case PRINT:
case RETURN:
return;
default:
break;
}
Advance();
}
}
Expr *Parser::ExpressionFun()
{
return Assignment();
}
Stmt *Parser::PrintStatement()
{
Expr *value = ExpressionFun();
Consume(SEMICOLON, "Expect ';' after value.");
return new Print(value);
}
Stmt *Parser::VarDeclaration()
{
Token name = Consume(IDENTIFIER, "Expect variable name.");
Expr *initializer = nullptr;
if (Match(EQUAL))
{
initializer = ExpressionFun();
}
Consume(SEMICOLON, "Expect ';' after variable declaration.");
return new Var(name, initializer);
}
Stmt *Parser::WhileStatement()
{
Consume(LEFT_PAREN, "Expect '(' after 'while'.");
Expr *condition = ExpressionFun();
Consume(RIGHT_PAREN, "Expect ')' after condition.");
Stmt *body = Statement();
return new While(condition, body);
}
Stmt *Parser::ExpressionStatement()
{
Expr *expr = ExpressionFun();
Consume(SEMICOLON, "Expect ';' after expression.");
return new Expression(expr);
}
Function *Parser::FunctionMethod(std::string kind)
{
Token name = Consume(IDENTIFIER, "Expect " + kind + " name.");
Consume(LEFT_PAREN, "Expect '(' after " + kind + " name.");
std::vector<Token> parameters;
if (!Check(RIGHT_PAREN))
{
do
{
if (parameters.size() >= 255)
{
Error(Peek(), "Can't have more than 255 parameters.");
}
parameters.push_back(Consume(IDENTIFIER, "Expect parameter name."));
} while (Match(COMMA));
}
Consume(RIGHT_PAREN, "Expect ')' after parameters.");
Consume(LEFT_BRACE, "Expect '{' before " + kind + " body.");
std::vector<Stmt *> body = BlockFun();
return new Function(name, parameters, body);
}
std::vector<Stmt *> Parser::BlockFun()
{
std::vector<Stmt *> statements;
while (!Check(RIGHT_BRACE) && !IsAtEnd())
statements.push_back(Declaration());
Consume(RIGHT_BRACE, "Expect '}' after block.");
return statements;
}
Expr *Parser::Assignment()
{
Expr *expr = Or();
if (Match(EQUAL))
{
Token equals = Previous();
Expr *value = Assignment();
if (auto variableExpr = dynamic_cast<Variable *>(expr))
{
Token name = variableExpr->name;
return new Assign(name, value);
}
else if (auto getExpr = dynamic_cast<Get *>(expr))
{
return new Set(getExpr->object, getExpr->name, value);
Error(equals, "Invalid assignment target.");
}
}
return expr;
}
Expr *Parser::Or()
{
Expr *expr = And();
while (Match(OR))
{
Token op = Previous();
Expr *right = And();
expr = new Logical(expr, op, right);
}
return expr;
}
Expr *Parser::And()
{
Expr *expr = Equality();
while (Match(AND))
{
Token op = Previous();
Expr *right = Equality();
expr = new Logical(expr, op, right);
}
return expr;
}
Stmt *Parser::Statement()
{
if (Match(FOR))
return ForStatement();
if (Match(IF))
return IfStatement();
if (Match(PRINT))
return PrintStatement();
if (Match(RETURN))
return ReturnStatement();
if (Match(WHILE))
return WhileStatement();
if (Match(LEFT_BRACE))
return new Block(BlockFun());
return ExpressionStatement();
}
Stmt *Parser::ReturnStatement()
{
Token keyword = Previous();
Expr *value = nullptr;
if (!Check(SEMICOLON))
{
value = ExpressionFun();
}
Consume(SEMICOLON, "Expect ';' after return value.");
return new Return(keyword, value);
}
Stmt *Parser::ForStatement()
{
Consume(LEFT_PAREN, "Expect '(' after 'for'.");
Stmt *initializer;
if (Match(SEMICOLON))
{
initializer = nullptr;
}
else if (Match(VAR))
{
initializer = VarDeclaration();
}
else
{
initializer = ExpressionStatement();
}
Expr *condition = nullptr;
if (!Check(SEMICOLON))
{
condition = ExpressionFun();
}
Consume(SEMICOLON, "Expect ';' after loop condition.");
Expr *increment = nullptr;
if (!Check(RIGHT_PAREN))
{
increment = ExpressionFun();
}
Consume(RIGHT_PAREN, "Expect ')' after for clauses.");
Stmt *body = Statement();
if (increment != nullptr)
{
std::vector<Stmt *> stmtVector;
stmtVector.push_back(body);
stmtVector.push_back(new Expression(increment));
body = new Block(stmtVector);
}
if (condition == nullptr)
condition = new Literal(true);
body = new While(condition, body);
if (initializer != nullptr)
{
std::vector<Stmt *> stmtVector;
stmtVector.push_back(initializer);
stmtVector.push_back(body);
body = new Block(stmtVector);
}
return body;
}
Stmt *Parser::IfStatement()
{
Consume(LEFT_PAREN, "Expect '(' after 'if'.");
Expr *condition = ExpressionFun();
Consume(RIGHT_PAREN, "Expect ')' after if condition.");
Stmt *thenBranch = Statement();
Stmt *elseBranch = nullptr;
if (Match(ELSE))
{
elseBranch = Statement();
}
return new If(condition, thenBranch, elseBranch);
}
Stmt *Parser::Declaration()
{
try
{
if (Match(CLASS))
return ClassDeclaration();
if (Match(FUN))
return FunctionMethod("function");
if (Match(VAR))
return VarDeclaration();
return Statement();
}
catch (const ParseError &error)
{
Synchronize();
return nullptr;
}
}
Stmt *Parser::ClassDeclaration()
{
Token name = Consume(IDENTIFIER, "Expect class name.");
Variable *superclass = nullptr;
if (Match(LESS))
{
Consume(IDENTIFIER, "Expect superclass name.");
superclass = new Variable(Previous());
}
Consume(LEFT_BRACE, "Expect '{' before class body.");
std::vector<Function *> methods;
while (!Check(RIGHT_BRACE) && !IsAtEnd())
{
methods.push_back(FunctionMethod("method"));
}
Consume(RIGHT_BRACE, "Expect '}' after class body.");
return new Class(name, superclass, methods);
}
Expr *Parser::Equality()
{
Expr *expr = Comparison();
while (Match(BANG_EQUAL, EQUAL_EQUAL))
{
Token op = Previous();
Expr *right = Comparison();
expr = new Binary(expr, op, right);
}
return expr;
}
Expr *Parser::Comparison()
{
Expr *expr = Term();
while (Match(GREATER, GREATER_EQUAL, LESS, LESS_EQUAL))
{
Token op = Previous();
Expr *right = Term();
expr = new Binary(expr, op, right);
}
return expr;
}
Expr *Parser::Term()
{
Expr *expr = Factor();
while (Match(MINUS, PLUS))
{
Token op = Previous();
Expr *right = Factor();
expr = new Binary(expr, op, right);
}
return expr;
}
Expr *Parser::Factor()
{
Expr *expr = UnaryFun();
while (Match(SLASH, STAR))
{
Token op = Previous();
Expr *right = UnaryFun();
expr = new Binary(expr, op, right);
}
return expr;
}
Expr *Parser::UnaryFun()
{
if (Match(BANG, MINUS))
{
Token op = Previous();
Expr *right = UnaryFun();
return new Unary(op, right);
}
return CallFun();
}
Expr *Parser::FinishCall(Expr *callee)
{
std::vector<Expr *> arguments;
if (!Check(RIGHT_PAREN))
{
do
{
if (arguments.size() >= 255)
{
Error(Peek(), "Can't have more than 255 arguments.");
}
arguments.push_back(ExpressionFun());
} while (Match(COMMA));
}
Token paren = Consume(RIGHT_PAREN, "Expect ')' after arguments.");
return new Call(callee, paren, arguments);
}
Expr *Parser::CallFun()
{
Expr *expr = Primary();
while (true)
{
if (Match(LEFT_PAREN))
{
expr = FinishCall(expr);
}
else if (Match(DOT))
{
Token name = Consume(IDENTIFIER, "Expect property name after '.'.");
expr = new Get(expr, name);
}
else
{
break;
}
}
return expr;
}
Expr *Parser::Primary()
{
if (Match(FALSE))
return new Literal(false);
if (Match(TRUE))
return new Literal(true);
if (Match(NIL))
return new Literal(nullptr);
if (Match(NUMBER, STRING))
return new Literal(Previous().literal);
if (Match(SUPER))
{
Token keyword = Previous();
Consume(DOT, "Expect '.' after 'super'.");
Token method = Consume(IDENTIFIER,
"Expect superclass method name.");
return new Super(keyword, method);
}
if (Match(THIS))
return new This(Previous());
if (Match(IDENTIFIER))
return new Variable(Previous());
if (Match(LEFT_PAREN))
{
Expr *expr = ExpressionFun();
Consume(RIGHT_PAREN, "Expect ')' after expression.");
return new Grouping(expr);
}
throw Error(Peek(), "Expect expression.");
}
template <typename... Args>
bool Parser::Match(Args... types)
{
TokenType typesArray[] = {types...};
for (TokenType type : typesArray)
{
if (Check(type))
{
Advance();
return true;
}
}
return false;
}
Token Parser::Consume(TokenType type, std::string message)
{
if (Check(type))
return Advance();
throw Error(Peek(), message);
}
Parser::ParseError Parser::Error(Token token, std::string message)
{
Error::ReportError(token, message);
return ParseError();
}
bool Parser::Check(TokenType type)
{
if (IsAtEnd())
return false;
return Peek().type == type;
}
Token Parser::Advance()
{
if (!IsAtEnd())
current++;
return Previous();
}
bool Parser::IsAtEnd()
{
return Peek().type == END_OF_FILE;
}
Token Parser::Peek()
{
if (static_cast<size_t>(current) >= tokens.size())
return Token(END_OF_FILE, "", nullptr, tokens[current - 1].line);
return tokens[current];
}
Token Parser::Previous()
{
return tokens[current - 1];
}