-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrontend.cc
428 lines (354 loc) · 9.76 KB
/
frontend.cc
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
#include <string>
#include <iostream>
#include <vector>
#include <memory>
//"unknown tokens" are represented by their ascii code
enum Token { //why negative? bc ascii values are al positive
tok_eof = -1, //end of file
tok_def = -2, //func def
tok_extern = -3, //extern
tok_identifier = -4, //identifier
tok_number = -5 //num
};
static std::string IdentifierStr; //Fill in if tok_identifier
static double NumVal; //Fill in if tok_number
static int gettok(){
static int LastChar = ' '; //why int? ascii value
while (isspace(LastChar)){ //skip spaces
LastChar = getchar();
}
//parser identifier
if (isalpha(LastChar)){//identifier: [a-zA-Z][a-zA-Z0-9]*
IdentifierStr = LastChar;
while(isalnum(LastChar=getchar())){//get the complete token
IdentifierStr += LastChar;
}
if (IdentifierStr == "def"){
return tok_def;
}
if (IdentifierStr == "extern"){
return tok_extern;
}
return tok_identifier;
}
//parse num
if (isdigit(LastChar) || LastChar == '.'){
std::string NumStr;
do{
NumStr += LastChar;
LastChar = getchar();
}while (isdigit(LastChar) || LastChar == '.');
NumVal = strtod(NumStr.c_str(),0); //no err handling for 1.2.34
return tok_number;
}
//parsr comments
if (LastChar == '#'){
do{
LastChar = getchar();
}while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
}
//parse EOF
if (LastChar == EOF){
return tok_eof;
}
//Otherwise, just return the character as its ascii value
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
/*
int main(){
while(true){
int tok = gettok();
std::cout << "got token: " << tok << std::endl;
}
}
*/
class ExprAST{
public:
virtual ~ExprAST() {}
};
class NumberExprAST : public ExprAST{
double Val;
public:
NumberExprAST(double Val) : Val(Val){}
};
class VariableExprAST : public ExprAST {
std::string Name;
public:
VariableExprAST(const std::string &Name) : Name(Name) {}
};
class BinaryExprAST : public ExprAST {
char Op;
std::unique_ptr<ExprAST> LHS, RHS;
public:
BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
std::unique_ptr<ExprAST> RHS)
: Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
};
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<std::unique_ptr<ExprAST>> Args;
public:
CallExprAST(const std::string &Callee,
std::vector<std::unique_ptr<ExprAST>> Args)
: Callee(Callee), Args(std::move(Args)) {}
};
/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
class PrototypeAST {
std::string Name;
std::vector<std::string> Args;
public:
PrototypeAST(const std::string &Name, std::vector<std::string> Args)
: Name(Name), Args(std::move(Args)) {}
const std::string &getName() const { return Name; }
};
/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
std::unique_ptr<PrototypeAST> Proto;
std::unique_ptr<ExprAST> Body;
public:
FunctionAST(std::unique_ptr<PrototypeAST> Proto,
std::unique_ptr<ExprAST> Body)
: Proto(std::move(Proto)), Body(std::move(Body)) {}
};
static int CurTok;
static int getNextToken() {
return CurTok = gettok();
}
/// LogError* - These are little helper functions for error handling.
std::unique_ptr<ExprAST> LogError(const char *Str) {
fprintf(stderr, "Error: %s\n", Str);
return nullptr; // return nullptr to align with the return type of parserer functions
}
std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
LogError(Str);
return nullptr;
}
/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
auto Result = std::make_unique<NumberExprAST>(NumVal);
getNextToken(); // consume the number
return std::move(Result);
}
static std::unique_ptr<ExprAST> ParseExpression();
/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr(){
getNextToken(); //eat (.
auto V = ParseExpression();
if (!V){
return nullptr;
}
if (CurTok != ')'){
return LogError("expected ')'");
getNextToken(); //eat ).
}
}
/// identifierexpr
/// ::= identifier
/// ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
std::string IdName = IdentifierStr;
getNextToken(); // eat identifier
if (CurTok != '('){
return std::make_unique<VariableExprAST>(IdName);
}
//func call
getNextToken();
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();
}
}
getNextToken(); // eat ')'
return std::make_unique<CallExprAST>(IdName, std::move(Args));
}
/// primary
/// ::= identifierexpr
/// ::= numberexpr
/// ::= parenexpr
static std::unique_ptr<ExprAST> ParsePrimary() {
switch (CurTok) {
default:
return LogError("unknown token when expecting an expression");
case tok_identifier:
return ParseIdentifierExpr();
case tok_number:
return ParseNumberExpr();
case '(':
return ParseParenExpr();
}
}
static int GetTokPrecedence(){
switch (CurTok) {
case '<':
case '>':
return 10;
case '+':
case '-':
return 20;
case '*':
case '/':
return 40;
default:
return -1;
}
}
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS);
/// expression
/// ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
auto LHS = ParsePrimary();
if (!LHS){
return nullptr;
}
return ParseBinOpRHS(0, std::move(LHS));
}
/// binoprhs
/// ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS){
while (true) {
int TokPrec = GetTokPrecedence();
if (TokPrec < ExprPrec){
return LHS;
}
//we know this is a binop
int BinOp = CurTok;
getNextToken();
//parse the primary expression after binary operator
auto RHS = ParsePrimary();
if (!RHS){
return nullptr;
}
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
RHS = ParseBinOpRHS(NextPrec+1, std::move(RHS));
if (!RHS){
return nullptr;
}
}
LHS = std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
}
}
/// prototype
/// ::= id '(' id* ')'
static std::unique_ptr<PrototypeAST> ParsePrototype(){
if (CurTok != tok_identifier){
return LogErrorP("Expected function name in prototype");
}
std::string FnName = IdentifierStr;
getNextToken();
if (CurTok != '('){
return LogErrorP("Expected '(' in prototype");
}
// Read list of argument names
std::vector<std::string> ArgNames;
while (getNextToken() == tok_identifier){
ArgNames.push_back(IdentifierStr);
}
if (CurTok != ')'){
return LogErrorP("Expected ')' in prototype");
}
getNextToken(); // eat ')'
return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}
/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> 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;
}
/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
getNextToken(); // eat extern.
return ParsePrototype();
}
/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
if (auto E = ParseExpression()) {
// Make an anonymous proto.
auto Proto = std::make_unique<PrototypeAST>("", std::vector<std::string>());
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
}
return nullptr;
}
//===----------------------------------------------------------------------===//
// Top-Level parsing
//===----------------------------------------------------------------------===//
static void HandleDefinition() {
if (ParseDefinition()) {
fprintf(stderr, "Parsed a function definition.\n");
} else {
// Skip token for error recovery.
getNextToken();
}
}
static void HandleExtern() {
if (ParseExtern()) {
fprintf(stderr, "Parsed an extern\n");
} else {
// Skip token for error recovery.
getNextToken();
}
}
static void HandleTopLevelExpression() {
// Evaluate a top-level expression into an anonymous function.
if (ParseTopLevelExpr()) {
fprintf(stderr, "Parsed a top-level expr\n");
} else {
// Skip token for error recovery.
getNextToken();
}
}
/// top ::= definition | external | expression | ';'
static void MainLoop() {
while (true) {
fprintf(stderr, "ready> ");
switch (CurTok) {
case tok_eof:
return;
case ';': // ignore top-level semicolons.
getNextToken();
break;
case tok_def:
HandleDefinition();
break;
case tok_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
int main() {
// Prime the first token.
fprintf(stderr, "ready> ");
getNextToken();
// Run the main "interpreter loop" now.
MainLoop();
return 0;
}