-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cpp
More file actions
391 lines (316 loc) · 8.31 KB
/
Parser.cpp
File metadata and controls
391 lines (316 loc) · 8.31 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
#include "Parser.hpp"
#include "Expr.hpp"
#include "Scope.hpp"
#include "VarDecl.hpp"
#include <string>
#include <locale>
#include <fstream>
namespace Tok {
const std::string Print = "print";
const std::string L_Arrow = "<-";
const std::string R_Arrow = "->";
}
namespace Lbl {
const std::string Str = "STR";
}
void Parser::error(const char* s) {
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%')
++s;
else {
std::cerr << "invalid format string: missing arguments" << std::endl;
break;
}
}
std::cerr << *s++;
}
_errors = true;
}
template <typename T, typename... Args>
void Parser::error(const char* s, const T& value, Args&& ...args) {
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%')
++s;
else {
std::cerr << value;
s += 2;
return error(s, args...); // call even when *s == 0 to detect extra arguments
}
}
std::cerr << *s++;
}
}
void Parser::skipSpaces() {
while (!_loc.eof() && std::isspace(_loc.current())) {
_loc.next();
}
}
bool Parser::accept(char c) {
skipSpaces();
if (!_loc.eof() && c == _loc.current()) {
_loc.next();
return true;
}
return false;
}
bool Parser::accept(const std::string& tok) {
skipSpaces();
_loc.track();
for (u16_t i = 0; i < tok.length(); i++) {
if (tok[i] != _loc.current()) {
_loc.backtrack();
return false;
}
if (_loc.eof()) {
if (i < (tok.length() - 1))
error("Unexpected EOF: Could not detect '%s'", tok);
_loc.backtrack();
return false;
}
_loc.next();
}
return true;
}
bool Parser::expect(char c) {
if (!accept(c)) {
error("Did expected '%c'", c);
return false;
}
return true;
}
bool Parser::expect(const std::string& tok) {
if (!accept(tok)) {
error("Did expected '%s'", tok);
return false;
}
return true;
}
bool Parser::readIdentifier(std::string& ident) {
skipSpaces();
auto isValid = [this](bool first) -> bool {
if (_loc.eof())
return false;
const char c = _loc.current();
if (c == '_')
return true;
if (first)
return std::isalpha(c);
return std::isalnum(c);
};
if (!isValid(true))
return false;
ident.clear();
do {
ident += _loc.current();
_loc.next();
} while (isValid(false));
return ident.length() != 0;
}
bool Parser::readNumber(i32_t& num) {
skipSpaces();
auto isValid = [this]() -> bool {
if (_loc.eof())
return false;
const char c = _loc.current();
return std::isdigit(c);
};
if (!isValid())
return false;
num = 0;
do {
num *= 10;
num += _loc.current() - '0';
_loc.next();
} while (isValid());
return true;
}
Env* Parser::parse(const std::string& filename) {
std::ifstream stream(filename);
if (stream.good()) {
/*
* Get the size of the file
*/
stream.seekg(0, std::ios::end);
const std::streampos len = stream.tellg();
stream.seekg(0, std::ios::beg);
/*
* Read the whole file into the buffer.
*/
std::vector<char> buffer(len);
stream.read(&buffer[0], len);
_loc = Loc(&buffer.front(), &buffer.back());
// Ignore possible header
while (!_loc.eof() && !std::isalnum(_loc.current())) {
_loc.next();
}
while (!_loc.eof() && !_errors) {
parseFunc();
skipSpaces(); // discard any whitespaces until the next function begins
}
if (!_errors)
return &_env;
} else
std::cerr << "Cannot use invalid file handle" << std::endl;
return nullptr;
}
void Parser::parseFunc() {
std::string ident;
if (readIdentifier(ident)) {
expect('(');
// TODO: parameters
expect(')');
parseScope();
_env.addFunc(new Func(ident, _cur_scope));
_cur_scope = nullptr;
} else
error("No function found");
}
void Parser::parseScope() {
expect('{');
_cur_scope = new Scope(_cur_scope);
while (!_errors && !_loc.eof()) {
std::string ident;
if (accept(Tok::Print)) {
parsePrintDecl();
} else if (readIdentifier(ident)) {
const bool isVar = parseVarDecl(ident);
if (!isVar)
error("'%s' is not a valid variable", ident);
} else
break;
}
expect('}');
}
void Parser::parsePrintDecl() {
std::unique_ptr<PrintDecl> pi(new PrintDecl());
while (!_loc.eof()) {
const Expr* exp = parseExpr();
if (exp)
pi->addExpr(exp);
else {
const StringExpr* sexp = parseStringExpr();
if (sexp)
pi->addExpr(sexp);
else {
error("Nothing to print");
return;
}
}
if (!accept(','))
break;
}
_cur_scope->addDecl(pi.release());
}
bool Parser::parseVarDecl(const std::string& ident) {
if (accept('=')) {
Expr* exp = parseExpr();
if (!exp) {
error("Variable '%s' need assignment", ident);
return false;
}
_cur_scope->addVarDecl(ident, new VarDecl(exp));
return true;
} else if (accept(Tok::R_Arrow)) {
error("Currently, no pointers are implemented");
} else if (accept(Tok::L_Arrow)) {
error("Currently, no pointers are implemented");
} else {
error("Unexpected identifier: %s", ident);
}
return false;
}
StringExpr* Parser::parseStringExpr() {
if (accept('"')) {
std::string str;
while (!_loc.eof() && _loc.current() != '\"') {
str += _loc.current();
_loc.next();
}
expect('"');
const std::string label = _env.labels.addStr(str, Lbl::Str);
return new StringExpr(label);
}
return nullptr;
}
Expr* Parser::parseExpr() {
Expr* lhs = parseTerm();
if (!lhs)
return nullptr;
while (!_loc.eof()) {
if (accept('+')) {
Expr* rhs = parseTerm();
if (!rhs) {
error("Expected factor after +");
break;
}
lhs = new AddExpr(lhs, rhs);
} else if (accept('-')) {
Expr* rhs = parseTerm();
if (!rhs) {
error("Expected factor after -");
break;
}
lhs = new SubExpr(rhs, lhs);
} else
break;
}
return lhs;
}
Expr* Parser::parseTerm() {
Expr* lhs = parseFactor();
if (!lhs)
return nullptr;
while (!_loc.eof()) {
if (accept('*')) {
Expr* rhs = parseFactor();
if (!rhs) {
error("Expected factor after *");
break;
}
lhs = new MulExpr(lhs, rhs);
} else if (accept('/')) {
Expr* rhs = parseFactor();
if (!rhs) {
error("Expected factor after /");
break;
}
lhs = new DivExpr(rhs, lhs);
} else if (accept('%')) {
Expr* rhs = parseFactor();
if (!rhs) {
error("Expected factor after %");
break;
}
lhs = new ModExpr(rhs, lhs);
} else
break;
}
return lhs;
}
Expr* Parser::parseFactor() {
const bool negate = accept('-');
i32_t num;
std::string ident;
Expr* expr = nullptr;
if (readNumber(num))
expr = new NumExpr(num);
else if (accept('(')) {
expr = parseExpr();
expect(')');
} else if (readIdentifier(ident)) {
const VarDecl* var = seekingDown(ident, _cur_scope);
if (var)
expr = new VarExpr(var);
else
error("No such variable: '%s'", ident);
}
if (negate) {
if (!expr)
error("Nothing that can be negated");
else
return new NegExpr(expr);
}
return expr;
}