Added support for modulo operator.
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();
260 return new (pool_) IncDecExpression(pos, token, expr, false);
268 Expression *expr = expression();
271 return new (pool_) UnaryExpression(pos, token, expr);
278 Expression *expr = primary();
280 token = scanner_.peek();
281 if (token == TOK_INCREMENT || token == TOK_DECREMENT) {
283 return new (pool_) IncDecExpression(pos, token, expr, true);
290 Parser::multiplication()
292 Expression *left = unary();
294 if (!match(TOK_SLASH) && !match(TOK_STAR) && !match(TOK_PERCENT))
296 SourcePosition pos = scanner_.begin();
297 TokenKind kind = scanner_.last();
298 Expression *right = unary();
301 left = new (pool_) BinaryExpression(pos, kind, left, right);
309 Expression *left = multiplication();
311 if (!match(TOK_PLUS) && !match(TOK_MINUS))
313 SourcePosition pos = scanner_.begin();
314 TokenKind kind = scanner_.last();
315 Expression *right = multiplication();
318 left = new (pool_) BinaryExpression(pos, kind, left, right);
326 Expression *left = addition();
328 if (!match(TOK_SHL) && !match(TOK_SHR) && !match(TOK_USHR))
330 SourcePosition pos = scanner_.begin();
331 TokenKind kind = scanner_.last();
332 Expression *right = addition();
335 left = new (pool_) BinaryExpression(pos, kind, left, right);
343 Expression *left = shift();
345 if (!match(TOK_BITAND))
347 SourcePosition pos = scanner_.begin();
348 Expression *right = shift();
351 left = new (pool_) BinaryExpression(pos, TOK_BITAND, left, right);
359 Expression *left = bitand_();
361 if (!match(TOK_BITXOR))
363 SourcePosition pos = scanner_.begin();
364 Expression *right = shift();
367 left = new (pool_) BinaryExpression(pos, TOK_BITXOR, left, right);
375 Expression *left = bitxor();
377 if (!match(TOK_BITOR))
379 SourcePosition pos = scanner_.begin();
380 Expression *right = bitxor();
383 left = new (pool_) BinaryExpression(pos, TOK_BITOR, left, right);
391 Expression *left = bitor_();
393 TokenKind kind = scanner_.peek();
394 if (kind < TOK_LT || kind > TOK_GE)
397 SourcePosition pos = scanner_.begin();
398 Expression *right = shift();
401 left = new (pool_) BinaryExpression(pos, kind, left, right);
409 Expression *left = relational();
411 if (!match(TOK_EQUALS) && !match(TOK_NOTEQUALS))
413 TokenKind kind = scanner_.last();
414 SourcePosition pos = scanner_.begin();
415 Expression *right = relational();
418 left = new (pool_) BinaryExpression(pos, kind, left, right);
426 Expression *left = equals();
430 SourcePosition pos = scanner_.begin();
431 Expression *right = equals();
434 left = new (pool_) BinaryExpression(pos, TOK_AND, left, right);
442 Expression *left = and_();
446 SourcePosition pos = scanner_.begin();
447 Expression *right = and_();
450 left = new (pool_) BinaryExpression(pos, TOK_OR, left, right);
458 Expression *left = or_();
460 TokenKind token = scanner_.peek();
461 if (token != TOK_ASSIGN && (token < TOK_ASSIGN_ADD || token > TOK_ASSIGN_SHL))
464 SourcePosition pos = scanner_.begin();
465 Expression *expr = or_();
469 left = new (pool_) Assignment(pos, token, left, expr);
483 SourcePosition pos = scanner_.begin();
486 if (!expect(TOK_LPAREN))
489 Expression *condition = expression();
493 if (!expect(TOK_RPAREN))
496 // Inside a loop, we force the creation of a scope object. Normally, we
497 // will cull scopes if they have no variables. However inside a loop,
498 // function calls that take references may compute a LIFO object, and to
499 // avoid temporarily leaking many such objects, we ensure that a scope
500 // is present so a LIFO slot can be allocated.
501 if (!enterScope(Scope::BLOCK))
505 if (scanner_.peek() == TOK_LBRACE)
506 body = block(scope_);
508 body = localStatement();
512 scope_ = scope_->enclosing();
513 return new (pool_) WhileStatement(pos, TOK_WHILE, condition, body);
519 SourcePosition pos = scanner_.begin();
522 // See the comment in ::while_() as to why we force a scope.
523 if (!enterScope(Scope::BLOCK))
527 if (scanner_.peek() == TOK_LBRACE)
528 body = block(scope_);
530 body = localStatement();
534 scope_ = scope_->enclosing();
536 if (!expect(TOK_WHILE))
539 if (!expect(TOK_LPAREN))
541 Expression *condition = expression();
544 if (!expect(TOK_RPAREN))
547 return new (pool_) WhileStatement(pos, TOK_DO, condition, body);
551 Parser::forStatement()
553 SourcePosition pos = scanner_.begin();
555 if (!expect(TOK_LPAREN))
558 Statement *decl = NULL;
559 if (!match(TOK_SEMICOLON)) {
560 if (scanner_.peek() == TOK_NEW) {
561 if (!enterScope(Scope::BLOCK))
563 if ((decl = variableDeclaration()) == NULL)
566 if ((decl = expressionStatement()) == NULL)
569 if (!expect(TOK_SEMICOLON))
573 Expression *condition = NULL;
574 if (!match(TOK_SEMICOLON)) {
575 if ((condition = expression()) == NULL)
577 if (!expect(TOK_SEMICOLON))
581 Statement *update = NULL;
582 if (!match(TOK_RPAREN)) {
583 if ((update = expressionStatement()) == NULL)
585 if (!expect(TOK_RPAREN))
589 // See the comment in ::while_() as to why we force a scope.
590 if (!enterScope(Scope::BLOCK))
594 if (scanner_.peek() == TOK_LBRACE)
595 body = block(scope_);
597 body = localStatement();
601 scope_ = scope_->enclosing();
603 Scope *declScope = NULL;
604 if (decl && decl->isVariableDeclaration()) {
605 declScope = scope_->unlinkIfEmpty();
606 scope_ = scope_->enclosing();
608 return new (pool_) ForStatement(pos, declScope, decl, condition, update, body);
611 VariableDeclaration *
612 Parser::variableDeclaration()
614 if (!expect(TOK_NEW))
617 Local<String> tag(zone_);
618 if (matchName(tag.ref(), TOK_LABEL) && !tag)
621 Local<String> name(zone_, expectName());
625 if (BoundName *other = scope_->localLookup(name)) {
626 redeclarationError(other);
630 Variable *var = scope_->declareVariable(name, scanner_.begin());
634 ExpressionList *postDimensions = NULL;
635 if (scanner_.peek() == TOK_LBRACKET) {
636 postDimensions = new (pool_) ExpressionList();
637 while (match(TOK_LBRACKET)) {
638 Expression *dim = expression();
642 if (!expect(TOK_RBRACKET))
645 if (!postDimensions->append(dim))
650 Expression *expr = NULL;
651 if (match(TOK_ASSIGN)) {
652 if ((expr = expression()) == NULL)
656 return new (pool_) VariableDeclaration(var->pos(), var, tag, postDimensions, expr);
660 Parser::returnStatement()
662 SourcePosition pos = scanner_.begin();
663 if (!expect(TOK_RETURN))
666 Expression *expr = NULL;
667 if (scanner_.peek() != TOK_SEMICOLON) {
668 if ((expr = expression()) == NULL)
671 // We only care about non-void returns when determining whether a
672 // tagless function is non-void.
673 encounteredReturn_ = true;
676 return new (pool_) ReturnStatement(pos, expr);
680 Parser::expressionStatement()
682 Expression *left = assignment();
686 return new (pool_) ExpressionStatement(left);
690 Parser::block(Scope *scope)
692 if (!expect(TOK_LBRACE))
695 SourcePosition pos = scanner_.begin();
696 if (!scope && !enterScope(Scope::BLOCK))
699 StatementList *statements = new (pool_) StatementList();
700 while (!match(TOK_RBRACE)) {
701 Statement *statement = localStatement();
702 if (statement == NULL)
704 if (!statements->append(statement))
709 scope = scope_->unlinkIfEmpty();
710 scope_ = scope_->enclosing();
712 BlockStatement *block = new (pool_) BlockStatement(pos, scope, statements);
721 SourcePosition pos = scanner_.begin();
722 if (!expect(TOK_LPAREN))
725 Expression *cond = expression();
729 if (!expect(TOK_RPAREN))
732 Statement *ifTrue = localStatement();
736 IfStatement *outer = new (pool_) IfStatement(pos, cond, ifTrue);
738 IfStatement *last = outer;
739 while (match(TOK_ELSE)) {
740 if (!match(TOK_IF)) {
741 Statement *ifFalse = localStatement();
745 last->setIfFalse(ifFalse);
749 SourcePosition pos = scanner_.begin();
750 if (!expect(TOK_LPAREN))
753 Expression *otherCond = expression();
757 if (!expect(TOK_RPAREN))
760 Statement *otherIfTrue = localStatement();
764 IfStatement *inner = new (pool_) IfStatement(pos, otherCond, otherIfTrue);
765 last->setIfFalse(inner);
773 Parser::localStatement()
775 Statement *statement = NULL;
777 // Statements which must be followed by a semicolon will break out of the
778 // switch. If they may end in BlockStatements, they'll immediately return.
780 switch (scanner_.peek()) {
782 if ((statement = variableDeclaration()) == NULL)
787 return forStatement();
794 statement = new (pool_) BreakStatement(scanner_.begin());
799 statement = new (pool_) ContinueStatement(scanner_.begin());
803 if ((statement = do_()) == NULL)
808 if ((statement = returnStatement()) == NULL)
813 if ((statement = enum_()) == NULL)
828 if ((statement = expressionStatement()) == NULL)
832 if (!expect(TOK_SEMICOLON))
843 SourcePosition pos = scanner_.begin();
845 Local<String> name(zone_);
846 if (matchName(name.ref())) {
850 if (BoundName *other = scope_->localLookup(name)) {
851 redeclarationError(other);
855 if (!scope_->declareEnum(name, scanner_.begin()))
859 EnumStatement::EntryList *entries = new (pool_) EnumStatement::EntryList();
861 if (!expect(TOK_LBRACE))
865 if (scanner_.peek() == TOK_RBRACE)
868 Local<String> name(zone_, expectName());
872 if (BoundName *other = scope_->localLookup(name)) {
873 redeclarationError(other);
877 NamedConstant *constant = scope_->declareConstant(name, scanner_.begin());
881 Expression *expr = NULL;
882 if (match(TOK_ASSIGN)) {
883 if ((expr = expression()) == NULL)
887 if (!entries->append(EnumStatement::Entry(constant, expr)))
889 } while (match(TOK_COMMA));
890 if (!expect(TOK_RBRACE))
893 return new (pool_) EnumStatement(pos, name, entries);
897 Parser::function(TokenKind token)
899 Local<String> name(zone_, expectName());
903 SourcePosition pos = scanner_.begin();
905 // The function name goes into the outer (global) scope.
906 assert(!scope_->enclosing());
909 if (BoundName *other = scope_->localLookup(name)) {
910 // We allow a redeclaration if the new type is a public, and the old
911 // type was a forward. However, the forward must come first.
912 if (other->kind() != BoundName::FUNCTION) {
913 redeclarationError(other);
917 fun = other->toNamedFunction();
918 if (!fun->isForward() || token != TOK_PUBLIC) {
919 redeclarationError(other);
923 // We've got the same name, but the original is a forward, so let it
924 // slide and re-use the original declaration.
925 fun->setImplemented(scanner_.begin());
927 fun = scope_->declareFunction(name, scanner_.begin(), token);
932 Scope *scope = enterScope(Scope::FUNCTION);
936 ParameterList *parameters = new (pool_) ParameterList();
938 if (!expect(TOK_LPAREN))
940 if (!match(TOK_RPAREN)) {
942 bool isConst = match(TOK_CONST);
943 bool ref = match(TOK_AMPERSAND);
945 SourcePosition begin = scanner_.begin();
946 Local<String> tag(zone_);
947 if (matchName(tag.ref(), TOK_LABEL) && !tag)
950 if (match(TOK_ELLIPSES)) {
951 if (isConst || ref) {
952 cc_.reportError(begin, Message_InvalidVarArgs);
956 if (token != TOK_NATIVE) {
957 cc_.reportError(begin, Message_VarArgsOutsideNative);
961 fun->markNativeVariadic();
965 Local<String> name(zone_, expectName());
969 if (BoundName *other = scope_->localLookup(name)) {
970 redeclarationError(other);
973 Variable *arg = scope_->declareArgument(name, scanner_.begin());
977 // Look for dimensions.
978 ExpressionList *postDimensions = NULL;
979 while (match(TOK_LBRACKET)) {
981 postDimensions = new (pool_) ExpressionList();
983 Expression *dim = NULL;
984 if (!match(TOK_RBRACKET)) {
985 if ((dim = expression()) == NULL)
987 if (!expect(TOK_RBRACKET))
991 if (!postDimensions->append(dim))
995 Parameter *parameter = new (pool_) Parameter(arg, tag, ref, isConst, postDimensions);
996 if (!parameters->append(parameter))
999 if (!match(TOK_COMMA))
1002 if (!expect(TOK_RPAREN))
1006 encounteredReturn_ = false;
1008 Statement *body = NULL;
1009 if (token != TOK_FORWARD && token != TOK_NATIVE) {
1015 scope_ = scope_->enclosing();
1016 return new (pool_) FunctionStatement(pos, scope, fun, body, parameters, encounteredReturn_);
1022 StatementList *statements = new (pool_) StatementList();
1024 if (!enterScope(Scope::GLOBAL))
1028 Statement *statement = NULL;
1030 switch (scanner_.peek()) {
1038 if ((statement = function(TOK_NAME)) == NULL)
1046 TokenKind kind = scanner_.scan();
1047 if ((statement = function(kind)) == NULL)
1049 if ((kind == TOK_FORWARD || kind == TOK_NATIVE) && !matchSemicolon())
1056 // if ((statement = variableDeclaration()) == NULL)
1062 if ((statement = enum_()) == NULL)
1064 if (!matchSemicolon())
1069 cc_.reportError(scanner_.begin(), Message_ExpectedGlobal);
1076 if (!statements->append(statement))
1080 return new (pool_) ParseTree(scope_, statements, unbound_);
1083 class AstPrinter : public AstVisitor
1090 for (size_t i = 0; i < level_; i++)
1101 AstPrinter(FILE *fp)
1107 void visit(NameProxy *name) {
1109 fprintf(fp_, "[ NameProxy (%s)%s\n", name->name()->chars(),
1110 (name->binding() ? "" : " unbound"));
1112 void visit(CallExpression *node) {
1114 fprintf(fp_, "[ CallExpression\n");
1116 node->callee()->accept(this);
1117 for (size_t i = 0; i < node->arguments()->length(); i++)
1118 node->arguments()->at(i)->accept(this);
1121 void visit(FunctionStatement *node) {
1123 fprintf(fp_, "[ FunctionStatement (%s)\n", node->fun()->name()->chars());
1126 node->body()->accept(this);
1129 void visit(ExpressionStatement *node) {
1131 fprintf(fp_, "[ ExpressionStatement\n");
1133 node->expression()->accept(this);
1136 void visit(Assignment *node) {
1138 fprintf(fp_, "[ Assignment\n");
1140 node->lvalue()->accept(this);
1141 node->expression()->accept(this);
1144 void visit(BinaryExpression *node) {
1146 fprintf(fp_, "[ BinaryExpression (%s)\n", TokenNames[node->token()]);
1148 node->left()->accept(this);
1149 node->right()->accept(this);
1152 void visit(UnaryExpression *node) {
1154 fprintf(fp_, "[ UnaryExpression (%s)\n", TokenNames[node->token()]);
1156 node->expression()->accept(this);
1159 void visit(ReturnStatement *node) {
1161 fprintf(fp_, "[ ReturnStatement\n");
1163 if (node->expression())
1164 node->expression()->accept(this);
1167 void visit(ForStatement *node) {
1169 fprintf(fp_, "[ ForStatement\n");
1171 if (node->initialization())
1172 node->initialization()->accept(this);
1173 if (node->condition())
1174 node->condition()->accept(this);
1176 node->update()->accept(this);
1177 node->body()->accept(this);
1180 void visit(BlockStatement *node) {
1182 fprintf(fp_, "[ BlockStatement\n");
1184 for (size_t i = 0; i < node->statements()->length(); i++)
1185 node->statements()->at(i)->accept(this);
1188 void visit(VariableDeclaration *node) {
1190 fprintf(fp_, "[ VariableDeclaration (%s)\n", node->variable()->name()->chars());
1192 if (node->initialization())
1193 node->initialization()->accept(this);
1196 void visit(IntegerLiteral *node) {
1198 fprintf(fp_, "[ IntegerLiteral (%d)\n", node->value());
1200 void visit(FloatLiteral *node) {
1202 fprintf(fp_, "[ FloatLiteral (%f)\n", node->value());
1204 void visit(IfStatement *node) {
1206 fprintf(fp_, "[ IfStatement\n");
1208 node->ifTrue()->accept(this);
1209 if (node->ifFalse())
1210 node->ifFalse()->accept(this);
1213 void visit(IndexExpression *node) {
1215 fprintf(fp_, "[ IndexExpression\n");
1217 node->left()->accept(this);
1218 node->right()->accept(this);
1221 void visit(EnumStatement *node) {
1223 fprintf(fp_, "[ EnumStatement (%s)\n", node->name() ? node->name()->chars() : "<anonymous>");
1225 for (size_t i = 0; i < node->entries()->length(); i++) {
1227 fprintf(fp_, "%s =\n", node->entries()->at(i).name->name()->chars());
1228 if (node->entries()->at(i).expr) {
1230 node->entries()->at(i).expr->accept(this);
1236 void visit(WhileStatement *node) {
1238 fprintf(fp_, "[ WhileStatement (%s)\n",
1239 (node->token() == TOK_DO) ? "do" : "while");
1241 if (node->token() == TOK_DO) {
1242 node->condition()->accept(this);
1243 node->body()->accept(this);
1245 node->condition()->accept(this);
1246 node->body()->accept(this);
1250 void visit(BreakStatement *node) {
1252 fprintf(fp_, "[ BreakStatement\n");
1254 void visit(ContinueStatement *node) {
1256 fprintf(fp_, "[ ContinueStatement\n");
1258 void visit(StringLiteral *node) {
1260 fprintf(fp_, "[ StringLiteral\n");
1262 void visit(IncDecExpression *node) {
1264 fprintf(fp_, "[ IncDecExpression (postfix=%d)\n", node->postfix());
1266 node->expression()->accept(this);
1272 ParseTree::dump(FILE *fp)
1274 AstPrinter printer(fp);
1276 for (size_t i = 0; i < statements_->length(); i++)
1277 statements_->at(i)->accept(&printer);