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 ExprAST::~ExprAST() {}
87 /// NumberExprAST - Expression class for numeric literals like "1.0".
88 class NumberExprAST : public ExprAST {
90 NumberExprAST(double val) {}
91 virtual ~NumberExprAST();
94 NumberExprAST::~NumberExprAST() {}
96 /// VariableExprAST - Expression class for referencing a variable, like "a".
97 class VariableExprAST : public ExprAST {
100 VariableExprAST(const std::string &name) : Name(name) {}
101 virtual ~VariableExprAST();
104 VariableExprAST::~VariableExprAST() {}
106 /// BinaryExprAST - Expression class for a binary operator.
107 class BinaryExprAST : public ExprAST {
109 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) {}
110 virtual ~BinaryExprAST();
113 BinaryExprAST::~BinaryExprAST() {}
115 /// CallExprAST - Expression class for function calls.
116 class CallExprAST : public ExprAST {
118 std::vector<ExprAST*> Args;
120 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
121 : Callee(callee), Args(args) {}
122 virtual ~CallExprAST();
125 CallExprAST::~CallExprAST() {}
127 /// PrototypeAST - This class represents the "prototype" for a function,
128 /// which captures its name, and its argument names (thus implicitly the number
129 /// of arguments the function takes).
132 std::vector<std::string> Args;
134 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
135 : Name(name), Args(args) {}
139 /// FunctionAST - This class represents a function definition itself.
142 FunctionAST(PrototypeAST *proto, ExprAST *body) {}
145 //===----------------------------------------------------------------------===//
147 //===----------------------------------------------------------------------===//
149 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
150 /// token the parser is looking at. getNextToken reads another token from the
151 /// lexer and updates CurTok with its results.
153 static int getNextToken() {
154 return CurTok = gettok();
157 /// BinopPrecedence - This holds the precedence for each binary operator that is
159 static std::map<char, int> BinopPrecedence;
161 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
162 static int GetTokPrecedence() {
163 if (!isascii(CurTok))
166 // Make sure it's a declared binop.
167 int TokPrec = BinopPrecedence[CurTok];
168 if (TokPrec <= 0) return -1;
172 /// Error* - These are little helper functions for error handling.
173 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
174 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
175 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
177 static ExprAST *ParseExpression();
181 /// ::= identifier '(' expression* ')'
182 static ExprAST *ParseIdentifierExpr() {
183 std::string IdName = IdentifierStr;
185 getNextToken(); // eat identifier.
187 if (CurTok != '(') // Simple variable ref.
188 return new VariableExprAST(IdName);
191 getNextToken(); // eat (
192 std::vector<ExprAST*> Args;
195 ExprAST *Arg = ParseExpression();
199 if (CurTok == ')') break;
202 return Error("Expected ')' or ',' in argument list");
210 return new CallExprAST(IdName, Args);
213 /// numberexpr ::= number
214 static ExprAST *ParseNumberExpr() {
215 ExprAST *Result = new NumberExprAST(NumVal);
216 getNextToken(); // consume the number
220 /// parenexpr ::= '(' expression ')'
221 static ExprAST *ParseParenExpr() {
222 getNextToken(); // eat (.
223 ExprAST *V = ParseExpression();
227 return Error("expected ')'");
228 getNextToken(); // eat ).
233 /// ::= identifierexpr
236 static ExprAST *ParsePrimary() {
238 default: return Error("unknown token when expecting an expression");
239 case tok_identifier: return ParseIdentifierExpr();
240 case tok_number: return ParseNumberExpr();
241 case '(': return ParseParenExpr();
246 /// ::= ('+' primary)*
247 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
248 // If this is a binop, find its precedence.
250 int TokPrec = GetTokPrecedence();
252 // If this is a binop that binds at least as tightly as the current binop,
253 // consume it, otherwise we are done.
254 if (TokPrec < ExprPrec)
257 // Okay, we know this is a binop.
259 getNextToken(); // eat binop
261 // Parse the primary expression after the binary operator.
262 ExprAST *RHS = ParsePrimary();
265 // If BinOp binds less tightly with RHS than the operator after RHS, let
266 // the pending operator take RHS as its LHS.
267 int NextPrec = GetTokPrecedence();
268 if (TokPrec < NextPrec) {
269 RHS = ParseBinOpRHS(TokPrec+1, RHS);
270 if (RHS == 0) return 0;
274 LHS = new BinaryExprAST(BinOp, LHS, RHS);
279 /// ::= primary binoprhs
281 static ExprAST *ParseExpression() {
282 ExprAST *LHS = ParsePrimary();
285 return ParseBinOpRHS(0, LHS);
289 /// ::= id '(' id* ')'
290 static PrototypeAST *ParsePrototype() {
291 if (CurTok != tok_identifier)
292 return ErrorP("Expected function name in prototype");
294 std::string FnName = IdentifierStr;
298 return ErrorP("Expected '(' in prototype");
300 std::vector<std::string> ArgNames;
301 while (getNextToken() == tok_identifier)
302 ArgNames.push_back(IdentifierStr);
304 return ErrorP("Expected ')' in prototype");
307 getNextToken(); // eat ')'.
309 return new PrototypeAST(FnName, ArgNames);
312 /// definition ::= 'def' prototype expression
313 static FunctionAST *ParseDefinition() {
314 getNextToken(); // eat def.
315 PrototypeAST *Proto = ParsePrototype();
316 if (Proto == 0) return 0;
318 if (ExprAST *E = ParseExpression())
319 return new FunctionAST(Proto, E);
323 /// toplevelexpr ::= expression
324 static FunctionAST *ParseTopLevelExpr() {
325 if (ExprAST *E = ParseExpression()) {
326 // Make an anonymous proto.
327 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
328 return new FunctionAST(Proto, E);
333 /// external ::= 'extern' prototype
334 static PrototypeAST *ParseExtern() {
335 getNextToken(); // eat extern.
336 return ParsePrototype();
339 //===----------------------------------------------------------------------===//
341 //===----------------------------------------------------------------------===//
343 static void HandleDefinition() {
344 if (ParseDefinition()) {
345 fprintf(stderr, "Parsed a function definition.\n");
347 // Skip token for error recovery.
352 static void HandleExtern() {
354 fprintf(stderr, "Parsed an extern\n");
356 // Skip token for error recovery.
361 static void HandleTopLevelExpression() {
362 // Evaluate a top-level expression into an anonymous function.
363 if (ParseTopLevelExpr()) {
364 fprintf(stderr, "Parsed a top-level expr\n");
366 // Skip token for error recovery.
371 /// top ::= definition | external | expression | ';'
372 static void MainLoop() {
374 fprintf(stderr, "ready> ");
376 case tok_eof: return;
377 case ';': getNextToken(); break; // ignore top-level semicolons.
378 case tok_def: HandleDefinition(); break;
379 case tok_extern: HandleExtern(); break;
380 default: HandleTopLevelExpression(); break;
385 //===----------------------------------------------------------------------===//
387 //===----------------------------------------------------------------------===//
390 // Install standard binary operators.
391 // 1 is lowest precedence.
392 BinopPrecedence['<'] = 10;
393 BinopPrecedence['+'] = 20;
394 BinopPrecedence['-'] = 20;
395 BinopPrecedence['*'] = 40; // highest.
397 // Prime the first token.
398 fprintf(stderr, "ready> ");
401 // Run the main "interpreter loop" now.