1 #include "llvm/ADT/STLExtras.h"
11 //===----------------------------------------------------------------------===//
13 //===----------------------------------------------------------------------===//
15 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
16 // of these for known things.
29 static std::string IdentifierStr
; // Filled in if tok_identifier
30 static double NumVal
; // Filled in if tok_number
32 /// gettok - Return the next token from standard input.
34 static int LastChar
= ' ';
36 // Skip any whitespace.
37 while (isspace(LastChar
))
40 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
41 IdentifierStr
= LastChar
;
42 while (isalnum((LastChar
= getchar())))
43 IdentifierStr
+= LastChar
;
45 if (IdentifierStr
== "def")
47 if (IdentifierStr
== "extern")
49 return tok_identifier
;
52 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
57 } while (isdigit(LastChar
) || LastChar
== '.');
59 NumVal
= strtod(NumStr
.c_str(), nullptr);
63 if (LastChar
== '#') {
64 // Comment until end of line.
67 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
73 // Check for end of file. Don't eat the EOF.
77 // Otherwise, just return the character as its ascii value.
78 int ThisChar
= LastChar
;
83 //===----------------------------------------------------------------------===//
84 // Abstract Syntax Tree (aka Parse Tree)
85 //===----------------------------------------------------------------------===//
89 /// ExprAST - Base class for all expression nodes.
92 virtual ~ExprAST() = default;
95 /// NumberExprAST - Expression class for numeric literals like "1.0".
96 class NumberExprAST
: public ExprAST
{
100 NumberExprAST(double Val
) : Val(Val
) {}
103 /// VariableExprAST - Expression class for referencing a variable, like "a".
104 class VariableExprAST
: public ExprAST
{
108 VariableExprAST(const std::string
&Name
) : Name(Name
) {}
111 /// BinaryExprAST - Expression class for a binary operator.
112 class BinaryExprAST
: public ExprAST
{
114 std::unique_ptr
<ExprAST
> LHS
, RHS
;
117 BinaryExprAST(char Op
, std::unique_ptr
<ExprAST
> LHS
,
118 std::unique_ptr
<ExprAST
> RHS
)
119 : Op(Op
), LHS(std::move(LHS
)), RHS(std::move(RHS
)) {}
122 /// CallExprAST - Expression class for function calls.
123 class CallExprAST
: public ExprAST
{
125 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
128 CallExprAST(const std::string
&Callee
,
129 std::vector
<std::unique_ptr
<ExprAST
>> Args
)
130 : Callee(Callee
), Args(std::move(Args
)) {}
133 /// PrototypeAST - This class represents the "prototype" for a function,
134 /// which captures its name, and its argument names (thus implicitly the number
135 /// of arguments the function takes).
138 std::vector
<std::string
> Args
;
141 PrototypeAST(const std::string
&Name
, std::vector
<std::string
> Args
)
142 : Name(Name
), Args(std::move(Args
)) {}
144 const std::string
&getName() const { return Name
; }
147 /// FunctionAST - This class represents a function definition itself.
149 std::unique_ptr
<PrototypeAST
> Proto
;
150 std::unique_ptr
<ExprAST
> Body
;
153 FunctionAST(std::unique_ptr
<PrototypeAST
> Proto
,
154 std::unique_ptr
<ExprAST
> Body
)
155 : Proto(std::move(Proto
)), Body(std::move(Body
)) {}
158 } // end anonymous namespace
160 //===----------------------------------------------------------------------===//
162 //===----------------------------------------------------------------------===//
164 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
165 /// token the parser is looking at. getNextToken reads another token from the
166 /// lexer and updates CurTok with its results.
168 static int getNextToken() { return CurTok
= gettok(); }
170 /// BinopPrecedence - This holds the precedence for each binary operator that is
172 static std::map
<char, int> BinopPrecedence
;
174 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
175 static int GetTokPrecedence() {
176 if (!isascii(CurTok
))
179 // Make sure it's a declared binop.
180 int TokPrec
= BinopPrecedence
[CurTok
];
186 /// LogError* - These are little helper functions for error handling.
187 std::unique_ptr
<ExprAST
> LogError(const char *Str
) {
188 fprintf(stderr
, "Error: %s\n", Str
);
191 std::unique_ptr
<PrototypeAST
> LogErrorP(const char *Str
) {
196 static std::unique_ptr
<ExprAST
> ParseExpression();
198 /// numberexpr ::= number
199 static std::unique_ptr
<ExprAST
> ParseNumberExpr() {
200 auto Result
= std::make_unique
<NumberExprAST
>(NumVal
);
201 getNextToken(); // consume the number
202 return std::move(Result
);
205 /// parenexpr ::= '(' expression ')'
206 static std::unique_ptr
<ExprAST
> ParseParenExpr() {
207 getNextToken(); // eat (.
208 auto V
= ParseExpression();
213 return LogError("expected ')'");
214 getNextToken(); // eat ).
220 /// ::= identifier '(' expression* ')'
221 static std::unique_ptr
<ExprAST
> ParseIdentifierExpr() {
222 std::string IdName
= IdentifierStr
;
224 getNextToken(); // eat identifier.
226 if (CurTok
!= '(') // Simple variable ref.
227 return std::make_unique
<VariableExprAST
>(IdName
);
230 getNextToken(); // eat (
231 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
234 if (auto Arg
= ParseExpression())
235 Args
.push_back(std::move(Arg
));
243 return LogError("Expected ')' or ',' in argument list");
251 return std::make_unique
<CallExprAST
>(IdName
, std::move(Args
));
255 /// ::= identifierexpr
258 static std::unique_ptr
<ExprAST
> ParsePrimary() {
261 return LogError("unknown token when expecting an expression");
263 return ParseIdentifierExpr();
265 return ParseNumberExpr();
267 return ParseParenExpr();
272 /// ::= ('+' primary)*
273 static std::unique_ptr
<ExprAST
> ParseBinOpRHS(int ExprPrec
,
274 std::unique_ptr
<ExprAST
> LHS
) {
275 // If this is a binop, find its precedence.
277 int TokPrec
= GetTokPrecedence();
279 // If this is a binop that binds at least as tightly as the current binop,
280 // consume it, otherwise we are done.
281 if (TokPrec
< ExprPrec
)
284 // Okay, we know this is a binop.
286 getNextToken(); // eat binop
288 // Parse the primary expression after the binary operator.
289 auto RHS
= ParsePrimary();
293 // If BinOp binds less tightly with RHS than the operator after RHS, let
294 // the pending operator take RHS as its LHS.
295 int NextPrec
= GetTokPrecedence();
296 if (TokPrec
< NextPrec
) {
297 RHS
= ParseBinOpRHS(TokPrec
+ 1, std::move(RHS
));
303 LHS
= std::make_unique
<BinaryExprAST
>(BinOp
, std::move(LHS
),
309 /// ::= primary binoprhs
311 static std::unique_ptr
<ExprAST
> ParseExpression() {
312 auto LHS
= ParsePrimary();
316 return ParseBinOpRHS(0, std::move(LHS
));
320 /// ::= id '(' id* ')'
321 static std::unique_ptr
<PrototypeAST
> ParsePrototype() {
322 if (CurTok
!= tok_identifier
)
323 return LogErrorP("Expected function name in prototype");
325 std::string FnName
= IdentifierStr
;
329 return LogErrorP("Expected '(' in prototype");
331 std::vector
<std::string
> ArgNames
;
332 while (getNextToken() == tok_identifier
)
333 ArgNames
.push_back(IdentifierStr
);
335 return LogErrorP("Expected ')' in prototype");
338 getNextToken(); // eat ')'.
340 return std::make_unique
<PrototypeAST
>(FnName
, std::move(ArgNames
));
343 /// definition ::= 'def' prototype expression
344 static std::unique_ptr
<FunctionAST
> ParseDefinition() {
345 getNextToken(); // eat def.
346 auto Proto
= ParsePrototype();
350 if (auto E
= ParseExpression())
351 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
355 /// toplevelexpr ::= expression
356 static std::unique_ptr
<FunctionAST
> ParseTopLevelExpr() {
357 if (auto E
= ParseExpression()) {
358 // Make an anonymous proto.
359 auto Proto
= std::make_unique
<PrototypeAST
>("__anon_expr",
360 std::vector
<std::string
>());
361 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
366 /// external ::= 'extern' prototype
367 static std::unique_ptr
<PrototypeAST
> ParseExtern() {
368 getNextToken(); // eat extern.
369 return ParsePrototype();
372 //===----------------------------------------------------------------------===//
374 //===----------------------------------------------------------------------===//
376 static void HandleDefinition() {
377 if (ParseDefinition()) {
378 fprintf(stderr
, "Parsed a function definition.\n");
380 // Skip token for error recovery.
385 static void HandleExtern() {
387 fprintf(stderr
, "Parsed an extern\n");
389 // Skip token for error recovery.
394 static void HandleTopLevelExpression() {
395 // Evaluate a top-level expression into an anonymous function.
396 if (ParseTopLevelExpr()) {
397 fprintf(stderr
, "Parsed a top-level expr\n");
399 // Skip token for error recovery.
404 /// top ::= definition | external | expression | ';'
405 static void MainLoop() {
407 fprintf(stderr
, "ready> ");
411 case ';': // ignore top-level semicolons.
421 HandleTopLevelExpression();
427 //===----------------------------------------------------------------------===//
429 //===----------------------------------------------------------------------===//
432 // Install standard binary operators.
433 // 1 is lowest precedence.
434 BinopPrecedence
['<'] = 10;
435 BinopPrecedence
['+'] = 20;
436 BinopPrecedence
['-'] = 20;
437 BinopPrecedence
['*'] = 40; // highest.
439 // Prime the first token.
440 fprintf(stderr
, "ready> ");
443 // Run the main "interpreter loop" now.