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) {}
89 virtual ~NumberExprAST();
92 /// VariableExprAST - Expression class for referencing a variable, like "a".
93 class VariableExprAST : public ExprAST {
96 VariableExprAST(const std::string &name) : Name(name) {}
97 virtual ~VariableExprAST();
100 /// BinaryExprAST - Expression class for a binary operator.
101 class BinaryExprAST : public ExprAST {
103 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) {}
104 virtual ~BinaryExprAST();
107 /// CallExprAST - Expression class for function calls.
108 class CallExprAST : public ExprAST {
110 std::vector<ExprAST*> Args;
112 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
113 : Callee(callee), Args(args) {}
114 virtual ~CallExprAST();
117 // Provide out-of-line definitions to prevent weak vtables.
118 ExprAST::~ExprAST() {}
119 NumberExprAST::~NumberExprAST() {}
120 VariableExprAST::~VariableExprAST() {}
121 BinaryExprAST::~BinaryExprAST() {}
122 CallExprAST::~CallExprAST() {}
124 /// PrototypeAST - This class represents the "prototype" for a function,
125 /// which captures its name, and its argument names (thus implicitly the number
126 /// of arguments the function takes).
129 std::vector<std::string> Args;
131 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
132 : Name(name), Args(args) {}
136 /// FunctionAST - This class represents a function definition itself.
139 FunctionAST(PrototypeAST *proto, ExprAST *body) {}
142 //===----------------------------------------------------------------------===//
144 //===----------------------------------------------------------------------===//
146 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
147 /// token the parser is looking at. getNextToken reads another token from the
148 /// lexer and updates CurTok with its results.
150 static int getNextToken() {
151 return CurTok = gettok();
154 /// BinopPrecedence - This holds the precedence for each binary operator that is
156 static std::map<char, int> BinopPrecedence;
158 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
159 static int GetTokPrecedence() {
160 if (!isascii(CurTok))
163 // Make sure it's a declared binop.
164 int TokPrec = BinopPrecedence[CurTok];
165 if (TokPrec <= 0) return -1;
169 /// Error* - These are little helper functions for error handling.
170 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
171 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
172 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
174 static ExprAST *ParseExpression();
178 /// ::= identifier '(' expression* ')'
179 static ExprAST *ParseIdentifierExpr() {
180 std::string IdName = IdentifierStr;
182 getNextToken(); // eat identifier.
184 if (CurTok != '(') // Simple variable ref.
185 return new VariableExprAST(IdName);
188 getNextToken(); // eat (
189 std::vector<ExprAST*> Args;
192 ExprAST *Arg = ParseExpression();
196 if (CurTok == ')') break;
199 return Error("Expected ')' or ',' in argument list");
207 return new CallExprAST(IdName, Args);
210 /// numberexpr ::= number
211 static ExprAST *ParseNumberExpr() {
212 ExprAST *Result = new NumberExprAST(NumVal);
213 getNextToken(); // consume the number
217 /// parenexpr ::= '(' expression ')'
218 static ExprAST *ParseParenExpr() {
219 getNextToken(); // eat (.
220 ExprAST *V = ParseExpression();
224 return Error("expected ')'");
225 getNextToken(); // eat ).
230 /// ::= identifierexpr
233 static ExprAST *ParsePrimary() {
235 default: return Error("unknown token when expecting an expression");
236 case tok_identifier: return ParseIdentifierExpr();
237 case tok_number: return ParseNumberExpr();
238 case '(': return ParseParenExpr();
243 /// ::= ('+' primary)*
244 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
245 // If this is a binop, find its precedence.
247 int TokPrec = GetTokPrecedence();
249 // If this is a binop that binds at least as tightly as the current binop,
250 // consume it, otherwise we are done.
251 if (TokPrec < ExprPrec)
254 // Okay, we know this is a binop.
256 getNextToken(); // eat binop
258 // Parse the primary expression after the binary operator.
259 ExprAST *RHS = ParsePrimary();
262 // If BinOp binds less tightly with RHS than the operator after RHS, let
263 // the pending operator take RHS as its LHS.
264 int NextPrec = GetTokPrecedence();
265 if (TokPrec < NextPrec) {
266 RHS = ParseBinOpRHS(TokPrec+1, RHS);
267 if (RHS == 0) return 0;
271 LHS = new BinaryExprAST(BinOp, LHS, RHS);
276 /// ::= primary binoprhs
278 static ExprAST *ParseExpression() {
279 ExprAST *LHS = ParsePrimary();
282 return ParseBinOpRHS(0, LHS);
286 /// ::= id '(' id* ')'
287 static PrototypeAST *ParsePrototype() {
288 if (CurTok != tok_identifier)
289 return ErrorP("Expected function name in prototype");
291 std::string FnName = IdentifierStr;
295 return ErrorP("Expected '(' in prototype");
297 std::vector<std::string> ArgNames;
298 while (getNextToken() == tok_identifier)
299 ArgNames.push_back(IdentifierStr);
301 return ErrorP("Expected ')' in prototype");
304 getNextToken(); // eat ')'.
306 return new PrototypeAST(FnName, ArgNames);
309 /// definition ::= 'def' prototype expression
310 static FunctionAST *ParseDefinition() {
311 getNextToken(); // eat def.
312 PrototypeAST *Proto = ParsePrototype();
313 if (Proto == 0) return 0;
315 if (ExprAST *E = ParseExpression())
316 return new FunctionAST(Proto, E);
320 /// toplevelexpr ::= expression
321 static FunctionAST *ParseTopLevelExpr() {
322 if (ExprAST *E = ParseExpression()) {
323 // Make an anonymous proto.
324 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
325 return new FunctionAST(Proto, E);
330 /// external ::= 'extern' prototype
331 static PrototypeAST *ParseExtern() {
332 getNextToken(); // eat extern.
333 return ParsePrototype();
336 //===----------------------------------------------------------------------===//
338 //===----------------------------------------------------------------------===//
340 static void HandleDefinition() {
341 if (ParseDefinition()) {
342 fprintf(stderr, "Parsed a function definition.\n");
344 // Skip token for error recovery.
349 static void HandleExtern() {
351 fprintf(stderr, "Parsed an extern\n");
353 // Skip token for error recovery.
358 static void HandleTopLevelExpression() {
359 // Evaluate a top-level expression into an anonymous function.
360 if (ParseTopLevelExpr()) {
361 fprintf(stderr, "Parsed a top-level expr\n");
363 // Skip token for error recovery.
368 /// top ::= definition | external | expression | ';'
369 static void MainLoop() {
371 fprintf(stderr, "ready> ");
373 case tok_eof: return;
374 case ';': getNextToken(); break; // ignore top-level semicolons.
375 case tok_def: HandleDefinition(); break;
376 case tok_extern: HandleExtern(); break;
377 default: HandleTopLevelExpression(); break;
382 //===----------------------------------------------------------------------===//
384 //===----------------------------------------------------------------------===//
387 // Install standard binary operators.
388 // 1 is lowest precedence.
389 BinopPrecedence['<'] = 10;
390 BinopPrecedence['+'] = 20;
391 BinopPrecedence['-'] = 20;
392 BinopPrecedence['*'] = 40; // highest.
394 // Prime the first token.
395 fprintf(stderr, "ready> ");
398 // Run the main "interpreter loop" now.