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.
26 static std::string IdentifierStr; // Filled in if tok_identifier
27 static double NumVal; // Filled in if tok_number
29 /// gettok - Return the next token from standard input.
31 static int LastChar = ' ';
33 // Skip any whitespace.
34 while (isspace(LastChar))
37 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
38 IdentifierStr = LastChar;
39 while (isalnum((LastChar = getchar())))
40 IdentifierStr += LastChar;
42 if (IdentifierStr == "def")
44 if (IdentifierStr == "extern")
46 return tok_identifier;
49 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
54 } while (isdigit(LastChar) || LastChar == '.');
56 NumVal = strtod(NumStr.c_str(), nullptr);
60 if (LastChar == '#') {
61 // Comment until end of line.
64 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
70 // Check for end of file. Don't eat the EOF.
74 // Otherwise, just return the character as its ascii value.
75 int ThisChar = LastChar;
80 //===----------------------------------------------------------------------===//
81 // Abstract Syntax Tree (aka Parse Tree)
82 //===----------------------------------------------------------------------===//
84 /// ExprAST - Base class for all expression nodes.
90 /// NumberExprAST - Expression class for numeric literals like "1.0".
91 class NumberExprAST : public ExprAST {
95 NumberExprAST(double Val) : Val(Val) {}
98 /// VariableExprAST - Expression class for referencing a variable, like "a".
99 class VariableExprAST : public ExprAST {
103 VariableExprAST(const std::string &Name) : Name(Name) {}
106 /// BinaryExprAST - Expression class for a binary operator.
107 class BinaryExprAST : public ExprAST {
109 std::unique_ptr<ExprAST> LHS, RHS;
112 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
113 std::unique_ptr<ExprAST> RHS)
114 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
117 /// CallExprAST - Expression class for function calls.
118 class CallExprAST : public ExprAST {
120 std::vector<std::unique_ptr<ExprAST>> Args;
123 CallExprAST(const std::string &Callee,
124 std::vector<std::unique_ptr<ExprAST>> Args)
125 : Callee(Callee), Args(std::move(Args)) {}
128 /// PrototypeAST - This class represents the "prototype" for a function,
129 /// which captures its name, and its argument names (thus implicitly the number
130 /// of arguments the function takes).
133 std::vector<std::string> Args;
136 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
137 : Name(Name), Args(std::move(Args)) {}
140 /// FunctionAST - This class represents a function definition itself.
142 std::unique_ptr<PrototypeAST> Proto;
143 std::unique_ptr<ExprAST> Body;
146 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
147 std::unique_ptr<ExprAST> Body)
148 : Proto(std::move(Proto)), Body(std::move(Body)) {}
150 } // end anonymous namespace
152 //===----------------------------------------------------------------------===//
154 //===----------------------------------------------------------------------===//
156 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
157 /// token the parser is looking at. getNextToken reads another token from the
158 /// lexer and updates CurTok with its results.
160 static int getNextToken() { return CurTok = gettok(); }
162 /// BinopPrecedence - This holds the precedence for each binary operator that is
164 static std::map<char, int> BinopPrecedence;
166 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
167 static int GetTokPrecedence() {
168 if (!isascii(CurTok))
171 // Make sure it's a declared binop.
172 int TokPrec = BinopPrecedence[CurTok];
178 /// Error* - These are little helper functions for error handling.
179 std::unique_ptr<ExprAST> Error(const char *Str) {
180 fprintf(stderr, "Error: %s\n", Str);
183 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
188 static std::unique_ptr<ExprAST> ParseExpression();
190 /// numberexpr ::= number
191 static std::unique_ptr<ExprAST> ParseNumberExpr() {
192 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
193 getNextToken(); // consume the number
194 return std::move(Result);
197 /// parenexpr ::= '(' expression ')'
198 static std::unique_ptr<ExprAST> ParseParenExpr() {
199 getNextToken(); // eat (.
200 auto V = ParseExpression();
205 return Error("expected ')'");
206 getNextToken(); // eat ).
212 /// ::= identifier '(' expression* ')'
213 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
214 std::string IdName = IdentifierStr;
216 getNextToken(); // eat identifier.
218 if (CurTok != '(') // Simple variable ref.
219 return llvm::make_unique<VariableExprAST>(IdName);
222 getNextToken(); // eat (
223 std::vector<std::unique_ptr<ExprAST>> Args;
226 if (auto Arg = ParseExpression())
227 Args.push_back(std::move(Arg));
235 return Error("Expected ')' or ',' in argument list");
243 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
247 /// ::= identifierexpr
250 static std::unique_ptr<ExprAST> ParsePrimary() {
253 return Error("unknown token when expecting an expression");
255 return ParseIdentifierExpr();
257 return ParseNumberExpr();
259 return ParseParenExpr();
264 /// ::= ('+' primary)*
265 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
266 std::unique_ptr<ExprAST> LHS) {
267 // If this is a binop, find its precedence.
269 int TokPrec = GetTokPrecedence();
271 // If this is a binop that binds at least as tightly as the current binop,
272 // consume it, otherwise we are done.
273 if (TokPrec < ExprPrec)
276 // Okay, we know this is a binop.
278 getNextToken(); // eat binop
280 // Parse the primary expression after the binary operator.
281 auto RHS = ParsePrimary();
285 // If BinOp binds less tightly with RHS than the operator after RHS, let
286 // the pending operator take RHS as its LHS.
287 int NextPrec = GetTokPrecedence();
288 if (TokPrec < NextPrec) {
289 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
296 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
301 /// ::= primary binoprhs
303 static std::unique_ptr<ExprAST> ParseExpression() {
304 auto LHS = ParsePrimary();
308 return ParseBinOpRHS(0, std::move(LHS));
312 /// ::= id '(' id* ')'
313 static std::unique_ptr<PrototypeAST> ParsePrototype() {
314 if (CurTok != tok_identifier)
315 return ErrorP("Expected function name in prototype");
317 std::string FnName = IdentifierStr;
321 return ErrorP("Expected '(' in prototype");
323 std::vector<std::string> ArgNames;
324 while (getNextToken() == tok_identifier)
325 ArgNames.push_back(IdentifierStr);
327 return ErrorP("Expected ')' in prototype");
330 getNextToken(); // eat ')'.
332 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
335 /// definition ::= 'def' prototype expression
336 static std::unique_ptr<FunctionAST> ParseDefinition() {
337 getNextToken(); // eat def.
338 auto Proto = ParsePrototype();
342 if (auto E = ParseExpression())
343 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
347 /// toplevelexpr ::= expression
348 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
349 if (auto E = ParseExpression()) {
350 // Make an anonymous proto.
351 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
352 std::vector<std::string>());
353 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
358 /// external ::= 'extern' prototype
359 static std::unique_ptr<PrototypeAST> ParseExtern() {
360 getNextToken(); // eat extern.
361 return ParsePrototype();
364 //===----------------------------------------------------------------------===//
366 //===----------------------------------------------------------------------===//
368 static void HandleDefinition() {
369 if (ParseDefinition()) {
370 fprintf(stderr, "Parsed a function definition.\n");
372 // Skip token for error recovery.
377 static void HandleExtern() {
379 fprintf(stderr, "Parsed an extern\n");
381 // Skip token for error recovery.
386 static void HandleTopLevelExpression() {
387 // Evaluate a top-level expression into an anonymous function.
388 if (ParseTopLevelExpr()) {
389 fprintf(stderr, "Parsed a top-level expr\n");
391 // Skip token for error recovery.
396 /// top ::= definition | external | expression | ';'
397 static void MainLoop() {
399 fprintf(stderr, "ready> ");
403 case ';': // ignore top-level semicolons.
413 HandleTopLevelExpression();
419 //===----------------------------------------------------------------------===//
421 //===----------------------------------------------------------------------===//
424 // Install standard binary operators.
425 // 1 is lowest precedence.
426 BinopPrecedence['<'] = 10;
427 BinopPrecedence['+'] = 20;
428 BinopPrecedence['-'] = 20;
429 BinopPrecedence['*'] = 40; // highest.
431 // Prime the first token.
432 fprintf(stderr, "ready> ");
435 // Run the main "interpreter loop" now.