1 #include "llvm/ADT/STLExtras.h" 2 #include <cctype> 3 #include <cstdio> 4 #include <cstdlib> 5 #include <map> 6 #include <memory> 7 #include <string> 8 #include <vector> 9 10 //===----------------------------------------------------------------------===// 11 // Lexer 12 //===----------------------------------------------------------------------===// 13 14 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one 15 // of these for known things. 16 enum Token { 17 tok_eof = -1, 18 19 // commands 20 tok_def = -2, 21 tok_extern = -3, 22 23 // primary 24 tok_identifier = -4, 25 tok_number = -5 26 }; 27 28 static std::string IdentifierStr; // Filled in if tok_identifier 29 static double NumVal; // Filled in if tok_number 30 31 /// gettok - Return the next token from standard input. 32 static int gettok() { 33 static int LastChar = ' '; 34 35 // Skip any whitespace. 36 while (isspace(LastChar)) 37 LastChar = getchar(); 38 39 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]* 40 IdentifierStr = LastChar; 41 while (isalnum((LastChar = getchar()))) 42 IdentifierStr += LastChar; 43 44 if (IdentifierStr == "def") 45 return tok_def; 46 if (IdentifierStr == "extern") 47 return tok_extern; 48 return tok_identifier; 49 } 50 51 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+ 52 std::string NumStr; 53 do { 54 NumStr += LastChar; 55 LastChar = getchar(); 56 } while (isdigit(LastChar) || LastChar == '.'); 57 58 NumVal = strtod(NumStr.c_str(), nullptr); 59 return tok_number; 60 } 61 62 if (LastChar == '#') { 63 // Comment until end of line. 64 do 65 LastChar = getchar(); 66 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r'); 67 68 if (LastChar != EOF) 69 return gettok(); 70 } 71 72 // Check for end of file. Don't eat the EOF. 73 if (LastChar == EOF) 74 return tok_eof; 75 76 // Otherwise, just return the character as its ascii value. 77 int ThisChar = LastChar; 78 LastChar = getchar(); 79 return ThisChar; 80 } 81 82 //===----------------------------------------------------------------------===// 83 // Abstract Syntax Tree (aka Parse Tree) 84 //===----------------------------------------------------------------------===// 85 namespace { 86 /// ExprAST - Base class for all expression nodes. 87 class ExprAST { 88 public: 89 virtual ~ExprAST() {} 90 }; 91 92 /// NumberExprAST - Expression class for numeric literals like "1.0". 93 class NumberExprAST : public ExprAST { 94 double Val; 95 96 public: 97 NumberExprAST(double Val) : Val(Val) {} 98 }; 99 100 /// VariableExprAST - Expression class for referencing a variable, like "a". 101 class VariableExprAST : public ExprAST { 102 std::string Name; 103 104 public: 105 VariableExprAST(const std::string &Name) : Name(Name) {} 106 }; 107 108 /// BinaryExprAST - Expression class for a binary operator. 109 class BinaryExprAST : public ExprAST { 110 char Op; 111 std::unique_ptr<ExprAST> LHS, RHS; 112 113 public: 114 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS, 115 std::unique_ptr<ExprAST> RHS) 116 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {} 117 }; 118 119 /// CallExprAST - Expression class for function calls. 120 class CallExprAST : public ExprAST { 121 std::string Callee; 122 std::vector<std::unique_ptr<ExprAST>> Args; 123 124 public: 125 CallExprAST(const std::string &Callee, 126 std::vector<std::unique_ptr<ExprAST>> Args) 127 : Callee(Callee), Args(std::move(Args)) {} 128 }; 129 130 /// PrototypeAST - This class represents the "prototype" for a function, 131 /// which captures its name, and its argument names (thus implicitly the number 132 /// of arguments the function takes). 133 class PrototypeAST { 134 std::string Name; 135 std::vector<std::string> Args; 136 137 public: 138 PrototypeAST(const std::string &Name, std::vector<std::string> Args) 139 : Name(Name), Args(std::move(Args)) {} 140 }; 141 142 /// FunctionAST - This class represents a function definition itself. 143 class FunctionAST { 144 std::unique_ptr<PrototypeAST> Proto; 145 std::unique_ptr<ExprAST> Body; 146 147 public: 148 FunctionAST(std::unique_ptr<PrototypeAST> Proto, 149 std::unique_ptr<ExprAST> Body) 150 : Proto(std::move(Proto)), Body(std::move(Body)) {} 151 }; 152 } // end anonymous namespace 153 154 //===----------------------------------------------------------------------===// 155 // Parser 156 //===----------------------------------------------------------------------===// 157 158 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current 159 /// token the parser is looking at. getNextToken reads another token from the 160 /// lexer and updates CurTok with its results. 161 static int CurTok; 162 static int getNextToken() { return CurTok = gettok(); } 163 164 /// BinopPrecedence - This holds the precedence for each binary operator that is 165 /// defined. 166 static std::map<char, int> BinopPrecedence; 167 168 /// GetTokPrecedence - Get the precedence of the pending binary operator token. 169 static int GetTokPrecedence() { 170 if (!isascii(CurTok)) 171 return -1; 172 173 // Make sure it's a declared binop. 174 int TokPrec = BinopPrecedence[CurTok]; 175 if (TokPrec <= 0) 176 return -1; 177 return TokPrec; 178 } 179 180 /// LogError* - These are little helper functions for error handling. 181 std::unique_ptr<ExprAST> LogError(const char *Str) { 182 fprintf(stderr, "Error: %s\n", Str); 183 return nullptr; 184 } 185 std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) { 186 LogError(Str); 187 return nullptr; 188 } 189 190 static std::unique_ptr<ExprAST> ParseExpression(); 191 192 /// numberexpr ::= number 193 static std::unique_ptr<ExprAST> ParseNumberExpr() { 194 auto Result = llvm::make_unique<NumberExprAST>(NumVal); 195 getNextToken(); // consume the number 196 return std::move(Result); 197 } 198 199 /// parenexpr ::= '(' expression ')' 200 static std::unique_ptr<ExprAST> ParseParenExpr() { 201 getNextToken(); // eat (. 202 auto V = ParseExpression(); 203 if (!V) 204 return nullptr; 205 206 if (CurTok != ')') 207 return LogError("expected ')'"); 208 getNextToken(); // eat ). 209 return V; 210 } 211 212 /// identifierexpr 213 /// ::= identifier 214 /// ::= identifier '(' expression* ')' 215 static std::unique_ptr<ExprAST> ParseIdentifierExpr() { 216 std::string IdName = IdentifierStr; 217 218 getNextToken(); // eat identifier. 219 220 if (CurTok != '(') // Simple variable ref. 221 return llvm::make_unique<VariableExprAST>(IdName); 222 223 // Call. 224 getNextToken(); // eat ( 225 std::vector<std::unique_ptr<ExprAST>> Args; 226 if (CurTok != ')') { 227 while (true) { 228 if (auto Arg = ParseExpression()) 229 Args.push_back(std::move(Arg)); 230 else 231 return nullptr; 232 233 if (CurTok == ')') 234 break; 235 236 if (CurTok != ',') 237 return LogError("Expected ')' or ',' in argument list"); 238 getNextToken(); 239 } 240 } 241 242 // Eat the ')'. 243 getNextToken(); 244 245 return llvm::make_unique<CallExprAST>(IdName, std::move(Args)); 246 } 247 248 /// primary 249 /// ::= identifierexpr 250 /// ::= numberexpr 251 /// ::= parenexpr 252 static std::unique_ptr<ExprAST> ParsePrimary() { 253 switch (CurTok) { 254 default: 255 return LogError("unknown token when expecting an expression"); 256 case tok_identifier: 257 return ParseIdentifierExpr(); 258 case tok_number: 259 return ParseNumberExpr(); 260 case '(': 261 return ParseParenExpr(); 262 } 263 } 264 265 /// binoprhs 266 /// ::= ('+' primary)* 267 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, 268 std::unique_ptr<ExprAST> LHS) { 269 // If this is a binop, find its precedence. 270 while (true) { 271 int TokPrec = GetTokPrecedence(); 272 273 // If this is a binop that binds at least as tightly as the current binop, 274 // consume it, otherwise we are done. 275 if (TokPrec < ExprPrec) 276 return LHS; 277 278 // Okay, we know this is a binop. 279 int BinOp = CurTok; 280 getNextToken(); // eat binop 281 282 // Parse the primary expression after the binary operator. 283 auto RHS = ParsePrimary(); 284 if (!RHS) 285 return nullptr; 286 287 // If BinOp binds less tightly with RHS than the operator after RHS, let 288 // the pending operator take RHS as its LHS. 289 int NextPrec = GetTokPrecedence(); 290 if (TokPrec < NextPrec) { 291 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS)); 292 if (!RHS) 293 return nullptr; 294 } 295 296 // Merge LHS/RHS. 297 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), 298 std::move(RHS)); 299 } 300 } 301 302 /// expression 303 /// ::= primary binoprhs 304 /// 305 static std::unique_ptr<ExprAST> ParseExpression() { 306 auto LHS = ParsePrimary(); 307 if (!LHS) 308 return nullptr; 309 310 return ParseBinOpRHS(0, std::move(LHS)); 311 } 312 313 /// prototype 314 /// ::= id '(' id* ')' 315 static std::unique_ptr<PrototypeAST> ParsePrototype() { 316 if (CurTok != tok_identifier) 317 return LogErrorP("Expected function name in prototype"); 318 319 std::string FnName = IdentifierStr; 320 getNextToken(); 321 322 if (CurTok != '(') 323 return LogErrorP("Expected '(' in prototype"); 324 325 std::vector<std::string> ArgNames; 326 while (getNextToken() == tok_identifier) 327 ArgNames.push_back(IdentifierStr); 328 if (CurTok != ')') 329 return LogErrorP("Expected ')' in prototype"); 330 331 // success. 332 getNextToken(); // eat ')'. 333 334 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames)); 335 } 336 337 /// definition ::= 'def' prototype expression 338 static std::unique_ptr<FunctionAST> ParseDefinition() { 339 getNextToken(); // eat def. 340 auto Proto = ParsePrototype(); 341 if (!Proto) 342 return nullptr; 343 344 if (auto E = ParseExpression()) 345 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E)); 346 return nullptr; 347 } 348 349 /// toplevelexpr ::= expression 350 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() { 351 if (auto E = ParseExpression()) { 352 // Make an anonymous proto. 353 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr", 354 std::vector<std::string>()); 355 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E)); 356 } 357 return nullptr; 358 } 359 360 /// external ::= 'extern' prototype 361 static std::unique_ptr<PrototypeAST> ParseExtern() { 362 getNextToken(); // eat extern. 363 return ParsePrototype(); 364 } 365 366 //===----------------------------------------------------------------------===// 367 // Top-Level parsing 368 //===----------------------------------------------------------------------===// 369 370 static void HandleDefinition() { 371 if (ParseDefinition()) { 372 fprintf(stderr, "Parsed a function definition.\n"); 373 } else { 374 // Skip token for error recovery. 375 getNextToken(); 376 } 377 } 378 379 static void HandleExtern() { 380 if (ParseExtern()) { 381 fprintf(stderr, "Parsed an extern\n"); 382 } else { 383 // Skip token for error recovery. 384 getNextToken(); 385 } 386 } 387 388 static void HandleTopLevelExpression() { 389 // Evaluate a top-level expression into an anonymous function. 390 if (ParseTopLevelExpr()) { 391 fprintf(stderr, "Parsed a top-level expr\n"); 392 } else { 393 // Skip token for error recovery. 394 getNextToken(); 395 } 396 } 397 398 /// top ::= definition | external | expression | ';' 399 static void MainLoop() { 400 while (true) { 401 fprintf(stderr, "ready> "); 402 switch (CurTok) { 403 case tok_eof: 404 return; 405 case ';': // ignore top-level semicolons. 406 getNextToken(); 407 break; 408 case tok_def: 409 HandleDefinition(); 410 break; 411 case tok_extern: 412 HandleExtern(); 413 break; 414 default: 415 HandleTopLevelExpression(); 416 break; 417 } 418 } 419 } 420 421 //===----------------------------------------------------------------------===// 422 // Main driver code. 423 //===----------------------------------------------------------------------===// 424 425 int main() { 426 // Install standard binary operators. 427 // 1 is lowest precedence. 428 BinopPrecedence['<'] = 10; 429 BinopPrecedence['+'] = 20; 430 BinopPrecedence['-'] = 20; 431 BinopPrecedence['*'] = 40; // highest. 432 433 // Prime the first token. 434 fprintf(stderr, "ready> "); 435 getNextToken(); 436 437 // Run the main "interpreter loop" now. 438 MainLoop(); 439 440 return 0; 441 } 442