10 //===----------------------------------------------------------------------===//
12 //===----------------------------------------------------------------------===//
14 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
15 // of these for known things.
28 static std::string IdentifierStr
; // Filled in if tok_identifier
29 static double NumVal
; // Filled in if tok_number
31 /// gettok - Return the next token from standard input.
33 static int LastChar
= ' ';
35 // Skip any whitespace.
36 while (isspace(LastChar
))
39 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
40 IdentifierStr
= LastChar
;
41 while (isalnum((LastChar
= getchar())))
42 IdentifierStr
+= LastChar
;
44 if (IdentifierStr
== "def")
46 if (IdentifierStr
== "extern")
48 return tok_identifier
;
51 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
56 } while (isdigit(LastChar
) || LastChar
== '.');
58 NumVal
= strtod(NumStr
.c_str(), nullptr);
62 if (LastChar
== '#') {
63 // Comment until end of line.
66 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
72 // Check for end of file. Don't eat the EOF.
76 // Otherwise, just return the character as its ascii value.
77 int ThisChar
= LastChar
;
82 //===----------------------------------------------------------------------===//
83 // Abstract Syntax Tree (aka Parse Tree)
84 //===----------------------------------------------------------------------===//
88 /// ExprAST - Base class for all expression nodes.
91 virtual ~ExprAST() = default;
94 /// NumberExprAST - Expression class for numeric literals like "1.0".
95 class NumberExprAST
: public ExprAST
{
99 NumberExprAST(double Val
) : Val(Val
) {}
102 /// VariableExprAST - Expression class for referencing a variable, like "a".
103 class VariableExprAST
: public ExprAST
{
107 VariableExprAST(const std::string
&Name
) : Name(Name
) {}
110 /// BinaryExprAST - Expression class for a binary operator.
111 class BinaryExprAST
: public ExprAST
{
113 std::unique_ptr
<ExprAST
> LHS
, RHS
;
116 BinaryExprAST(char Op
, std::unique_ptr
<ExprAST
> LHS
,
117 std::unique_ptr
<ExprAST
> RHS
)
118 : Op(Op
), LHS(std::move(LHS
)), RHS(std::move(RHS
)) {}
121 /// CallExprAST - Expression class for function calls.
122 class CallExprAST
: public ExprAST
{
124 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
127 CallExprAST(const std::string
&Callee
,
128 std::vector
<std::unique_ptr
<ExprAST
>> Args
)
129 : Callee(Callee
), Args(std::move(Args
)) {}
132 /// PrototypeAST - This class represents the "prototype" for a function,
133 /// which captures its name, and its argument names (thus implicitly the number
134 /// of arguments the function takes).
137 std::vector
<std::string
> Args
;
140 PrototypeAST(const std::string
&Name
, std::vector
<std::string
> Args
)
141 : Name(Name
), Args(std::move(Args
)) {}
143 const std::string
&getName() const { return Name
; }
146 /// FunctionAST - This class represents a function definition itself.
148 std::unique_ptr
<PrototypeAST
> Proto
;
149 std::unique_ptr
<ExprAST
> Body
;
152 FunctionAST(std::unique_ptr
<PrototypeAST
> Proto
,
153 std::unique_ptr
<ExprAST
> Body
)
154 : Proto(std::move(Proto
)), Body(std::move(Body
)) {}
157 } // end anonymous namespace
159 //===----------------------------------------------------------------------===//
161 //===----------------------------------------------------------------------===//
163 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
164 /// token the parser is looking at. getNextToken reads another token from the
165 /// lexer and updates CurTok with its results.
167 static int getNextToken() { return CurTok
= gettok(); }
169 /// BinopPrecedence - This holds the precedence for each binary operator that is
171 static std::map
<char, int> BinopPrecedence
;
173 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
174 static int GetTokPrecedence() {
175 if (!isascii(CurTok
))
178 // Make sure it's a declared binop.
179 int TokPrec
= BinopPrecedence
[CurTok
];
185 /// LogError* - These are little helper functions for error handling.
186 std::unique_ptr
<ExprAST
> LogError(const char *Str
) {
187 fprintf(stderr
, "Error: %s\n", Str
);
190 std::unique_ptr
<PrototypeAST
> LogErrorP(const char *Str
) {
195 static std::unique_ptr
<ExprAST
> ParseExpression();
197 /// numberexpr ::= number
198 static std::unique_ptr
<ExprAST
> ParseNumberExpr() {
199 auto Result
= std::make_unique
<NumberExprAST
>(NumVal
);
200 getNextToken(); // consume the number
201 return std::move(Result
);
204 /// parenexpr ::= '(' expression ')'
205 static std::unique_ptr
<ExprAST
> ParseParenExpr() {
206 getNextToken(); // eat (.
207 auto V
= ParseExpression();
212 return LogError("expected ')'");
213 getNextToken(); // eat ).
219 /// ::= identifier '(' expression* ')'
220 static std::unique_ptr
<ExprAST
> ParseIdentifierExpr() {
221 std::string IdName
= IdentifierStr
;
223 getNextToken(); // eat identifier.
225 if (CurTok
!= '(') // Simple variable ref.
226 return std::make_unique
<VariableExprAST
>(IdName
);
229 getNextToken(); // eat (
230 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
233 if (auto Arg
= ParseExpression())
234 Args
.push_back(std::move(Arg
));
242 return LogError("Expected ')' or ',' in argument list");
250 return std::make_unique
<CallExprAST
>(IdName
, std::move(Args
));
254 /// ::= identifierexpr
257 static std::unique_ptr
<ExprAST
> ParsePrimary() {
260 return LogError("unknown token when expecting an expression");
262 return ParseIdentifierExpr();
264 return ParseNumberExpr();
266 return ParseParenExpr();
271 /// ::= ('+' primary)*
272 static std::unique_ptr
<ExprAST
> ParseBinOpRHS(int ExprPrec
,
273 std::unique_ptr
<ExprAST
> LHS
) {
274 // If this is a binop, find its precedence.
276 int TokPrec
= GetTokPrecedence();
278 // If this is a binop that binds at least as tightly as the current binop,
279 // consume it, otherwise we are done.
280 if (TokPrec
< ExprPrec
)
283 // Okay, we know this is a binop.
285 getNextToken(); // eat binop
287 // Parse the primary expression after the binary operator.
288 auto RHS
= ParsePrimary();
292 // If BinOp binds less tightly with RHS than the operator after RHS, let
293 // the pending operator take RHS as its LHS.
294 int NextPrec
= GetTokPrecedence();
295 if (TokPrec
< NextPrec
) {
296 RHS
= ParseBinOpRHS(TokPrec
+ 1, std::move(RHS
));
303 std::make_unique
<BinaryExprAST
>(BinOp
, std::move(LHS
), std::move(RHS
));
308 /// ::= primary binoprhs
310 static std::unique_ptr
<ExprAST
> ParseExpression() {
311 auto LHS
= ParsePrimary();
315 return ParseBinOpRHS(0, std::move(LHS
));
319 /// ::= id '(' id* ')'
320 static std::unique_ptr
<PrototypeAST
> ParsePrototype() {
321 if (CurTok
!= tok_identifier
)
322 return LogErrorP("Expected function name in prototype");
324 std::string FnName
= IdentifierStr
;
328 return LogErrorP("Expected '(' in prototype");
330 std::vector
<std::string
> ArgNames
;
331 while (getNextToken() == tok_identifier
)
332 ArgNames
.push_back(IdentifierStr
);
334 return LogErrorP("Expected ')' in prototype");
337 getNextToken(); // eat ')'.
339 return std::make_unique
<PrototypeAST
>(FnName
, std::move(ArgNames
));
342 /// definition ::= 'def' prototype expression
343 static std::unique_ptr
<FunctionAST
> ParseDefinition() {
344 getNextToken(); // eat def.
345 auto Proto
= ParsePrototype();
349 if (auto E
= ParseExpression())
350 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
354 /// toplevelexpr ::= expression
355 static std::unique_ptr
<FunctionAST
> ParseTopLevelExpr() {
356 if (auto E
= ParseExpression()) {
357 // Make an anonymous proto.
358 auto Proto
= std::make_unique
<PrototypeAST
>("__anon_expr",
359 std::vector
<std::string
>());
360 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
365 /// external ::= 'extern' prototype
366 static std::unique_ptr
<PrototypeAST
> ParseExtern() {
367 getNextToken(); // eat extern.
368 return ParsePrototype();
371 //===----------------------------------------------------------------------===//
373 //===----------------------------------------------------------------------===//
375 static void HandleDefinition() {
376 if (ParseDefinition()) {
377 fprintf(stderr
, "Parsed a function definition.\n");
379 // Skip token for error recovery.
384 static void HandleExtern() {
386 fprintf(stderr
, "Parsed an extern\n");
388 // Skip token for error recovery.
393 static void HandleTopLevelExpression() {
394 // Evaluate a top-level expression into an anonymous function.
395 if (ParseTopLevelExpr()) {
396 fprintf(stderr
, "Parsed a top-level expr\n");
398 // Skip token for error recovery.
403 /// top ::= definition | external | expression | ';'
404 static void MainLoop() {
406 fprintf(stderr
, "ready> ");
410 case ';': // ignore top-level semicolons.
420 HandleTopLevelExpression();
426 //===----------------------------------------------------------------------===//
428 //===----------------------------------------------------------------------===//
431 // Install standard binary operators.
432 // 1 is lowest precedence.
433 BinopPrecedence
['<'] = 10;
434 BinopPrecedence
['+'] = 20;
435 BinopPrecedence
['-'] = 20;
436 BinopPrecedence
['*'] = 40; // highest.
438 // Prime the first token.
439 fprintf(stderr
, "ready> ");
442 // Run the main "interpreter loop" now.