-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tokenizer.cpp
434 lines (356 loc) · 10.4 KB
/
Tokenizer.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
#include "Tokenizer.h"
#include "errors.h"
std::unique_ptr<Tokenizer> Tokenizer::singleton_ = nullptr;
int Tokenizer::GetTok() {
// Skip any whitespace.
while (isspace(LastChar))
LastChar = getchar();
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
IdentifierStr = LastChar;
while (isalnum((LastChar = getchar())))
IdentifierStr += LastChar;
if (IdentifierStr == "def")
return Def;
if (IdentifierStr == "extern")
return Extern;
if (IdentifierStr == "if")
return If;
if (IdentifierStr == "then")
return Then;
if (IdentifierStr == "else")
return Else;
if (IdentifierStr == "for")
return For;
if (IdentifierStr == "in")
return In;
if (IdentifierStr == "var")
return Var;
return Identifier;
}
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
std::string NumStr;
do {
NumStr += LastChar;
LastChar = getchar();
} while (isdigit(LastChar) || LastChar == '.');
NumVal = strtod(NumStr.c_str(), nullptr);
return Number;
}
if (LastChar == '#') {
// Comment until end of line.
do
LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
return GetTok();
}
// Check for end of file. Don't eat the EOF.
if (LastChar == EOF)
return Eof;
// Otherwise, just return the character as its ascii value.
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
std::unique_ptr<Tokenizer> &Tokenizer::GetInstance() {
if (singleton_ == nullptr) {
singleton_ = std::unique_ptr<Tokenizer>(new Tokenizer());
}
return singleton_;
}
/// numberexpr ::= number
std::unique_ptr<ExprAST> Tokenizer::ParseNumberExpr() {
auto Result = std::make_unique<NumberExprAST>(NumVal);
GetNextToken(); // consume the number
return std::move(Result);
}
std::unique_ptr<ExprAST> Tokenizer::ParseParenExpr() {
GetNextToken(); // eat (.
auto V = ParseExpression();
if (!V)
return nullptr;
if (CurTok != ')')
return LogError("expected ')'");
GetNextToken(); // eat ).
return V;
}
/// identifierexpr
/// ::= identifier
/// ::= identifier '(' expression* ')'
std::unique_ptr<ExprAST> Tokenizer::ParseIdentifierExpr() {
std::string IdName = IdentifierStr;
GetNextToken(); // eat identifier.
if (CurTok != '(') // Simple variable ref.
return std::make_unique<VariableExprAST>(IdName);
// Call.
GetNextToken(); // eat (
std::vector<std::unique_ptr<ExprAST>> Args;
if (CurTok != ')') {
while (true) {
if (auto Arg = ParseExpression())
Args.push_back(std::move(Arg));
else
return nullptr;
if (CurTok == ')')
break;
if (CurTok != ',')
return LogError("Expected ')' or ',' in argument list");
GetNextToken();
}
}
// Eat the ')'.
GetNextToken();
return std::make_unique<CallExprAST>(IdName, std::move(Args));
}
std::unique_ptr<ExprAST> Tokenizer::ParsePrimary() {
switch (CurTok) {
case Identifier:
return ParseIdentifierExpr();
case Number:
return ParseNumberExpr();
case '(':
return ParseParenExpr();
case If:
return ParseIfExpr();
case For:
return ParseForExpr();
case Var:
return ParseVarExpr();
default:
return LogError("unknown token when expecting an expression");
}
}
int Tokenizer::GetTokPrecedence() {
if (!isascii(CurTok))
return -1;
// Make sure it's a declared binop.
if (auto search = BinopPrecedence.find(CurTok);
search != BinopPrecedence.end()) {
return search->second;
}
return -1;
}
std::unique_ptr<ExprAST> Tokenizer::ParseExpression() {
auto LHS = ParsePrimary();
if (!LHS)
return nullptr;
return ParseBinOpRHS(0, std::move(LHS));
}
std::unique_ptr<ExprAST>
Tokenizer::ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS) {
// If this is a binop, find its precedence.
while (true) {
int TokPrec = GetTokPrecedence();
// If this is a binop that binds at least as tightly as the current binop,
// consume it, otherwise we are done.
if (TokPrec < ExprPrec)
return LHS;
int BinOp = CurTok;
GetNextToken(); // eat binop
// Parse the primary expression after the binary operator.
auto RHS = ParsePrimary();
if (!RHS)
return nullptr;
// If BinOp binds less tightly with RHS than the operator after RHS, let
// the pending operator take RHS as its LHS.
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
if (!RHS)
return nullptr;
}
// Merge LHS/RHS.
LHS =
std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
} // loop around to the top of the while loop.
}
std::unique_ptr<PrototypeAST> Tokenizer::ParsePrototype() {
if (CurTok != Identifier)
return LogErrorP("Expected function name in prototype");
std::string FnName = IdentifierStr;
GetNextToken();
if (CurTok != '(')
return LogErrorP("Expected '(' in prototype");
// Read the list of argument names.
std::vector<std::string> ArgNames;
while (GetNextToken() == Identifier)
ArgNames.push_back(IdentifierStr);
if (CurTok != ')')
return LogErrorP("Expected ')' in prototype");
// success.
GetNextToken(); // eat ')'.
return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}
std::unique_ptr<FunctionAST> Tokenizer::ParseDefinition() {
GetNextToken(); // eat def.
auto Proto = ParsePrototype();
if (!Proto)
return nullptr;
if (auto E = ParseExpression())
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
return nullptr;
}
std::unique_ptr<PrototypeAST> Tokenizer::ParseExtern() {
GetNextToken(); // eat extern.
return ParsePrototype();
}
std::unique_ptr<FunctionAST> Tokenizer::ParseTopLevelExpr() {
if (auto E = ParseExpression()) {
// Make an anonymous proto.
auto Proto = std::make_unique<PrototypeAST>("__anon_expr",
std::vector<std::string>());
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
}
return nullptr;
}
std::unique_ptr<ExprAST> Tokenizer::ParseIfExpr() {
GetNextToken(); // eat the if.
// condition.
auto Cond = ParseExpression();
if (!Cond)
return nullptr;
if (CurTok != Then)
return LogError("expected then");
GetNextToken(); // eat the then
auto Then = ParseExpression();
if (!Then)
return nullptr;
if (CurTok != Else)
return LogError("expected else");
GetNextToken();
auto Else = ParseExpression();
if (!Else)
return nullptr;
return std::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
std::move(Else));
}
/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
std::unique_ptr<ExprAST> Tokenizer::ParseForExpr() {
GetNextToken(); // eat the for.
if (CurTok != Identifier)
return LogError("expected identifier after for");
std::string IdName = IdentifierStr;
GetNextToken(); // eat identifier.
if (CurTok != '=')
return LogError("expected '=' after for");
GetNextToken(); // eat '='.
auto Start = ParseExpression();
if (!Start)
return nullptr;
if (CurTok != ',')
return LogError("expected ',' after for start value");
GetNextToken();
auto End = ParseExpression();
if (!End)
return nullptr;
// The step value is optional.
std::unique_ptr<ExprAST> Step;
if (CurTok == ',') {
GetNextToken();
Step = ParseExpression();
if (!Step)
return nullptr;
}
if (CurTok != In)
return LogError("expected 'in' after for");
GetNextToken(); // eat 'in'.
auto Body = ParseExpression();
if (!Body)
return nullptr;
return std::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
std::move(Step), std::move(Body));
}
std::unique_ptr<ExprAST> Tokenizer::ParseVarExpr() {
GetNextToken(); // eat the var.
std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
// At least one variable name is required.
if (CurTok != Identifier)
return LogError("expected identifier after var");
while (true) {
std::string Name = IdentifierStr;
GetNextToken(); // eat identifier.
// Read the optional initializer.
std::unique_ptr<ExprAST> Init;
if (CurTok == '=') {
GetNextToken(); // eat the '='.
Init = ParseExpression();
if (!Init)
return nullptr;
}
VarNames.emplace_back(Name, std::move(Init));
// End of var list, exit loop.
if (CurTok != ',')
break;
GetNextToken(); // eat the ','.
if (CurTok != Identifier)
return LogError("expected identifier list after var");
}
// At this point, we have to have 'in'.
if (CurTok != In)
return LogError("expected 'in' keyword after 'var'");
GetNextToken(); // eat 'in'.
auto Body = ParseExpression();
if (!Body)
return nullptr;
return std::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
}
void Tokenizer::HandleDefinition() {
if (auto FnAST = ParseDefinition()) {
if (auto *FnIR = FnAST->codegen()) {
fprintf(stderr, "Read function definition:\n");
FnIR->print(llvm::errs());
fprintf(stderr, "\n");
}
} else {
// Skip token for error recovery.
GetNextToken();
}
}
void Tokenizer::HandleExtern() {
if (auto ProtoAST = ParseExtern()) {
if (auto *FnIR = ProtoAST->codegen()) {
fprintf(stderr, "Read extern: ");
FnIR->print(llvm::errs());
fprintf(stderr, "\n");
}
} else {
// Skip token for error recovery.
GetNextToken();
}
}
void Tokenizer::HandleTopLevelExpression() {
// Evaluate a top-level expression into an anonymous function.
if (auto FnAST = ParseTopLevelExpr()) {
if (auto *FnIR = FnAST->codegen()) {
fprintf(stderr, "Read top-level expression:\n");
FnIR->print(llvm::errs());
fprintf(stderr, "\n");
// Remove the anonymous expression.
FnIR->eraseFromParent();
}
} else {
// Skip token for error recovery.
GetNextToken();
}
}
void Tokenizer::MainLoop() {
while (true) {
fprintf(stderr, "ready> ");
switch (CurTok) {
case Eof:
return;
case ';': // ignore top-level semicolons.
GetNextToken();
break;
case Def:
HandleDefinition();
break;
case Extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}