9 // Cloning make_unique here until it's standard in C++14.
10 // Using a namespace to avoid conflicting with MSVC's std::make_unique (which
11 // ADL can sometimes find in unqualified calls).
12 template <class T, class... Args>
14 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
15 make_unique(Args &&... args) {
16 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
38 static std::string IdentifierStr; // Filled in if tok_identifier
39 static double NumVal; // Filled in if tok_number
41 /// gettok - Return the next token from standard input.
43 static int LastChar = ' ';
45 // Skip any whitespace.
46 while (isspace(LastChar))
49 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
50 IdentifierStr = LastChar;
51 while (isalnum((LastChar = getchar())))
52 IdentifierStr += LastChar;
54 if (IdentifierStr == "def")
56 if (IdentifierStr == "extern")
58 return tok_identifier;
61 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
66 } while (isdigit(LastChar) || LastChar == '.');
68 NumVal = strtod(NumStr.c_str(), nullptr);
72 if (LastChar == '#') {
73 // Comment until end of line.
76 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
82 // Check for end of file. Don't eat the EOF.
86 // Otherwise, just return the character as its ascii value.
87 int ThisChar = LastChar;
92 //===----------------------------------------------------------------------===//
93 // Abstract Syntax Tree (aka Parse Tree)
94 //===----------------------------------------------------------------------===//
96 /// ExprAST - Base class for all expression nodes.
102 /// NumberExprAST - Expression class for numeric literals like "1.0".
103 class NumberExprAST : public ExprAST {
107 NumberExprAST(double Val) : Val(Val) {}
110 /// VariableExprAST - Expression class for referencing a variable, like "a".
111 class VariableExprAST : public ExprAST {
115 VariableExprAST(const std::string &Name) : Name(Name) {}
118 /// BinaryExprAST - Expression class for a binary operator.
119 class BinaryExprAST : public ExprAST {
121 std::unique_ptr<ExprAST> LHS, RHS;
124 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
125 std::unique_ptr<ExprAST> RHS)
126 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
129 /// CallExprAST - Expression class for function calls.
130 class CallExprAST : public ExprAST {
132 std::vector<std::unique_ptr<ExprAST>> Args;
135 CallExprAST(const std::string &Callee,
136 std::vector<std::unique_ptr<ExprAST>> Args)
137 : Callee(Callee), Args(std::move(Args)) {}
140 /// PrototypeAST - This class represents the "prototype" for a function,
141 /// which captures its name, and its argument names (thus implicitly the number
142 /// of arguments the function takes).
145 std::vector<std::string> Args;
148 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
149 : Name(Name), Args(std::move(Args)) {}
152 /// FunctionAST - This class represents a function definition itself.
154 std::unique_ptr<PrototypeAST> Proto;
155 std::unique_ptr<ExprAST> Body;
158 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
159 std::unique_ptr<ExprAST> Body)
160 : Proto(std::move(Proto)), Body(std::move(Body)) {}
162 } // end anonymous namespace
164 //===----------------------------------------------------------------------===//
166 //===----------------------------------------------------------------------===//
168 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
169 /// token the parser is looking at. getNextToken reads another token from the
170 /// lexer and updates CurTok with its results.
172 static int getNextToken() { return CurTok = gettok(); }
174 /// BinopPrecedence - This holds the precedence for each binary operator that is
176 static std::map<char, int> BinopPrecedence;
178 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
179 static int GetTokPrecedence() {
180 if (!isascii(CurTok))
183 // Make sure it's a declared binop.
184 int TokPrec = BinopPrecedence[CurTok];
190 /// Error* - These are little helper functions for error handling.
191 std::unique_ptr<ExprAST> Error(const char *Str) {
192 fprintf(stderr, "Error: %s\n", Str);
195 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
200 static std::unique_ptr<ExprAST> ParseExpression();
202 /// numberexpr ::= number
203 static std::unique_ptr<ExprAST> ParseNumberExpr() {
204 auto Result = helper::make_unique<NumberExprAST>(NumVal);
205 getNextToken(); // consume the number
206 return std::move(Result);
209 /// parenexpr ::= '(' expression ')'
210 static std::unique_ptr<ExprAST> ParseParenExpr() {
211 getNextToken(); // eat (.
212 auto V = ParseExpression();
217 return Error("expected ')'");
218 getNextToken(); // eat ).
224 /// ::= identifier '(' expression* ')'
225 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
226 std::string IdName = IdentifierStr;
228 getNextToken(); // eat identifier.
230 if (CurTok != '(') // Simple variable ref.
231 return helper::make_unique<VariableExprAST>(IdName);
234 getNextToken(); // eat (
235 std::vector<std::unique_ptr<ExprAST>> Args;
238 if (auto Arg = ParseExpression())
239 Args.push_back(std::move(Arg));
247 return Error("Expected ')' or ',' in argument list");
255 return helper::make_unique<CallExprAST>(IdName, std::move(Args));
259 /// ::= identifierexpr
262 static std::unique_ptr<ExprAST> ParsePrimary() {
265 return Error("unknown token when expecting an expression");
267 return ParseIdentifierExpr();
269 return ParseNumberExpr();
271 return ParseParenExpr();
276 /// ::= ('+' primary)*
277 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
278 std::unique_ptr<ExprAST> LHS) {
279 // If this is a binop, find its precedence.
281 int TokPrec = GetTokPrecedence();
283 // If this is a binop that binds at least as tightly as the current binop,
284 // consume it, otherwise we are done.
285 if (TokPrec < ExprPrec)
288 // Okay, we know this is a binop.
290 getNextToken(); // eat binop
292 // Parse the primary expression after the binary operator.
293 auto RHS = ParsePrimary();
297 // If BinOp binds less tightly with RHS than the operator after RHS, let
298 // the pending operator take RHS as its LHS.
299 int NextPrec = GetTokPrecedence();
300 if (TokPrec < NextPrec) {
301 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
307 LHS = helper::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
313 /// ::= primary binoprhs
315 static std::unique_ptr<ExprAST> ParseExpression() {
316 auto LHS = ParsePrimary();
320 return ParseBinOpRHS(0, std::move(LHS));
324 /// ::= id '(' id* ')'
325 static std::unique_ptr<PrototypeAST> ParsePrototype() {
326 if (CurTok != tok_identifier)
327 return ErrorP("Expected function name in prototype");
329 std::string FnName = IdentifierStr;
333 return ErrorP("Expected '(' in prototype");
335 std::vector<std::string> ArgNames;
336 while (getNextToken() == tok_identifier)
337 ArgNames.push_back(IdentifierStr);
339 return ErrorP("Expected ')' in prototype");
342 getNextToken(); // eat ')'.
344 return helper::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
347 /// definition ::= 'def' prototype expression
348 static std::unique_ptr<FunctionAST> ParseDefinition() {
349 getNextToken(); // eat def.
350 auto Proto = ParsePrototype();
354 if (auto E = ParseExpression())
355 return helper::make_unique<FunctionAST>(std::move(Proto), std::move(E));
359 /// toplevelexpr ::= expression
360 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
361 if (auto E = ParseExpression()) {
362 // Make an anonymous proto.
363 auto Proto = helper::make_unique<PrototypeAST>("__anon_expr",
364 std::vector<std::string>());
365 return helper::make_unique<FunctionAST>(std::move(Proto), std::move(E));
370 /// external ::= 'extern' prototype
371 static std::unique_ptr<PrototypeAST> ParseExtern() {
372 getNextToken(); // eat extern.
373 return ParsePrototype();
376 //===----------------------------------------------------------------------===//
378 //===----------------------------------------------------------------------===//
380 static void HandleDefinition() {
381 if (ParseDefinition()) {
382 fprintf(stderr, "Parsed a function definition.\n");
384 // Skip token for error recovery.
389 static void HandleExtern() {
391 fprintf(stderr, "Parsed an extern\n");
393 // Skip token for error recovery.
398 static void HandleTopLevelExpression() {
399 // Evaluate a top-level expression into an anonymous function.
400 if (ParseTopLevelExpr()) {
401 fprintf(stderr, "Parsed a top-level expr\n");
403 // Skip token for error recovery.
408 /// top ::= definition | external | expression | ';'
409 static void MainLoop() {
411 fprintf(stderr, "ready> ");
415 case ';': // ignore top-level semicolons.
425 HandleTopLevelExpression();
431 //===----------------------------------------------------------------------===//
433 //===----------------------------------------------------------------------===//
436 // Install standard binary operators.
437 // 1 is lowest precedence.
438 BinopPrecedence['<'] = 10;
439 BinopPrecedence['+'] = 20;
440 BinopPrecedence['-'] = 20;
441 BinopPrecedence['*'] = 40; // highest.
443 // Prime the first token.
444 fprintf(stderr, "ready> ");
447 // Run the main "interpreter loop" now.