1 #include "llvm/ADT/STLExtras.h"
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, std::unique_ptr<ExprAST> LHS,
102 std::unique_ptr<ExprAST> RHS) {}
105 /// CallExprAST - Expression class for function calls.
106 class CallExprAST : public ExprAST {
108 std::vector<std::unique_ptr<ExprAST>> Args;
110 CallExprAST(const std::string &Callee,
111 std::vector<std::unique_ptr<ExprAST>> Args)
112 : Callee(Callee), Args(std::move(Args)) {}
115 /// PrototypeAST - This class represents the "prototype" for a function,
116 /// which captures its name, and its argument names (thus implicitly the number
117 /// of arguments the function takes).
120 std::vector<std::string> Args;
122 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
123 : Name(Name), Args(std::move(Args)) {}
127 /// FunctionAST - This class represents a function definition itself.
130 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
131 std::unique_ptr<ExprAST> Body) {}
133 } // end anonymous namespace
135 //===----------------------------------------------------------------------===//
137 //===----------------------------------------------------------------------===//
139 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
140 /// token the parser is looking at. getNextToken reads another token from the
141 /// lexer and updates CurTok with its results.
143 static int getNextToken() {
144 return CurTok = gettok();
147 /// BinopPrecedence - This holds the precedence for each binary operator that is
149 static std::map<char, int> BinopPrecedence;
151 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
152 static int GetTokPrecedence() {
153 if (!isascii(CurTok))
156 // Make sure it's a declared binop.
157 int TokPrec = BinopPrecedence[CurTok];
158 if (TokPrec <= 0) return -1;
162 /// Error* - These are little helper functions for error handling.
163 std::unique_ptr<ExprAST> Error(const char *Str) {
164 fprintf(stderr, "Error: %s\n", Str);
167 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
172 static std::unique_ptr<ExprAST> ParseExpression();
176 /// ::= identifier '(' expression* ')'
177 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
178 std::string IdName = IdentifierStr;
180 getNextToken(); // eat identifier.
182 if (CurTok != '(') // Simple variable ref.
183 return llvm::make_unique<VariableExprAST>(IdName);
186 getNextToken(); // eat (
187 std::vector<std::unique_ptr<ExprAST>> Args;
190 if (auto Arg = ParseExpression())
191 Args.push_back(std::move(Arg));
195 if (CurTok == ')') break;
198 return Error("Expected ')' or ',' in argument list");
206 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
209 /// numberexpr ::= number
210 static std::unique_ptr<ExprAST> ParseNumberExpr() {
211 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
212 getNextToken(); // consume the number
213 return std::move(Result);
216 /// parenexpr ::= '(' expression ')'
217 static std::unique_ptr<ExprAST> ParseParenExpr() {
218 getNextToken(); // eat (.
219 auto V = ParseExpression();
224 return Error("expected ')'");
225 getNextToken(); // eat ).
230 /// ::= identifierexpr
233 static std::unique_ptr<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 std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
245 std::unique_ptr<ExprAST> LHS) {
246 // If this is a binop, find its precedence.
248 int TokPrec = GetTokPrecedence();
250 // If this is a binop that binds at least as tightly as the current binop,
251 // consume it, otherwise we are done.
252 if (TokPrec < ExprPrec)
255 // Okay, we know this is a binop.
257 getNextToken(); // eat binop
259 // Parse the primary expression after the binary operator.
260 auto RHS = ParsePrimary();
261 if (!RHS) return nullptr;
263 // If BinOp binds less tightly with RHS than the operator after RHS, let
264 // the pending operator take RHS as its LHS.
265 int NextPrec = GetTokPrecedence();
266 if (TokPrec < NextPrec) {
267 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
268 if (!RHS) return nullptr;
272 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
278 /// ::= primary binoprhs
280 static std::unique_ptr<ExprAST> ParseExpression() {
281 auto LHS = ParsePrimary();
282 if (!LHS) return nullptr;
284 return ParseBinOpRHS(0, std::move(LHS));
288 /// ::= id '(' id* ')'
289 static std::unique_ptr<PrototypeAST> ParsePrototype() {
290 if (CurTok != tok_identifier)
291 return ErrorP("Expected function name in prototype");
293 std::string FnName = IdentifierStr;
297 return ErrorP("Expected '(' in prototype");
299 std::vector<std::string> ArgNames;
300 while (getNextToken() == tok_identifier)
301 ArgNames.push_back(IdentifierStr);
303 return ErrorP("Expected ')' in prototype");
306 getNextToken(); // eat ')'.
308 return llvm::make_unique<PrototypeAST>(std::move(FnName),
309 std::move(ArgNames));
312 /// definition ::= 'def' prototype expression
313 static std::unique_ptr<FunctionAST> ParseDefinition() {
314 getNextToken(); // eat def.
315 auto Proto = ParsePrototype();
316 if (!Proto) return nullptr;
318 if (auto E = ParseExpression())
319 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
323 /// toplevelexpr ::= expression
324 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
325 if (auto E = ParseExpression()) {
326 // Make an anonymous proto.
327 auto Proto = llvm::make_unique<PrototypeAST>("",
328 std::vector<std::string>());
329 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
334 /// external ::= 'extern' prototype
335 static std::unique_ptr<PrototypeAST> ParseExtern() {
336 getNextToken(); // eat extern.
337 return ParsePrototype();
340 //===----------------------------------------------------------------------===//
342 //===----------------------------------------------------------------------===//
344 static void HandleDefinition() {
345 if (ParseDefinition()) {
346 fprintf(stderr, "Parsed a function definition.\n");
348 // Skip token for error recovery.
353 static void HandleExtern() {
355 fprintf(stderr, "Parsed an extern\n");
357 // Skip token for error recovery.
362 static void HandleTopLevelExpression() {
363 // Evaluate a top-level expression into an anonymous function.
364 if (ParseTopLevelExpr()) {
365 fprintf(stderr, "Parsed a top-level expr\n");
367 // Skip token for error recovery.
372 /// top ::= definition | external | expression | ';'
373 static void MainLoop() {
375 fprintf(stderr, "ready> ");
377 case tok_eof: return;
378 case ';': getNextToken(); break; // ignore top-level semicolons.
379 case tok_def: HandleDefinition(); break;
380 case tok_extern: HandleExtern(); break;
381 default: HandleTopLevelExpression(); break;
386 //===----------------------------------------------------------------------===//
388 //===----------------------------------------------------------------------===//
391 // Install standard binary operators.
392 // 1 is lowest precedence.
393 BinopPrecedence['<'] = 10;
394 BinopPrecedence['+'] = 20;
395 BinopPrecedence['-'] = 20;
396 BinopPrecedence['*'] = 40; // highest.
398 // Prime the first token.
399 fprintf(stderr, "ready> ");
402 // Run the main "interpreter loop" now.