-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cpp
More file actions
296 lines (247 loc) · 9.3 KB
/
Copy pathParser.cpp
File metadata and controls
296 lines (247 loc) · 9.3 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
// ============================================================
// SYNTAX ANALYSIS – Parser.cpp
// ============================================================
// Purpose: SYNTAX ANALYSIS – recursive descent parser.
// Each grammar rule becomes a parseXxx() method.
// The parser builds an AST as it recognises structure.
// ============================================================
#include "Parser.h"
#include <sstream>
// Constructor: take ownership of the token list, start at index 0
Parser::Parser(std::vector<Token> tokens)
: tokens_(std::move(tokens)), pos_(0) {}
// Token stream helpers
// CURRENT() – token at the read cursor
Token& Parser::current() {
return tokens_[pos_];
}
// PEEK() – look ahead without consuming (default 1 step ahead)
Token& Parser::peek(int offset) {
int idx = pos_ + offset;
if (idx >= (int)tokens_.size()) return tokens_.back(); // EOF token
return tokens_[idx];
}
// CONSUME() – return current token and advance the cursor
Token Parser::consume() {
Token t = tokens_[pos_];
if (pos_ < (int)tokens_.size() - 1) pos_++;
return t;
}
// EXCEPT() – consume a token that MUST be of type t; error otherwise
Token Parser::expect(TokenType t) {
if (current().type != t) {
throw error("Expected '" + Token::typeName(t) +
"' but got '" + current().lexeme + "'");
}
return consume();
}
bool Parser::check(TokenType t) const {
return tokens_[pos_].type == t;
}
bool Parser::match(TokenType t) {
if (check(t)) { consume(); return true; }
return false;
}
bool Parser::isAtEnd() const {
return tokens_[pos_].type == TokenType::END_OF_FILE;
}
// ERROR() – build a runtime_error with line information
std::runtime_error Parser::error(const std::string& msg) {
return std::runtime_error("Parse error at line " +
std::to_string(current().line) +
": " + msg);
}
// PARSE() – entry point
std::vector<ASTNodePtr> Parser::parse() {
std::vector<ASTNodePtr> stmts;
while (!isAtEnd()) {
stmts.push_back(parseStatement()); // Parse one statement at a time
}
return stmts;
}
// PARSESTATEMENT() – dispatch by current token
ASTNodePtr Parser::parseStatement() {
// Variable declaration starts with 'int' or 'float'
if (check(TokenType::INT) || check(TokenType::FLOAT))
return parseVarDecl();
// if statement
if (check(TokenType::IF))
return parseIfStatement();
// while loop
if (check(TokenType::WHILE))
return parseWhileStatement();
// print built-in
if (check(TokenType::PRINT))
return parsePrintStatement();
// return statement
if (check(TokenType::RETURN))
return parseReturnStatement();
// Block of statements { ... }
if (check(TokenType::LBRACE)) {
consume(); // eat '{'
auto stmts = parseBlock();
auto block = std::make_unique<BlockNode>();
block->statements = std::move(stmts);
return block;
}
// Otherwise must be an assignment: ident = expr;
return parseAssignment();
}
// PARSEVARDECL() – int x = expr; or float y = expr;
ASTNodePtr Parser::parseVarDecl() {
// Consume the type keyword
Token typeToken = consume(); // "int" or "float"
Token nameToken = expect(TokenType::IDENTIFIER); // variable name
ASTNodePtr init = nullptr;
if (match(TokenType::EQUAL)) {
init = parseExpression(); // Optional initialiser
}
expect(TokenType::SEMICOLON); // Mandatory terminator
return std::make_unique<VarDeclNode>(typeToken.lexeme,
nameToken.lexeme,
std::move(init));
}
// PARSEASSIGNMENT() – ident = expr;
ASTNodePtr Parser::parseAssignment() {
Token nameToken = expect(TokenType::IDENTIFIER); // Left-hand side
expect(TokenType::EQUAL); // '='
ASTNodePtr expr = parseExpression(); // Right-hand side
expect(TokenType::SEMICOLON);
return std::make_unique<AssignNode>(nameToken.lexeme, std::move(expr));
}
// PARSEIFSTATEMENT() – if (cond) { } [else { }]
ASTNodePtr Parser::parseIfStatement() {
consume(); // eat 'if'
expect(TokenType::LPAREN); // '('
ASTNodePtr cond = parseExpression();
expect(TokenType::RPAREN); // ')'
expect(TokenType::LBRACE); // '{'
auto thenBranch = parseBlock(); // then-body
auto node = std::make_unique<IfNode>();
node->condition = std::move(cond);
node->thenBranch = std::move(thenBranch);
if (match(TokenType::ELSE)) { // optional else branch
expect(TokenType::LBRACE);
node->elseBranch = parseBlock();
}
return node;
}
// PARSEWHILESTATEMENT() – while (cond) { body }
ASTNodePtr Parser::parseWhileStatement() {
consume(); // eat 'while'
expect(TokenType::LPAREN);
ASTNodePtr cond = parseExpression();
expect(TokenType::RPAREN);
expect(TokenType::LBRACE);
auto body = parseBlock();
auto node = std::make_unique<WhileNode>();
node->condition = std::move(cond);
node->body = std::move(body);
return node;
}
// PARSEPRINTSTATEMENT() – print(expr);
ASTNodePtr Parser::parsePrintStatement() {
consume(); // eat 'print'
expect(TokenType::LPAREN);
ASTNodePtr expr = parseExpression();
expect(TokenType::RPAREN);
expect(TokenType::SEMICOLON);
return std::make_unique<PrintNode>(std::move(expr));
}
// PARSERETURNSTATEMENT() – return expr;
ASTNodePtr Parser::parseReturnStatement() {
consume(); // eat 'return'
ASTNodePtr expr = nullptr;
if (!check(TokenType::SEMICOLON))
expr = parseExpression();
expect(TokenType::SEMICOLON);
return std::make_unique<ReturnNode>(std::move(expr));
}
// PARSEBLOCK() – { stmt* }
std::vector<ASTNodePtr> Parser::parseBlock() {
std::vector<ASTNodePtr> stmts;
while (!check(TokenType::RBRACE) && !isAtEnd())
stmts.push_back(parseStatement());
expect(TokenType::RBRACE); // Consume closing '}'
return stmts;
}
// EXPRESSION PARSING – recursive descent with operator precedence
// PARSEEXPRESSION() – lowest precedence entry point
ASTNodePtr Parser::parseExpression() {
return parseEquality();
}
// PARSEEQUALITY() – handles == and !=
ASTNodePtr Parser::parseEquality() {
ASTNodePtr left = parseComparison();
while (check(TokenType::EQ_EQ) || check(TokenType::NOT_EQ)) {
Token op = consume(); // eat == or !=
ASTNodePtr right = parseComparison();
left = std::make_unique<BinaryOpNode>(op.lexeme,
std::move(left),
std::move(right));
}
return left;
}
// PARSECOMPARISON() – handles <, >, <=, >=
ASTNodePtr Parser::parseComparison() {
ASTNodePtr left = parseTerm();
while (check(TokenType::LESS) || check(TokenType::GREATER) ||
check(TokenType::LESS_EQ) || check(TokenType::GREATER_EQ)) {
Token op = consume();
ASTNodePtr right = parseTerm();
left = std::make_unique<BinaryOpNode>(op.lexeme,
std::move(left),
std::move(right));
}
return left;
}
// PARSETERM() – handles + and -
ASTNodePtr Parser::parseTerm() {
ASTNodePtr left = parseFactor();
while (check(TokenType::PLUS) || check(TokenType::MINUS)) {
Token op = consume();
ASTNodePtr right = parseFactor();
left = std::make_unique<BinaryOpNode>(op.lexeme,
std::move(left),
std::move(right));
}
return left;
}
// PARSEFACTOR() – handles * and /
ASTNodePtr Parser::parseFactor() {
ASTNodePtr left = parsePrimary();
while (check(TokenType::STAR) || check(TokenType::SLASH)) {
Token op = consume();
ASTNodePtr right = parsePrimary();
left = std::make_unique<BinaryOpNode>(op.lexeme,
std::move(left),
std::move(right));
}
return left;
}
// PARSEPRIMARY() – handles literals, identifiers, and grouped expressions
ASTNodePtr Parser::parsePrimary() {
if (check(TokenType::NUMBER)) {
Token t = consume();
return std::make_unique<NumberNode>(std::stod(t.lexeme));
}
if (check(TokenType::STRING_LIT)) {
Token t = consume();
return std::make_unique<StringNode>(t.lexeme);
}
if (check(TokenType::IDENTIFIER)) {
Token t = consume();
return std::make_unique<IdentifierNode>(t.lexeme);
}
if (match(TokenType::LPAREN)) {
ASTNodePtr expr = parseExpression(); // Grouped expression
expect(TokenType::RPAREN);
return expr;
}
throw error("Unexpected token '" + current().lexeme + "'");
}
// example :
// The rest of the parseXxx() methods (parseVarDecl, parseIfStatement, etc.) are defined above.
// "int x = 45;"
// [INT,"int",1] [IDENTIFIER,"x",1] [EQUAL,"=",1] [NUMBER,"45",1] [SEMICOLON,";",1] [EOF,"",1]
// The parser will consume these tokens and build an AST representing the variable declaration of 'x' with an initial value of 45.