Added support for forwards.
1 /* vim: set ts=4 sw=4 tw=99 et:
3 * Copyright (C) 2012 David Anderson
5 * This file is part of JITCraft.
7 * JITCraft is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License as published by the Free
9 * Software Foundation, either version 3 of the License, or (at your option)
12 * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
13 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with
17 * JITCraft. If not, see http://www.gnu.org/licenses/.
21 #include "FixedArray.h"
28 Parser::Parser(Zone *zone, CompileContext &cc, const char *stream, size_t length)
32 scanner_(cc, stream, length),
36 unbound_ = new (pool_) PoolList<NameProxy *>();
40 Parser::match(TokenKind kind)
42 if (scanner_.peek() != kind)
49 Parser::matchSemicolon()
51 return expect(TOK_SEMICOLON);
55 Parser::expect(TokenKind kind)
57 TokenKind got = scanner_.scan();
60 cc_.reportError(scanner_.begin(), Message_WrongToken, TokenNames[kind], TokenNames[got]);
65 Parser::enterScope(Scope::Kind kind)
67 scope_ = new (pool_) Scope(pool_, kind, scope_);
68 if (!scope_->initialize())
74 Parser::bind(Handle<String> name)
76 BoundName *bound = scope_->lookup(name);
77 NameProxy *proxy = new (pool_) NameProxy(scanner_.begin(), name, bound);
78 if (!bound && !unbound_->append(proxy))
84 Parser::matchName(String **name, TokenKind kind)
86 assert(kind == TOK_NAME || kind == TOK_LABEL);
90 *name = zone_->makeSymbol(scanner_.literal(), scanner_.literal_length());
97 if (!expect(TOK_NAME))
99 return zone_->makeSymbol(scanner_.literal(), scanner_.literal_length());
103 Parser::redeclarationError(BoundName *other)
105 cc_.reportError(scanner_.begin(), Message_RedeclaredName, other->name()->chars(),
106 other->pos().line, other->pos().col);
112 TokenKind kind = scanner_.peek();
116 Local<String> name(zone_, expectName());
122 case TOK_FLOAT_LITERAL:
125 double value = Scanner::ParseDouble(scanner_.literal());
126 return new (pool_) FloatLiteral(scanner_.begin(), value);
129 case TOK_INTEGER_LITERAL:
132 int value = atoi(scanner_.literal());
133 return new (pool_) IntegerLiteral(scanner_.begin(), value);
136 case TOK_STRING_LITERAL:
139 Local<ByteArray> array(zone_, ByteArray::New(zone_, scanner_.literal_length() + 1));
142 memcpy(array->raw(), scanner_.literal(), scanner_.literal_length() + 1);
143 return new (pool_) StringLiteral(scanner_.begin(), array);
148 if (kind != TOK_ERROR)
149 cc_.reportError(scanner_.begin(), Message_ExpectedExpression, TokenNames[kind]);
158 switch (scanner_.peek()) {
162 Expression *expr = expression();
165 if (!expect(TOK_RPAREN))
176 Parser::call(Expression *callee)
178 ExpressionList *arguments = new (pool_) ExpressionList();
180 SourcePosition pos = scanner_.begin();
183 if (!match(TOK_RPAREN)) {
185 Expression *expr = expression();
189 if (!arguments->append(expr))
192 if (!match(TOK_COMMA))
196 if (!expect(TOK_RPAREN))
200 return new (pool_) CallExpression(pos, callee, arguments);
204 Parser::index(Expression *left)
206 expect(TOK_LBRACKET);
208 SourcePosition pos = scanner_.begin();
209 Expression *expr = expression();
213 if (!expect(TOK_RBRACKET))
216 return new (pool_) IndexExpression(pos, left, expr);
222 Expression *expr = prefix();
227 switch (scanner_.peek()) {
249 TokenKind token = scanner_.peek();
251 SourcePosition pos = scanner_.begin();
257 Expression *expr = expression();
261 return new (pool_) IncDecExpression(pos, token, expr, false);
268 Expression *expr = primary();
270 token = scanner_.peek();
271 if (token == TOK_INCREMENT || token == TOK_DECREMENT) {
273 return new (pool_) IncDecExpression(pos, token, expr, true);
280 Parser::multiplication()
282 Expression *left = unary();
284 if (!match(TOK_SLASH) && !match(TOK_STAR))
286 SourcePosition pos = scanner_.begin();
287 TokenKind kind = scanner_.last();
288 Expression *right = unary();
291 left = new (pool_) BinaryExpression(pos, kind, left, right);
299 Expression *left = multiplication();
301 if (!match(TOK_PLUS) && !match(TOK_MINUS))
303 SourcePosition pos = scanner_.begin();
304 TokenKind kind = scanner_.last();
305 Expression *right = multiplication();
308 left = new (pool_) BinaryExpression(pos, kind, left, right);
316 Expression *left = addition();
318 if (!match(TOK_SHL) && !match(TOK_SHR) && !match(TOK_USHR))
320 SourcePosition pos = scanner_.begin();
321 TokenKind kind = scanner_.last();
322 Expression *right = addition();
325 left = new (pool_) BinaryExpression(pos, kind, left, right);
333 Expression *left = shift();
335 if (!match(TOK_BITAND))
337 SourcePosition pos = scanner_.begin();
338 Expression *right = shift();
341 left = new (pool_) BinaryExpression(pos, TOK_BITAND, left, right);
349 Expression *left = bitand_();
351 if (!match(TOK_BITXOR))
353 SourcePosition pos = scanner_.begin();
354 Expression *right = shift();
357 left = new (pool_) BinaryExpression(pos, TOK_BITXOR, left, right);
365 Expression *left = bitxor();
367 if (!match(TOK_BITOR))
369 SourcePosition pos = scanner_.begin();
370 Expression *right = shift();
373 left = new (pool_) BinaryExpression(pos, TOK_BITOR, left, right);
381 Expression *left = bitor_();
383 TokenKind kind = scanner_.peek();
384 if (kind < TOK_LT || kind > TOK_GE)
387 SourcePosition pos = scanner_.begin();
388 Expression *right = shift();
391 left = new (pool_) BinaryExpression(pos, kind, left, right);
399 Expression *left = relational();
401 if (!match(TOK_EQUALS) && !match(TOK_NOTEQUALS))
403 TokenKind kind = scanner_.last();
404 SourcePosition pos = scanner_.begin();
405 Expression *right = relational();
408 left = new (pool_) BinaryExpression(pos, kind, left, right);
416 Expression *left = equals();
418 TokenKind token = scanner_.peek();
419 if (token != TOK_ASSIGN && (token < TOK_ASSIGN_ADD || token > TOK_ASSIGN_SHL))
422 SourcePosition pos = scanner_.begin();
423 Expression *expr = equals();
427 left = new (pool_) Assignment(pos, token, left, expr);
441 SourcePosition pos = scanner_.begin();
444 if (!expect(TOK_LPAREN))
447 Expression *condition = expression();
451 if (!expect(TOK_RPAREN))
454 // Inside a loop, we force the creation of a scope object. Normally, we
455 // will cull scopes if they have no variables. However inside a loop,
456 // function calls that take references may compute a LIFO object, and to
457 // avoid temporarily leaking many such objects, we ensure that a scope
458 // is present so a LIFO slot can be allocated.
459 if (!enterScope(Scope::BLOCK))
463 if (scanner_.peek() == TOK_LBRACE)
464 body = block(scope_);
466 body = localStatement();
470 scope_ = scope_->enclosing();
471 return new (pool_) WhileStatement(pos, TOK_WHILE, condition, body);
477 SourcePosition pos = scanner_.begin();
480 // See the comment in ::while_() as to why we force a scope.
481 if (!enterScope(Scope::BLOCK))
485 if (scanner_.peek() == TOK_LBRACE)
486 body = block(scope_);
488 body = localStatement();
492 scope_ = scope_->enclosing();
494 if (!expect(TOK_WHILE))
497 if (!expect(TOK_LPAREN))
499 Expression *condition = expression();
502 if (!expect(TOK_RPAREN))
505 return new (pool_) WhileStatement(pos, TOK_DO, condition, body);
509 Parser::forStatement()
511 SourcePosition pos = scanner_.begin();
513 if (!expect(TOK_LPAREN))
516 Statement *decl = NULL;
517 if (!match(TOK_SEMICOLON)) {
518 if (scanner_.peek() == TOK_NEW) {
519 if (!enterScope(Scope::BLOCK))
521 if ((decl = variableDeclaration()) == NULL)
524 if ((decl = expressionStatement()) == NULL)
527 if (!expect(TOK_SEMICOLON))
531 Expression *condition = NULL;
532 if (!match(TOK_SEMICOLON)) {
533 if ((condition = expression()) == NULL)
535 if (!expect(TOK_SEMICOLON))
539 Statement *update = NULL;
540 if (!match(TOK_RPAREN)) {
541 if ((update = expressionStatement()) == NULL)
543 if (!expect(TOK_RPAREN))
547 // See the comment in ::while_() as to why we force a scope.
548 if (!enterScope(Scope::BLOCK))
552 if (scanner_.peek() == TOK_LBRACE)
553 body = block(scope_);
555 body = localStatement();
559 scope_ = scope_->enclosing();
561 Scope *declScope = NULL;
562 if (decl && decl->isVariableDeclaration()) {
563 declScope = scope_->unlinkIfEmpty();
564 scope_ = scope_->enclosing();
566 return new (pool_) ForStatement(pos, declScope, decl, condition, update, body);
569 VariableDeclaration *
570 Parser::variableDeclaration()
572 if (!expect(TOK_NEW))
575 Local<String> tag(zone_);
576 if (matchName(tag.ref(), TOK_LABEL) && !tag)
579 Local<String> name(zone_, expectName());
583 if (BoundName *other = scope_->localLookup(name)) {
584 redeclarationError(other);
588 Variable *var = scope_->declareVariable(name, scanner_.begin());
592 ExpressionList *postDimensions = NULL;
593 if (scanner_.peek() == TOK_LBRACKET) {
594 postDimensions = new (pool_) ExpressionList();
595 while (match(TOK_LBRACKET)) {
596 Expression *dim = expression();
600 if (!expect(TOK_RBRACKET))
603 if (!postDimensions->append(dim))
608 Expression *expr = NULL;
609 if (match(TOK_ASSIGN)) {
610 if ((expr = expression()) == NULL)
614 return new (pool_) VariableDeclaration(var->pos(), var, tag, postDimensions, expr);
618 Parser::returnStatement()
620 SourcePosition pos = scanner_.begin();
621 if (!expect(TOK_RETURN))
624 Expression *expr = expression();
628 return new (pool_) ReturnStatement(pos, expr);
632 Parser::expressionStatement()
634 Expression *left = assignment();
638 return new (pool_) ExpressionStatement(left);
642 Parser::block(Scope *scope)
644 if (!expect(TOK_LBRACE))
647 SourcePosition pos = scanner_.begin();
648 if (!scope && !enterScope(Scope::BLOCK))
651 StatementList *statements = new (pool_) StatementList();
652 while (!match(TOK_RBRACE)) {
653 Statement *statement = localStatement();
654 if (statement == NULL)
656 if (!statements->append(statement))
661 scope = scope_->unlinkIfEmpty();
662 scope_ = scope_->enclosing();
664 BlockStatement *block = new (pool_) BlockStatement(pos, scope, statements);
673 SourcePosition pos = scanner_.begin();
674 if (!expect(TOK_LPAREN))
677 Expression *cond = expression();
681 if (!expect(TOK_RPAREN))
684 Statement *ifTrue = localStatement();
688 IfStatement *outer = new (pool_) IfStatement(pos, cond, ifTrue);
690 IfStatement *last = outer;
691 while (match(TOK_ELSE)) {
692 if (!match(TOK_IF)) {
693 Statement *ifFalse = localStatement();
697 last->setIfFalse(ifFalse);
704 SourcePosition pos = scanner_.begin();
705 if (!expect(TOK_LPAREN))
708 Expression *otherCond = expression();
712 if (!expect(TOK_RPAREN))
715 Statement *otherIfTrue = localStatement();
719 IfStatement *inner = new (pool_) IfStatement(pos, otherCond, otherIfTrue);
720 last->setIfFalse(inner);
728 Parser::localStatement()
730 Statement *statement = NULL;
732 // Statements which must be followed by a semicolon will break out of the
733 // switch. If they may end in BlockStatements, they'll immediately return.
735 switch (scanner_.peek()) {
737 if ((statement = variableDeclaration()) == NULL)
742 return forStatement();
749 statement = new (pool_) BreakStatement(scanner_.begin());
754 statement = new (pool_) ContinueStatement(scanner_.begin());
758 if ((statement = do_()) == NULL)
763 if ((statement = returnStatement()) == NULL)
768 if ((statement = enum_()) == NULL)
783 if ((statement = expressionStatement()) == NULL)
787 if (!expect(TOK_SEMICOLON))
798 SourcePosition pos = scanner_.begin();
800 Local<String> name(zone_);
801 if (matchName(name.ref())) {
805 if (BoundName *other = scope_->localLookup(name)) {
806 redeclarationError(other);
810 if (!scope_->declareEnum(name, scanner_.begin()))
814 EnumStatement::EntryList *entries = new (pool_) EnumStatement::EntryList();
816 if (!expect(TOK_LBRACE))
820 if (scanner_.peek() == TOK_RBRACE)
823 Local<String> name(zone_, expectName());
827 if (BoundName *other = scope_->localLookup(name)) {
828 redeclarationError(other);
832 NamedConstant *constant = scope_->declareConstant(name, scanner_.begin());
836 Expression *expr = NULL;
837 if (match(TOK_ASSIGN)) {
838 if ((expr = expression()) == NULL)
842 if (!entries->append(EnumStatement::Entry(constant, expr)))
844 } while (match(TOK_COMMA));
845 if (!expect(TOK_RBRACE))
848 return new (pool_) EnumStatement(pos, name, entries);
852 Parser::function(TokenKind token)
854 Local<String> name(zone_, expectName());
858 SourcePosition pos = scanner_.begin();
860 // The function name goes into the outer (global) scope.
861 assert(!scope_->enclosing());
864 if (BoundName *other = scope_->localLookup(name)) {
865 // We allow a redeclaration if the new type is a public, and the old
866 // type was a forward. However, the forward must come first.
867 if (other->kind() != BoundName::FUNCTION) {
868 redeclarationError(other);
872 fun = other->toNamedFunction();
873 if (!fun->isForward() || token != TOK_PUBLIC) {
874 redeclarationError(other);
878 // We've got the same name, but the original is a forward, so let it
879 // slide and re-use the original declaration.
880 fun->setImplemented(scanner_.begin());
882 fun = scope_->declareFunction(name, scanner_.begin(), token);
887 Scope *scope = enterScope(Scope::FUNCTION);
891 ParameterList *parameters = new (pool_) ParameterList();
893 if (!expect(TOK_LPAREN))
895 if (!match(TOK_RPAREN)) {
897 bool ref = match(TOK_AMPERSAND);
899 Local<String> name(zone_, expectName());
903 if (BoundName *other = scope_->localLookup(name)) {
904 redeclarationError(other);
907 Variable *arg = scope_->declareArgument(name, scanner_.begin());
911 Local<String> tag(zone_);
912 Parameter *parameter = new (pool_) Parameter(arg, tag, ref);
913 if (!parameters->append(parameter))
916 if (!match(TOK_COMMA))
919 if (!expect(TOK_RPAREN))
923 Statement *body = NULL;
924 if (token != TOK_FORWARD) {
930 scope_ = scope_->enclosing();
931 return new (pool_) FunctionStatement(pos, scope, fun, body, parameters);
937 StatementList *statements = new (pool_) StatementList();
939 if (!enterScope(Scope::GLOBAL))
943 Statement *statement = NULL;
945 switch (scanner_.peek()) {
953 if ((statement = function(TOK_NAME)) == NULL)
960 TokenKind kind = scanner_.scan();
961 if ((statement = function(kind)) == NULL)
963 if (kind == TOK_FORWARD && !matchSemicolon())
969 if ((statement = enum_()) == NULL)
971 if (!matchSemicolon())
976 cc_.reportError(scanner_.begin(), Message_ExpectedGlobal);
983 if (!statements->append(statement))
987 return new (pool_) ParseTree(scope_, statements, unbound_);
990 class AstPrinter : public AstVisitor
997 for (size_t i = 0; i < level_; i++)
1008 AstPrinter(FILE *fp)
1014 void visit(NameProxy *name) {
1016 fprintf(fp_, "[ NameProxy (%s)%s\n", name->name()->chars(),
1017 (name->binding() ? "" : " unbound"));
1019 void visit(CallExpression *node) {
1021 fprintf(fp_, "[ CallExpression\n");
1023 node->callee()->accept(this);
1024 for (size_t i = 0; i < node->arguments()->length(); i++)
1025 node->arguments()->at(i)->accept(this);
1028 void visit(FunctionStatement *node) {
1030 fprintf(fp_, "[ FunctionStatement (%s)\n", node->fun()->name()->chars());
1033 node->body()->accept(this);
1036 void visit(ExpressionStatement *node) {
1038 fprintf(fp_, "[ ExpressionStatement\n");
1040 node->expression()->accept(this);
1043 void visit(Assignment *node) {
1045 fprintf(fp_, "[ Assignment\n");
1047 node->lvalue()->accept(this);
1048 node->expression()->accept(this);
1051 void visit(BinaryExpression *node) {
1053 fprintf(fp_, "[ BinaryExpression (%s)\n", TokenNames[node->token()]);
1055 node->left()->accept(this);
1056 node->right()->accept(this);
1059 void visit(ReturnStatement *node) {
1061 fprintf(fp_, "[ ReturnStatement\n");
1063 node->expression()->accept(this);
1066 void visit(ForStatement *node) {
1068 fprintf(fp_, "[ ForStatement\n");
1070 if (node->initialization())
1071 node->initialization()->accept(this);
1072 if (node->condition())
1073 node->condition()->accept(this);
1075 node->update()->accept(this);
1076 node->body()->accept(this);
1079 void visit(BlockStatement *node) {
1081 fprintf(fp_, "[ BlockStatement\n");
1083 for (size_t i = 0; i < node->statements()->length(); i++)
1084 node->statements()->at(i)->accept(this);
1087 void visit(VariableDeclaration *node) {
1089 fprintf(fp_, "[ VariableDeclaration (%s)\n", node->variable()->name()->chars());
1091 if (node->initialization())
1092 node->initialization()->accept(this);
1095 void visit(IntegerLiteral *node) {
1097 fprintf(fp_, "[ IntegerLiteral (%d)\n", node->value());
1099 void visit(FloatLiteral *node) {
1101 fprintf(fp_, "[ FloatLiteral (%f)\n", node->value());
1103 void visit(IfStatement *node) {
1105 fprintf(fp_, "[ IfStatement\n");
1107 node->ifTrue()->accept(this);
1108 if (node->ifFalse())
1109 node->ifFalse()->accept(this);
1112 void visit(IndexExpression *node) {
1114 fprintf(fp_, "[ IndexExpression\n");
1116 node->left()->accept(this);
1117 node->right()->accept(this);
1120 void visit(EnumStatement *node) {
1122 fprintf(fp_, "[ EnumStatement (%s)\n", node->name() ? node->name()->chars() : "<anonymous>");
1124 for (size_t i = 0; i < node->entries()->length(); i++) {
1126 fprintf(fp_, "%s =\n", node->entries()->at(i).name->name()->chars());
1127 if (node->entries()->at(i).expr) {
1129 node->entries()->at(i).expr->accept(this);
1135 void visit(WhileStatement *node) {
1137 fprintf(fp_, "[ WhileStatement (%s)\n",
1138 (node->token() == TOK_DO) ? "do" : "while");
1140 if (node->token() == TOK_DO) {
1141 node->condition()->accept(this);
1142 node->body()->accept(this);
1144 node->condition()->accept(this);
1145 node->body()->accept(this);
1149 void visit(BreakStatement *node) {
1151 fprintf(fp_, "[ BreakStatement\n");
1153 void visit(ContinueStatement *node) {
1155 fprintf(fp_, "[ ContinueStatement\n");
1157 void visit(StringLiteral *node) {
1159 fprintf(fp_, "[ StringLiteral\n");
1161 void visit(IncDecExpression *node) {
1163 fprintf(fp_, "[ IncDecExpression (postfix=%d)\n", node->postfix());
1165 node->expression()->accept(this);
1171 ParseTree::dump(FILE *fp)
1173 AstPrinter printer(fp);
1175 for (size_t i = 0; i < statements_->length(); i++)
1176 statements_->at(i)->accept(&printer);