8
//===----------------------------------------------------------------------===//
10
//===----------------------------------------------------------------------===//
12
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
13
// of these for known things.
18
tok_def = -2, tok_extern = -3,
21
tok_identifier = -4, tok_number = -5
24
static std::string IdentifierStr; // Filled in if tok_identifier
25
static double NumVal; // Filled in if tok_number
27
/// gettok - Return the next token from standard input.
29
static int LastChar = ' ';
31
// Skip any whitespace.
32
while (isspace(LastChar))
35
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
36
IdentifierStr = LastChar;
37
while (isalnum((LastChar = getchar())))
38
IdentifierStr += LastChar;
40
if (IdentifierStr == "def") return tok_def;
41
if (IdentifierStr == "extern") return tok_extern;
42
return tok_identifier;
45
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
50
} while (isdigit(LastChar) || LastChar == '.');
52
NumVal = strtod(NumStr.c_str(), 0);
56
if (LastChar == '#') {
57
// Comment until end of line.
58
do LastChar = getchar();
59
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
65
// Check for end of file. Don't eat the EOF.
69
// Otherwise, just return the character as its ascii value.
70
int ThisChar = LastChar;
75
//===----------------------------------------------------------------------===//
76
// Abstract Syntax Tree (aka Parse Tree)
77
//===----------------------------------------------------------------------===//
79
/// ExprAST - Base class for all expression nodes.
85
/// NumberExprAST - Expression class for numeric literals like "1.0".
86
class NumberExprAST : public ExprAST {
88
NumberExprAST(double val) {}
91
/// VariableExprAST - Expression class for referencing a variable, like "a".
92
class VariableExprAST : public ExprAST {
95
VariableExprAST(const std::string &name) : Name(name) {}
98
/// BinaryExprAST - Expression class for a binary operator.
99
class BinaryExprAST : public ExprAST {
101
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) {}
104
/// CallExprAST - Expression class for function calls.
105
class CallExprAST : public ExprAST {
107
std::vector<ExprAST*> Args;
109
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
110
: Callee(callee), Args(args) {}
113
/// PrototypeAST - This class represents the "prototype" for a function,
114
/// which captures its name, and its argument names (thus implicitly the number
115
/// of arguments the function takes).
118
std::vector<std::string> Args;
120
PrototypeAST(const std::string &name, const std::vector<std::string> &args)
121
: Name(name), Args(args) {}
125
/// FunctionAST - This class represents a function definition itself.
128
FunctionAST(PrototypeAST *proto, ExprAST *body) {}
130
} // end anonymous namespace
132
//===----------------------------------------------------------------------===//
134
//===----------------------------------------------------------------------===//
136
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
137
/// token the parser is looking at. getNextToken reads another token from the
138
/// lexer and updates CurTok with its results.
140
static int getNextToken() {
141
return CurTok = gettok();
144
/// BinopPrecedence - This holds the precedence for each binary operator that is
146
static std::map<char, int> BinopPrecedence;
148
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
149
static int GetTokPrecedence() {
150
if (!isascii(CurTok))
153
// Make sure it's a declared binop.
154
int TokPrec = BinopPrecedence[CurTok];
155
if (TokPrec <= 0) return -1;
159
/// Error* - These are little helper functions for error handling.
160
ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
161
PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
163
static ExprAST *ParseExpression();
167
/// ::= identifier '(' expression* ')'
168
static ExprAST *ParseIdentifierExpr() {
169
std::string IdName = IdentifierStr;
171
getNextToken(); // eat identifier.
173
if (CurTok != '(') // Simple variable ref.
174
return new VariableExprAST(IdName);
177
getNextToken(); // eat (
178
std::vector<ExprAST*> Args;
181
ExprAST *Arg = ParseExpression();
185
if (CurTok == ')') break;
188
return Error("Expected ')' or ',' in argument list");
196
return new CallExprAST(IdName, Args);
199
/// numberexpr ::= number
200
static ExprAST *ParseNumberExpr() {
201
ExprAST *Result = new NumberExprAST(NumVal);
202
getNextToken(); // consume the number
206
/// parenexpr ::= '(' expression ')'
207
static ExprAST *ParseParenExpr() {
208
getNextToken(); // eat (.
209
ExprAST *V = ParseExpression();
213
return Error("expected ')'");
214
getNextToken(); // eat ).
219
/// ::= identifierexpr
222
static ExprAST *ParsePrimary() {
224
default: return Error("unknown token when expecting an expression");
225
case tok_identifier: return ParseIdentifierExpr();
226
case tok_number: return ParseNumberExpr();
227
case '(': return ParseParenExpr();
232
/// ::= ('+' primary)*
233
static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
234
// If this is a binop, find its precedence.
236
int TokPrec = GetTokPrecedence();
238
// If this is a binop that binds at least as tightly as the current binop,
239
// consume it, otherwise we are done.
240
if (TokPrec < ExprPrec)
243
// Okay, we know this is a binop.
245
getNextToken(); // eat binop
247
// Parse the primary expression after the binary operator.
248
ExprAST *RHS = ParsePrimary();
251
// If BinOp binds less tightly with RHS than the operator after RHS, let
252
// the pending operator take RHS as its LHS.
253
int NextPrec = GetTokPrecedence();
254
if (TokPrec < NextPrec) {
255
RHS = ParseBinOpRHS(TokPrec+1, RHS);
256
if (RHS == 0) return 0;
260
LHS = new BinaryExprAST(BinOp, LHS, RHS);
265
/// ::= primary binoprhs
267
static ExprAST *ParseExpression() {
268
ExprAST *LHS = ParsePrimary();
271
return ParseBinOpRHS(0, LHS);
275
/// ::= id '(' id* ')'
276
static PrototypeAST *ParsePrototype() {
277
if (CurTok != tok_identifier)
278
return ErrorP("Expected function name in prototype");
280
std::string FnName = IdentifierStr;
284
return ErrorP("Expected '(' in prototype");
286
std::vector<std::string> ArgNames;
287
while (getNextToken() == tok_identifier)
288
ArgNames.push_back(IdentifierStr);
290
return ErrorP("Expected ')' in prototype");
293
getNextToken(); // eat ')'.
295
return new PrototypeAST(FnName, ArgNames);
298
/// definition ::= 'def' prototype expression
299
static FunctionAST *ParseDefinition() {
300
getNextToken(); // eat def.
301
PrototypeAST *Proto = ParsePrototype();
302
if (Proto == 0) return 0;
304
if (ExprAST *E = ParseExpression())
305
return new FunctionAST(Proto, E);
309
/// toplevelexpr ::= expression
310
static FunctionAST *ParseTopLevelExpr() {
311
if (ExprAST *E = ParseExpression()) {
312
// Make an anonymous proto.
313
PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
314
return new FunctionAST(Proto, E);
319
/// external ::= 'extern' prototype
320
static PrototypeAST *ParseExtern() {
321
getNextToken(); // eat extern.
322
return ParsePrototype();
325
//===----------------------------------------------------------------------===//
327
//===----------------------------------------------------------------------===//
329
static void HandleDefinition() {
330
if (ParseDefinition()) {
331
fprintf(stderr, "Parsed a function definition.\n");
333
// Skip token for error recovery.
338
static void HandleExtern() {
340
fprintf(stderr, "Parsed an extern\n");
342
// Skip token for error recovery.
347
static void HandleTopLevelExpression() {
348
// Evaluate a top-level expression into an anonymous function.
349
if (ParseTopLevelExpr()) {
350
fprintf(stderr, "Parsed a top-level expr\n");
352
// Skip token for error recovery.
357
/// top ::= definition | external | expression | ';'
358
static void MainLoop() {
360
fprintf(stderr, "ready> ");
362
case tok_eof: return;
363
case ';': getNextToken(); break; // ignore top-level semicolons.
364
case tok_def: HandleDefinition(); break;
365
case tok_extern: HandleExtern(); break;
366
default: HandleTopLevelExpression(); break;
371
//===----------------------------------------------------------------------===//
373
//===----------------------------------------------------------------------===//
376
// Install standard binary operators.
377
// 1 is lowest precedence.
378
BinopPrecedence['<'] = 10;
379
BinopPrecedence['+'] = 20;
380
BinopPrecedence['-'] = 20;
381
BinopPrecedence['*'] = 40; // highest.
383
// Prime the first token.
384
fprintf(stderr, "ready> ");
387
// Run the main "interpreter loop" now.