-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cpp
More file actions
373 lines (337 loc) · 17.1 KB
/
Parser.cpp
File metadata and controls
373 lines (337 loc) · 17.1 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
#include "Parser.h"
#include <iostream>
#include <vector>
extern bool hadError;
Parser::Parser(const std::vector<Token>& tokens) : tokens(tokens) {}
std::vector<std::unique_ptr<Stmt>> Parser::parse() {
std::vector<std::unique_ptr<Stmt>> statements;
while (!isAtEnd()) {
try {
statements.push_back(declaration());
} catch (const ParseError& e) {
std::cerr << "[Line " << peek().line << "] " << e.what() << std::endl;
hadError = true;
synchronize();
}
}
return statements;
}
bool Parser::isAtEnd() { return peek().type == TokenType::TOKEN_EOF; }
Token Parser::peek() { return tokens[current]; }
Token Parser::peekNext() { if (current + 1 >= tokens.size()) return tokens.back(); return tokens[current + 1]; }
Token Parser::previous() { return tokens[current - 1]; }
Token Parser::advance() { if (!isAtEnd()) current++; return previous(); }
bool Parser::check(TokenType type) { if (isAtEnd()) return false; return peek().type == type; }
bool Parser::checkNext(TokenType type) { if (isAtEnd() || current + 1 >= tokens.size()) return false; return tokens[current + 1].type == type; }
bool Parser::match(const std::vector<TokenType>& types) {
for (TokenType type : types) { if (check(type)) { advance(); return true; } }
return false;
}
Token Parser::consume(TokenType type, const std::string& message) {
if (check(type)) return advance();
throw error(peek(), message);
}
std::unique_ptr<Stmt> Parser::includeDeclaration() {
Token path = consume(TokenType::STRING, "Expect field path (string) after #SetField.");
if (check(TokenType::SEMICOLON)) advance();
return std::make_unique<IncludeStmt>(path);
}
std::unique_ptr<Stmt> Parser::declaration() {
try {
if (match({TokenType::KEYWORD_LORDOFD})) return classDeclaration();
if (match({TokenType::KEYWORD_TOONWORLD})) return structDeclaration();
if (match({TokenType::KEYWORD_RITUAL})) return ritualDeclaration("function");
if (check(TokenType::KEYWORD_YUGI) && checkNext(TokenType::LEFT_PAREN)) {
advance();
return ritualDeclaration("function");
}
if (check(TokenType::KEYWORD_DARKMAGICIAN) || check(TokenType::KEYWORD_BLUEEYESWHITEDRAGON) ||
check(TokenType::KEYWORD_REDEYESBLACKDRAGON) || check(TokenType::KEYWORD_TIMEWIZARD) ||
(check(TokenType::IDENTIFIER) && checkNext(TokenType::IDENTIFIER))) {
if (previous().type != TokenType::KEYWORD_YUGI) {
match({TokenType::KEYWORD_DARKMAGICIAN, TokenType::KEYWORD_BLUEEYESWHITEDRAGON, TokenType::KEYWORD_REDEYESBLACKDRAGON, TokenType::KEYWORD_TIMEWIZARD, TokenType::IDENTIFIER});
}
return varDeclaration();
}
if (match({TokenType::KEYWORD_SETFIELD})) {
return includeDeclaration();
}
if (match({TokenType::KEYWORD_KAIBA})) {
Token name = consume(TokenType::KEYWORD_JOEY, "Expect 'Joey' (std) after 'Kaiba' (using).");
consume(TokenType::SEMICOLON, "Expect ';' after 'using' statement.");
return std::make_unique<UsingStmt>(previous(), name);
}
return statement();
} catch (ParseError& e) {
synchronize(); hadError = true; std::cerr << "[Line " << peek().line << "] " << e.what() << std::endl; return nullptr;
}
}
std::unique_ptr<Stmt> Parser::statement() {
if (match({TokenType::KEYWORD_SUMMON})) return summonStatement();
if (match({TokenType::KEYWORD_DRAW})) return drawStatement();
if (match({TokenType::KEYWORD_JUDGMENTOFANUBIS})) return ifStatement();
if (match({TokenType::KEYWORD_FAIRYBOX})) return whileStatement();
if (match({TokenType::KEYWORD_SWORDSOFREVEALINGLIGHT})) return forStatement();
if (match({TokenType::KEYWORD_TRIBUTE})) return returnStatement();
if (match({TokenType::LEFT_BRACE})) {
return std::make_unique<BlockStmt>(std::move(block()->statements));
}
return expressionStatement();
}
std::unique_ptr<Stmt> Parser::drawStatement() {
consume(TokenType::DRAW_OP, "Expect '>>' after 'Draw'.");
Token name = consume(TokenType::IDENTIFIER, "Expect variable name after '>>'.");
consume(TokenType::SEMICOLON, "Expect ';' after 'Draw' statement.");
return std::make_unique<DrawStmt>(name);
}
std::unique_ptr<Stmt> Parser::ifStatement() {
consume(TokenType::LEFT_PAREN, "Expect '(' after 'JudgmentOfAnubis'.");
std::unique_ptr<Expr> condition = expression();
consume(TokenType::RIGHT_PAREN, "Expect ')' after if condition.");
std::unique_ptr<Stmt> thenBranch = statement();
std::unique_ptr<Stmt> elseBranch = nullptr;
if (match({TokenType::KEYWORD_SOLEMNJUDGMENT})) elseBranch = statement();
return std::make_unique<IfStmt>(std::move(condition), std::move(thenBranch), std::move(elseBranch));
}
std::unique_ptr<Stmt> Parser::whileStatement() {
consume(TokenType::LEFT_PAREN, "Expect '(' after 'FairyBox'.");
std::unique_ptr<Expr> condition = expression();
consume(TokenType::RIGHT_PAREN, "Expect ')' after condition.");
std::unique_ptr<Stmt> body = statement();
return std::make_unique<WhileStmt>(std::move(condition), std::move(body));
}
std::unique_ptr<Stmt> Parser::forStatement() {
consume(TokenType::LEFT_PAREN, "Expect '(' after 'SwordsOfRevealingLight'.");
std::unique_ptr<Stmt> initializer;
if (match({TokenType::SEMICOLON})) {
initializer = nullptr;
}
else if (check(TokenType::KEYWORD_DARKMAGICIAN) ||
check(TokenType::KEYWORD_BLUEEYESWHITEDRAGON) ||
check(TokenType::KEYWORD_REDEYESBLACKDRAGON) ||
check(TokenType::KEYWORD_TIMEWIZARD) ||
check(TokenType::IDENTIFIER))
{
if (checkNext(TokenType::IDENTIFIER)) {
advance(); // Consume the type
initializer = varDeclaration();
} else {
initializer = expressionStatement();
}
} else {
initializer = expressionStatement();
}
std::unique_ptr<Expr> condition = nullptr;
if (!check(TokenType::SEMICOLON)) condition = expression();
consume(TokenType::SEMICOLON, "Expect ';' after loop condition.");
std::unique_ptr<Expr> increment = nullptr;
if (!check(TokenType::RIGHT_PAREN)) increment = expression();
consume(TokenType::RIGHT_PAREN, "Expect ')' after for clauses.");
std::unique_ptr<Stmt> body = statement();
if (increment != nullptr) {
std::vector<std::unique_ptr<Stmt>> statements;
statements.push_back(std::move(body));
statements.push_back(std::make_unique<ExpressionStmt>(std::move(increment)));
body = std::make_unique<BlockStmt>(std::move(statements));
}
if (condition == nullptr) condition = std::make_unique<LiteralExpr>(true);
body = std::make_unique<WhileStmt>(std::move(condition), std::move(body));
if (initializer != nullptr) {
std::vector<std::unique_ptr<Stmt>> statements;
statements.push_back(std::move(initializer));
statements.push_back(std::move(body));
body = std::make_unique<BlockStmt>(std::move(statements));
}
return body;
}
std::unique_ptr<Stmt> Parser::returnStatement() {
Token keyword = previous();
std::unique_ptr<Expr> value = nullptr;
if (!check(TokenType::SEMICOLON)) value = expression();
consume(TokenType::SEMICOLON, "Expect ';' after 'Tribute' (return) value.");
return std::make_unique<ReturnStmt>(keyword, std::move(value));
}
std::unique_ptr<Stmt> Parser::summonStatement() {
consume(TokenType::SUMMON_OP, "Expect '<<' after 'Summon'.");
std::unique_ptr<Expr> value = expression();
while (match({TokenType::SUMMON_OP})) {
Token op = previous();
std::unique_ptr<Expr> right = expression();
value = std::make_unique<BinaryExpr>(std::move(value), op, std::move(right));
}
consume(TokenType::SEMICOLON, "Expect ';' after 'Summon' statement.");
return std::make_unique<SummonStmt>(std::move(value));
}
std::unique_ptr<Stmt> Parser::varDeclaration() {
Token type = previous();
Token name = consume(TokenType::IDENTIFIER, "Expect variable name.");
std::unique_ptr<Expr> initializer = nullptr;
if (match({TokenType::EQUAL})) initializer = expression();
consume(TokenType::SEMICOLON, "Expect ';' after variable declaration.");
return std::make_unique<VarDeclStmt>(type, name, std::move(initializer));
}
std::unique_ptr<Stmt> Parser::classDeclaration() {
Token name = consume(TokenType::IDENTIFIER, "Expect class name.");
consume(TokenType::LEFT_BRACE, "Expect '{' before class body.");
std::vector<std::unique_ptr<VarDeclStmt>> fields;
std::vector<std::unique_ptr<FunctionStmt>> methods;
while (!check(TokenType::RIGHT_BRACE) && !isAtEnd()) {
if (match({TokenType::KEYWORD_RITUAL})) methods.push_back(std::unique_ptr<FunctionStmt>(static_cast<FunctionStmt*>(ritualDeclaration("method").release())));
else if (match({TokenType::KEYWORD_DARKMAGICIAN, TokenType::KEYWORD_BLUEEYESWHITEDRAGON, TokenType::KEYWORD_REDEYESBLACKDRAGON, TokenType::KEYWORD_TIMEWIZARD, TokenType::IDENTIFIER})) fields.push_back(std::unique_ptr<VarDeclStmt>(static_cast<VarDeclStmt*>(varDeclaration().release())));
else {
if (peek().type == TokenType::SEMICOLON) advance();
else throw error(peek(), "Expect field or method declaration inside class.");
}
}
consume(TokenType::RIGHT_BRACE, "Expect '}' after class body.");
consume(TokenType::SEMICOLON, "Expect ';' after class declaration.");
return std::make_unique<ClassStmt>(name, std::move(fields), std::move(methods));
}
std::unique_ptr<Stmt> Parser::structDeclaration() {
Token name = consume(TokenType::IDENTIFIER, "Expect struct name.");
consume(TokenType::LEFT_BRACE, "Expect '{' before struct body.");
std::vector<std::unique_ptr<VarDeclStmt>> fields;
while (!check(TokenType::RIGHT_BRACE) && !isAtEnd()) {
if (match({TokenType::KEYWORD_DARKMAGICIAN, TokenType::KEYWORD_BLUEEYESWHITEDRAGON, TokenType::KEYWORD_REDEYESBLACKDRAGON, TokenType::KEYWORD_TIMEWIZARD, TokenType::IDENTIFIER})) fields.push_back(std::unique_ptr<VarDeclStmt>(static_cast<VarDeclStmt*>(varDeclaration().release())));
else throw error(peek(), "Expect field declaration inside struct.");
}
consume(TokenType::RIGHT_BRACE, "Expect '}' after struct body.");
consume(TokenType::SEMICOLON, "Expect ';' after struct declaration.");
return std::make_unique<StructStmt>(name, std::move(fields));
}
std::unique_ptr<Stmt> Parser::ritualDeclaration(std::string kind) {
Token name;
if (check(TokenType::KEYWORD_YUGI)) { name = advance(); }
else if (match({TokenType::KEYWORD_YUGI})) { name = previous(); }
else { name = consume(TokenType::IDENTIFIER, "Expect " + kind + " name."); }
consume(TokenType::LEFT_PAREN, "Expect '(' after " + kind + " name.");
std::vector<FunctionParameter> params = parseParameters();
consume(TokenType::RIGHT_PAREN, "Expect ')' after parameters.");
consume(TokenType::LEFT_BRACE, "Expect '{' before " + kind + " body.");
std::unique_ptr<BlockStmt> body = block();
return std::make_unique<FunctionStmt>(name, std::move(params), std::move(body));
}
std::vector<FunctionParameter> Parser::parseParameters() {
std::vector<FunctionParameter> params;
if (!check(TokenType::RIGHT_PAREN)) {
do {
if (params.size() >= 255) error(peek(), "Can't have more than 255 parameters.");
Token type;
if (match({TokenType::KEYWORD_DARKMAGICIAN, TokenType::KEYWORD_BLUEEYESWHITEDRAGON, TokenType::KEYWORD_REDEYESBLACKDRAGON, TokenType::KEYWORD_TIMEWIZARD, TokenType::IDENTIFIER})) type = previous(); else throw error(peek(), "Expect parameter type.");
Token name = consume(TokenType::IDENTIFIER, "Expect parameter name.");
params.push_back({type, name});
} while (match({TokenType::COMMA}));
}
return params;
}
std::unique_ptr<BlockStmt> Parser::block() {
std::vector<std::unique_ptr<Stmt>> statements;
while (!check(TokenType::RIGHT_BRACE) && !isAtEnd()) statements.push_back(declaration());
consume(TokenType::RIGHT_BRACE, "Expect '}' after block.");
return std::make_unique<BlockStmt>(std::move(statements));
}
std::unique_ptr<Stmt> Parser::expressionStatement() {
std::unique_ptr<Expr> expr = expression();
consume(TokenType::SEMICOLON, "Expect ';' after expression.");
return std::make_unique<ExpressionStmt>(std::move(expr));
}
std::unique_ptr<Expr> Parser::expression() { return assignment(); }
std::unique_ptr<Expr> Parser::assignment() {
std::unique_ptr<Expr> expr = logic_or();
if (match({TokenType::EQUAL})) {
Token equals = previous();
std::unique_ptr<Expr> value = assignment();
if (VariableExpr* varExpr = dynamic_cast<VariableExpr*>(expr.get())) return std::make_unique<AssignExpr>(varExpr->name, std::move(value));
else if (GetExpr* getExpr = dynamic_cast<GetExpr*>(expr.get())) return std::make_unique<SetExpr>(std::move(getExpr->object), getExpr->name, std::move(value));
throw error(equals, "Invalid assignment target.");
}
return expr;
}
std::unique_ptr<Expr> Parser::logic_or() { return logic_and(); }
std::unique_ptr<Expr> Parser::logic_and() { return equality(); }
std::unique_ptr<Expr> Parser::equality() {
std::unique_ptr<Expr> expr = comparison();
while (match({TokenType::BANG_EQUAL, TokenType::EQUAL_EQUAL})) {
Token op = previous(); std::unique_ptr<Expr> right = comparison(); expr = std::make_unique<BinaryExpr>(std::move(expr), op, std::move(right));
}
return expr;
}
std::unique_ptr<Expr> Parser::comparison() {
std::unique_ptr<Expr> expr = term();
while (match({TokenType::GREATER, TokenType::GREATER_EQUAL, TokenType::LESS, TokenType::LESS_EQUAL})) {
Token op = previous(); std::unique_ptr<Expr> right = term(); expr = std::make_unique<BinaryExpr>(std::move(expr), op, std::move(right));
}
return expr;
}
std::unique_ptr<Expr> Parser::term() {
std::unique_ptr<Expr> expr = factor();
while (match({TokenType::MINUS, TokenType::PLUS})) {
Token op = previous(); std::unique_ptr<Expr> right = factor(); expr = std::make_unique<BinaryExpr>(std::move(expr), op, std::move(right));
}
return expr;
}
std::unique_ptr<Expr> Parser::factor() {
std::unique_ptr<Expr> expr = unary();
while (match({TokenType::SLASH, TokenType::STAR})) {
Token op = previous(); std::unique_ptr<Expr> right = unary(); expr = std::make_unique<BinaryExpr>(std::move(expr), op, std::move(right));
}
return expr;
}
std::unique_ptr<Expr> Parser::unary() {
if (match({TokenType::BANG, TokenType::MINUS})) {
Token op = previous(); std::unique_ptr<Expr> right = unary(); return std::make_unique<UnaryExpr>(op, std::move(right));
}
return call();
}
std::unique_ptr<Expr> Parser::call() {
std::unique_ptr<Expr> expr = primary();
while (true) {
if (match({TokenType::LEFT_PAREN})) expr = finishCall(std::move(expr));
else if (match({TokenType::DOT})) {
Token name = consume(TokenType::IDENTIFIER, "Expect property name after '.'.");
expr = std::make_unique<GetExpr>(std::move(expr), name);
} else break;
}
return expr;
}
std::unique_ptr<Expr> Parser::finishCall(std::unique_ptr<Expr> callee) {
std::vector<std::unique_ptr<Expr>> arguments;
if (!check(TokenType::RIGHT_PAREN)) {
do {
if (arguments.size() >= 255) error(peek(), "Can't have more than 255 arguments.");
arguments.push_back(expression());
} while (match({TokenType::COMMA}));
}
Token paren = consume(TokenType::RIGHT_PAREN, "Expect ')' after arguments.");
return std::make_unique<CallExpr>(std::move(callee), paren, std::move(arguments));
}
std::unique_ptr<Expr> Parser::primary() {
if (match({TokenType::KEYWORD_FALSE})) return std::make_unique<LiteralExpr>(false);
if (match({TokenType::KEYWORD_TRUE})) return std::make_unique<LiteralExpr>(true);
if (match({TokenType::NUMBER})) return std::make_unique<LiteralExpr>(std::stod(previous().lexeme));
if (match({TokenType::STRING})) return std::make_unique<LiteralExpr>(previous().lexeme);
if (match({TokenType::IDENTIFIER})) return std::make_unique<VariableExpr>(previous());
if (match({TokenType::LEFT_PAREN})) {
std::unique_ptr<Expr> expr = expression();
consume(TokenType::RIGHT_PAREN, "Expect ')' after expression.");
return std::make_unique<GroupingExpr>(std::move(expr));
}
throw error(peek(), "Expect expression.");
}
Parser::ParseError Parser::error(Token token, const std::string& message) {
hadError = true;
return ParseError("Error at '" + token.lexeme + "': " + message);
}
void Parser::synchronize() {
advance();
while (!isAtEnd()) {
if (previous().type == TokenType::SEMICOLON) return;
switch (peek().type) {
case TokenType::KEYWORD_RITUAL: case TokenType::KEYWORD_LORDOFD: case TokenType::KEYWORD_TOONWORLD:
case TokenType::KEYWORD_JUDGMENTOFANUBIS: case TokenType::KEYWORD_FAIRYBOX: case TokenType::KEYWORD_TRIBUTE:
case TokenType::KEYWORD_SETFIELD: case TokenType::KEYWORD_KAIBA: case TokenType::KEYWORD_SUMMON: case TokenType::KEYWORD_DRAW:
return;
}
advance();
}
}