blob: d425b101b518ba13de236064cfacc75b2b580906 [file] [log] [blame]
Lang Hames09bf4c12015-08-18 18:11:06 +00001#include "llvm/ADT/STLExtras.h"
Chandler Carruthd7cd9ac92014-01-13 09:53:45 +00002#include "llvm/IR/Verifier.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00003#include "llvm/IR/DerivedTypes.h"
4#include "llvm/IR/IRBuilder.h"
5#include "llvm/IR/LLVMContext.h"
6#include "llvm/IR/Module.h"
Will Dietz981af002013-10-12 00:55:57 +00007#include <cctype>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +00008#include <cstdio>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +00009#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000010#include <string>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000011#include <vector>
12using namespace llvm;
13
14//===----------------------------------------------------------------------===//
15// Lexer
16//===----------------------------------------------------------------------===//
17
18// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
19// of these for known things.
20enum Token {
21 tok_eof = -1,
22
23 // commands
24 tok_def = -2, tok_extern = -3,
25
26 // primary
27 tok_identifier = -4, tok_number = -5
28};
29
30static std::string IdentifierStr; // Filled in if tok_identifier
31static double NumVal; // Filled in if tok_number
32
33/// gettok - Return the next token from standard input.
34static int gettok() {
35 static int LastChar = ' ';
36
37 // Skip any whitespace.
38 while (isspace(LastChar))
39 LastChar = getchar();
40
41 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
42 IdentifierStr = LastChar;
43 while (isalnum((LastChar = getchar())))
44 IdentifierStr += LastChar;
45
46 if (IdentifierStr == "def") return tok_def;
47 if (IdentifierStr == "extern") 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(), 0);
59 return tok_number;
60 }
61
62 if (LastChar == '#') {
63 // Comment until end of line.
64 do LastChar = getchar();
65 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
66
67 if (LastChar != EOF)
68 return gettok();
69 }
70
71 // Check for end of file. Don't eat the EOF.
72 if (LastChar == EOF)
73 return tok_eof;
74
75 // Otherwise, just return the character as its ascii value.
76 int ThisChar = LastChar;
77 LastChar = getchar();
78 return ThisChar;
79}
80
81//===----------------------------------------------------------------------===//
82// Abstract Syntax Tree (aka Parse Tree)
83//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +000084namespace {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000085/// ExprAST - Base class for all expression nodes.
86class ExprAST {
87public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +000088 virtual ~ExprAST() {}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000089 virtual Value *Codegen() = 0;
90};
91
92/// NumberExprAST - Expression class for numeric literals like "1.0".
93class NumberExprAST : public ExprAST {
94 double Val;
95public:
Lang Hames09bf4c12015-08-18 18:11:06 +000096 NumberExprAST(double Val) : Val(Val) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +000097 Value *Codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000098};
99
100/// VariableExprAST - Expression class for referencing a variable, like "a".
101class VariableExprAST : public ExprAST {
102 std::string Name;
103public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000104 VariableExprAST(const std::string &Name) : Name(Name) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000105 Value *Codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000106};
107
108/// BinaryExprAST - Expression class for a binary operator.
109class BinaryExprAST : public ExprAST {
110 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000111 std::unique_ptr<ExprAST> LHS, RHS;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000112public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000113 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
114 std::unique_ptr<ExprAST> RHS)
115 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000116 Value *Codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000117};
118
119/// CallExprAST - Expression class for function calls.
120class CallExprAST : public ExprAST {
121 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000122 std::vector<std::unique_ptr<ExprAST>> Args;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000123public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000124 CallExprAST(const std::string &Callee,
125 std::vector<std::unique_ptr<ExprAST>> Args)
126 : Callee(Callee), Args(std::move(Args)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000127 Value *Codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000128};
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).
133class PrototypeAST {
134 std::string Name;
135 std::vector<std::string> Args;
136public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000137 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
138 : Name(Name), Args(std::move(Args)) {}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000139
140 Function *Codegen();
141};
142
143/// FunctionAST - This class represents a function definition itself.
144class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000145 std::unique_ptr<PrototypeAST> Proto;
146 std::unique_ptr<ExprAST> Body;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000147public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000148 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
149 std::unique_ptr<ExprAST> Body)
150 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000151
152 Function *Codegen();
153};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000154} // end anonymous namespace
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000155
156//===----------------------------------------------------------------------===//
157// Parser
158//===----------------------------------------------------------------------===//
159
160/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
161/// token the parser is looking at. getNextToken reads another token from the
162/// lexer and updates CurTok with its results.
163static int CurTok;
164static int getNextToken() {
165 return CurTok = gettok();
166}
167
168/// BinopPrecedence - This holds the precedence for each binary operator that is
169/// defined.
170static std::map<char, int> BinopPrecedence;
171
172/// GetTokPrecedence - Get the precedence of the pending binary operator token.
173static int GetTokPrecedence() {
174 if (!isascii(CurTok))
175 return -1;
176
177 // Make sure it's a declared binop.
178 int TokPrec = BinopPrecedence[CurTok];
179 if (TokPrec <= 0) return -1;
180 return TokPrec;
181}
182
183/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000184std::unique_ptr<ExprAST> Error(const char *Str) {
185 fprintf(stderr, "Error: %s\n", Str);
186 return nullptr;
187}
188std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
189 Error(Str);
190 return nullptr;
191}
192std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
193 Error(Str);
194 return nullptr;
195}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000196
Lang Hames09bf4c12015-08-18 18:11:06 +0000197static std::unique_ptr<ExprAST> ParseExpression();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000198
199/// identifierexpr
200/// ::= identifier
201/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000202static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000203 std::string IdName = IdentifierStr;
204
205 getNextToken(); // eat identifier.
206
207 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000208 return llvm::make_unique<VariableExprAST>(IdName);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000209
210 // Call.
211 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000212 std::vector<std::unique_ptr<ExprAST>> Args;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000213 if (CurTok != ')') {
214 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000215 if (auto Arg = ParseExpression())
216 Args.push_back(std::move(Arg));
217 else
218 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000219
220 if (CurTok == ')') break;
221
222 if (CurTok != ',')
223 return Error("Expected ')' or ',' in argument list");
224 getNextToken();
225 }
226 }
227
228 // Eat the ')'.
229 getNextToken();
230
Lang Hames09bf4c12015-08-18 18:11:06 +0000231 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000232}
233
234/// numberexpr ::= number
Lang Hames09bf4c12015-08-18 18:11:06 +0000235static std::unique_ptr<ExprAST> ParseNumberExpr() {
236 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000237 getNextToken(); // consume the number
Lang Hames09bf4c12015-08-18 18:11:06 +0000238 return std::move(Result);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000239}
240
241/// parenexpr ::= '(' expression ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000242static std::unique_ptr<ExprAST> ParseParenExpr() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000243 getNextToken(); // eat (.
Lang Hames09bf4c12015-08-18 18:11:06 +0000244 auto V = ParseExpression();
245 if (!V)
246 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000247
248 if (CurTok != ')')
249 return Error("expected ')'");
250 getNextToken(); // eat ).
251 return V;
252}
253
254/// primary
255/// ::= identifierexpr
256/// ::= numberexpr
257/// ::= parenexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000258static std::unique_ptr<ExprAST> ParsePrimary() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000259 switch (CurTok) {
260 default: return Error("unknown token when expecting an expression");
261 case tok_identifier: return ParseIdentifierExpr();
262 case tok_number: return ParseNumberExpr();
263 case '(': return ParseParenExpr();
264 }
265}
266
267/// binoprhs
268/// ::= ('+' primary)*
Lang Hames09bf4c12015-08-18 18:11:06 +0000269static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
270 std::unique_ptr<ExprAST> LHS) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000271 // If this is a binop, find its precedence.
272 while (1) {
273 int TokPrec = GetTokPrecedence();
274
275 // If this is a binop that binds at least as tightly as the current binop,
276 // consume it, otherwise we are done.
277 if (TokPrec < ExprPrec)
278 return LHS;
279
280 // Okay, we know this is a binop.
281 int BinOp = CurTok;
282 getNextToken(); // eat binop
283
284 // Parse the primary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000285 auto RHS = ParsePrimary();
286 if (!RHS) return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000287
288 // If BinOp binds less tightly with RHS than the operator after RHS, let
289 // the pending operator take RHS as its LHS.
290 int NextPrec = GetTokPrecedence();
291 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000292 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
293 if (!RHS) return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000294 }
295
296 // Merge LHS/RHS.
Lang Hames09bf4c12015-08-18 18:11:06 +0000297 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
298 std::move(RHS));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000299 }
300}
301
302/// expression
303/// ::= primary binoprhs
304///
Lang Hames09bf4c12015-08-18 18:11:06 +0000305static std::unique_ptr<ExprAST> ParseExpression() {
306 auto LHS = ParsePrimary();
307 if (!LHS) return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000308
Lang Hames09bf4c12015-08-18 18:11:06 +0000309 return ParseBinOpRHS(0, std::move(LHS));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000310}
311
312/// prototype
313/// ::= id '(' id* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000314static std::unique_ptr<PrototypeAST> ParsePrototype() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000315 if (CurTok != tok_identifier)
316 return ErrorP("Expected function name in prototype");
317
318 std::string FnName = IdentifierStr;
319 getNextToken();
320
321 if (CurTok != '(')
322 return ErrorP("Expected '(' in prototype");
323
324 std::vector<std::string> ArgNames;
325 while (getNextToken() == tok_identifier)
326 ArgNames.push_back(IdentifierStr);
327 if (CurTok != ')')
328 return ErrorP("Expected ')' in prototype");
329
330 // success.
331 getNextToken(); // eat ')'.
332
Lang Hames09bf4c12015-08-18 18:11:06 +0000333 return llvm::make_unique<PrototypeAST>(std::move(FnName),
334 std::move(ArgNames));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000335}
336
337/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000338static std::unique_ptr<FunctionAST> ParseDefinition() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000339 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000340 auto Proto = ParsePrototype();
341 if (!Proto) return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000342
Lang Hames09bf4c12015-08-18 18:11:06 +0000343 if (auto E = ParseExpression())
344 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
345 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000346}
347
348/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000349static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
350 if (auto E = ParseExpression()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000351 // Make an anonymous proto.
Lang Hames09bf4c12015-08-18 18:11:06 +0000352 auto Proto = llvm::make_unique<PrototypeAST>("",
353 std::vector<std::string>());
354 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000355 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000356 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000357}
358
359/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000360static std::unique_ptr<PrototypeAST> ParseExtern() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000361 getNextToken(); // eat extern.
362 return ParsePrototype();
363}
364
365//===----------------------------------------------------------------------===//
366// Code Generation
367//===----------------------------------------------------------------------===//
368
369static Module *TheModule;
370static IRBuilder<> Builder(getGlobalContext());
371static std::map<std::string, Value*> NamedValues;
372
Lang Hames09bf4c12015-08-18 18:11:06 +0000373Value *ErrorV(const char *Str) { Error(Str); return nullptr; }
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000374
375Value *NumberExprAST::Codegen() {
376 return ConstantFP::get(getGlobalContext(), APFloat(Val));
377}
378
379Value *VariableExprAST::Codegen() {
380 // Look this variable up in the function.
381 Value *V = NamedValues[Name];
382 return V ? V : ErrorV("Unknown variable name");
383}
384
385Value *BinaryExprAST::Codegen() {
386 Value *L = LHS->Codegen();
387 Value *R = RHS->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000388 if (!L || !R) return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000389
390 switch (Op) {
Chris Lattner26d79502010-06-21 22:51:14 +0000391 case '+': return Builder.CreateFAdd(L, R, "addtmp");
392 case '-': return Builder.CreateFSub(L, R, "subtmp");
393 case '*': return Builder.CreateFMul(L, R, "multmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000394 case '<':
395 L = Builder.CreateFCmpULT(L, R, "cmptmp");
396 // Convert bool 0/1 to double 0.0 or 1.0
397 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
398 "booltmp");
399 default: return ErrorV("invalid binary operator");
400 }
401}
402
403Value *CallExprAST::Codegen() {
404 // Look up the name in the global module table.
405 Function *CalleeF = TheModule->getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000406 if (!CalleeF)
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000407 return ErrorV("Unknown function referenced");
408
409 // If argument mismatch error.
410 if (CalleeF->arg_size() != Args.size())
411 return ErrorV("Incorrect # arguments passed");
412
413 std::vector<Value*> ArgsV;
414 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
415 ArgsV.push_back(Args[i]->Codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000416 if (!ArgsV.back()) return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000417 }
418
Francois Pichetc5d10502011-07-15 10:59:52 +0000419 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000420}
421
422Function *PrototypeAST::Codegen() {
423 // Make the function type: double(double,double) etc.
John Wiegley2a0177b2011-07-11 22:39:46 +0000424 std::vector<Type*> Doubles(Args.size(),
425 Type::getDoubleTy(getGlobalContext()));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000426 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
427 Doubles, false);
428
Lang Hames09bf4c12015-08-18 18:11:06 +0000429 Function *F = Function::Create(FT, Function::ExternalLinkage, Name,
430 TheModule);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000431
432 // If F conflicted, there was already something named 'Name'. If it has a
433 // body, don't allow redefinition or reextern.
434 if (F->getName() != Name) {
435 // Delete the one we just made and get the existing one.
436 F->eraseFromParent();
437 F = TheModule->getFunction(Name);
438
439 // If F already has a body, reject this.
440 if (!F->empty()) {
441 ErrorF("redefinition of function");
Lang Hames09bf4c12015-08-18 18:11:06 +0000442 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000443 }
444
445 // If F took a different number of args, reject.
446 if (F->arg_size() != Args.size()) {
447 ErrorF("redefinition of function with different # args");
Lang Hames09bf4c12015-08-18 18:11:06 +0000448 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000449 }
450 }
451
452 // Set names for all arguments.
453 unsigned Idx = 0;
454 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
455 ++AI, ++Idx) {
456 AI->setName(Args[Idx]);
457
458 // Add arguments to variable symbol table.
459 NamedValues[Args[Idx]] = AI;
460 }
461
462 return F;
463}
464
465Function *FunctionAST::Codegen() {
466 NamedValues.clear();
467
468 Function *TheFunction = Proto->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000469 if (!TheFunction)
470 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000471
472 // Create a new basic block to start insertion into.
473 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
474 Builder.SetInsertPoint(BB);
475
476 if (Value *RetVal = Body->Codegen()) {
477 // Finish off the function.
478 Builder.CreateRet(RetVal);
479
480 // Validate the generated code, checking for consistency.
481 verifyFunction(*TheFunction);
482
483 return TheFunction;
484 }
485
486 // Error reading body, remove function.
487 TheFunction->eraseFromParent();
Lang Hames09bf4c12015-08-18 18:11:06 +0000488 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000489}
490
491//===----------------------------------------------------------------------===//
492// Top-Level parsing and JIT Driver
493//===----------------------------------------------------------------------===//
494
495static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000496 if (auto FnAST = ParseDefinition()) {
497 if (auto *FnIR = FnAST->Codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000498 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +0000499 FnIR->dump();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000500 }
501 } else {
502 // Skip token for error recovery.
503 getNextToken();
504 }
505}
506
507static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000508 if (auto ProtoAST = ParseExtern()) {
509 if (auto *FnIR = ProtoAST->Codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000510 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +0000511 FnIR->dump();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000512 }
513 } else {
514 // Skip token for error recovery.
515 getNextToken();
516 }
517}
518
519static void HandleTopLevelExpression() {
520 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +0000521 if (auto FnAST = ParseTopLevelExpr()) {
522 if (auto *FnIR = FnAST->Codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000523 fprintf(stderr, "Read top-level expression:");
Lang Hames09bf4c12015-08-18 18:11:06 +0000524 FnIR->dump();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000525 }
526 } else {
527 // Skip token for error recovery.
528 getNextToken();
529 }
530}
531
532/// top ::= definition | external | expression | ';'
533static void MainLoop() {
534 while (1) {
535 fprintf(stderr, "ready> ");
536 switch (CurTok) {
537 case tok_eof: return;
538 case ';': getNextToken(); break; // ignore top-level semicolons.
539 case tok_def: HandleDefinition(); break;
540 case tok_extern: HandleExtern(); break;
541 default: HandleTopLevelExpression(); break;
542 }
543 }
544}
545
546//===----------------------------------------------------------------------===//
547// "Library" functions that can be "extern'd" from user code.
548//===----------------------------------------------------------------------===//
549
550/// putchard - putchar that takes a double and returns 0.
551extern "C"
552double putchard(double X) {
553 putchar((char)X);
554 return 0;
555}
556
557//===----------------------------------------------------------------------===//
558// Main driver code.
559//===----------------------------------------------------------------------===//
560
561int main() {
562 LLVMContext &Context = getGlobalContext();
563
564 // Install standard binary operators.
565 // 1 is lowest precedence.
566 BinopPrecedence['<'] = 10;
567 BinopPrecedence['+'] = 20;
568 BinopPrecedence['-'] = 20;
569 BinopPrecedence['*'] = 40; // highest.
570
571 // Prime the first token.
572 fprintf(stderr, "ready> ");
573 getNextToken();
574
575 // Make the module, which holds all the code.
Lang Hames09bf4c12015-08-18 18:11:06 +0000576 std::unique_ptr<Module> Owner = llvm::make_unique<Module>("my cool jit", Context);
577 TheModule = Owner.get();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000578
579 // Run the main "interpreter loop" now.
580 MainLoop();
581
582 // Print out all of the generated code.
583 TheModule->dump();
584
585 return 0;
586}