Add support for passing arrays.
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/.
19 #include "SemanticAnalysis.h"
22 #include "TypeManager.h"
30 IsPrimitiveType(Type *type, PrimitiveType primitive)
35 if (!type->isPrimitive())
38 return primitive == type->primitive();
42 EvaluateBinaryOperation(TokenKind kind, const BoxedPrimitive &left, const BoxedPrimitive &right,
47 *out = BoxedPrimitive::Int(left.toInt() + right.toInt());
51 *out = BoxedPrimitive::Int(left.toInt() << right.toInt());
60 EvaluateForConstant(Expression *expression, BoxedPrimitive *out)
62 switch (expression->kind()) {
63 case AstNode::kBinaryExpression:
67 BinaryExpression *b = expression->toBinaryExpression();
68 if (!EvaluateForConstant(b->left(), &left) ||
69 !EvaluateForConstant(b->right(), &right))
73 return EvaluateBinaryOperation(b->token(), left, right, out);
76 case AstNode::kNameProxy:
78 NameProxy *proxy = expression->toNameProxy();
79 if (proxy->binding()->kind() != BoundName::CONSTANT)
82 NamedConstant *c = proxy->binding()->toNamedConstant();
83 if (!IsPrimitiveType(c->type(), PrimitiveType_Int32))
90 case AstNode::kIntegerLiteral:
91 *out = BoxedPrimitive::Int(expression->toIntegerLiteral()->value());
99 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, ParseTree *tree)
109 SemanticAnalysis::analyze()
114 for (size_t i = 0; i < tree_->statements()->length(); i++) {
115 Statement *statement = tree_->statements()->at(i);
116 if (statement->isFunctionStatement()) {
117 FunctionStatement *funstmt = statement->toFunctionStatement();
118 if (!preanalyze(funstmt))
123 for (size_t i = 0; i < tree_->statements()->length(); i++) {
124 Statement *statement = tree_->statements()->at(i);
125 statement->accept(this);
128 return !cc_.failures();
132 SemanticAnalysis::visitAndApplyType(Expression *expression)
134 expression->accept(this);
135 return expression->type();
139 SemanticAnalysis::visitForLoad(Expression *expression)
141 Local<Type> type(zone_, visitAndApplyType(expression));
145 if (type->isReference()) {
146 expression->setType(type->contained());
147 } else if (expression->isIndexExpression()) {
149 expression->setType(type->contained());
152 return expression->type();
156 SemanticAnalysis::visitForRef(Expression *expression)
158 expression->accept(this);
159 return expression->type();
162 // :TODO: this leaks an interior pointer.
163 static inline const char *
164 GetTypeName(Type *type)
168 if (type->isFunction())
170 if (type->isReference())
171 type = type->contained();
173 return type->tag()->chars();
178 SemanticAnalysis::unaryTypeError(AstNode *node, TokenKind token, Handle<Type> type)
180 const char *op = TokenNames[token];
181 const char *name = GetTypeName(type);
183 cc_.reportError(node->pos(), Message_UnaryTypeError, op, name);
187 SemanticAnalysis::binaryTypeError(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
189 const char *op = TokenNames[token];
190 const char *leftName = GetTypeName(left);
191 const char *rightName = GetTypeName(right);
193 cc_.reportError(node->pos(), Message_BinaryTypeError, op, leftName, rightName);
197 SemanticAnalysis::typeCheckBinary(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
199 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
200 (token >= TOK_ASSIGN_ADD && token <= TOK_ASSIGN_DIV))
202 // If either side is a float, the other side must be a float or int.
203 if (left->isFloat() || right->isFloat()) {
204 Type *floatType = left->isFloat() ? left : right;
205 Type *other = left->isFloat() ? right : left;
206 if (other->isFloat() || (other->isInt32() && !other->tag()))
211 if ((!left->isInt32() || left->tag()) ||
212 (!right->isInt32() || right->tag()))
214 binaryTypeError(node, token, left, right);
222 SemanticAnalysis::canTest(AstNode *node, Handle<Type> type)
224 if (type->isArray()) {
225 cc_.reportError(node->pos(), Message_ArrayIsNotBoolean);
232 SemanticAnalysis::visitForLValue(Expression *expression)
234 if (expression->isIndexExpression()) {
235 Type *type = visitAndApplyType(expression);
239 return type->contained();
242 if (!expression->isNameProxy()) {
243 cc_.reportError(expression->pos(), Message_ExpectedLValue);
247 NameProxy *proxy = expression->toNameProxy();
248 if (!proxy->binding()->kind() == BoundName::VARIABLE) {
249 cc_.reportError(expression->pos(), Message_ExpectedLValue);
253 Variable *var = proxy->binding()->toVariable();
257 if (var->type()->isReference())
258 return var->type()->contained();
263 SemanticAnalysis::visit(NameProxy *name)
265 name->setType(name->binding()->type());
269 SemanticAnalysis::visit(Assignment *node)
271 Local<Type> exprType(zone_, visitForLoad(node->expression()));
275 Local<Type> type(zone_, visitForLValue(node->lvalue()));
279 if (node->token() != TOK_ASSIGN) {
280 if (!typeCheckBinary(node, node->token(), type, exprType))
284 if (!typeCheckAssignment(node, exprType, type, true))
291 SemanticAnalysis::visit(IncDecExpression *node)
293 Local<Type> type(zone_, visitForLValue(node->expression()));
297 assert(!type->isReference());
299 if ((!type->isInt32() || (type->isInt32() && type->tag())) && !type->isFloat()) {
300 unaryTypeError(node, node->token(), type);
308 SemanticAnalysis::visit(BinaryExpression *node)
310 Local<Type> left(zone_, visitForLoad(node->left()));
311 Local<Type> right(zone_, visitForLoad(node->right()));
315 Local<Type> result(zone_, typeCheckBinary(node, node->token(), left, right));
319 node->setType(result);
323 SemanticAnalysis::visit(ReturnStatement *node)
325 Local<Type> type(zone_, visitForLoad(node->expression()));
329 Local<Type> returnType(zone_, function_->returnType());
330 if (!typeCheckAssignment(node, type, returnType, true))
335 SemanticAnalysis::visit(ForStatement *node)
339 scope_ = node->scope();
341 if (node->initialization())
342 node->initialization()->accept(this);
344 if (node->condition()) {
345 Local<Type> type(zone_, visitForLoad(node->condition()));
346 if (!type || !canTest(node->condition(), type)) {
353 node->update()->accept(this);
355 node->body()->accept(this);
358 scope_ = scope_->enclosing();
363 SemanticAnalysis::visit(WhileStatement *node)
367 Local<Type> type(zone_, visitForLoad(node->condition()));
368 if (!type || !canTest(node->condition(), type)) {
373 node->body()->accept(this);
378 SemanticAnalysis::visit(BlockStatement *node)
381 scope_ = node->scope();
382 for (size_t i = 0; i < node->statements()->length(); i++) {
383 Statement *statement = node->statements()->at(i);
384 statement->accept(this);
387 scope_ = scope_->enclosing();
391 SemanticAnalysis::visit(VariableDeclaration *node)
393 Local<String> tag(zone_, node->tag());
394 Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
398 if (node->postDimensions()) {
399 Local<Type> init(zone_);
400 if (node->initialization()) {
401 if ((init = visitAndApplyType(node->initialization())) == NULL)
405 if (node->postDimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
406 cc_.reportError(node->pos(), Message_MaximumArrayDepth);
410 // If we have an initializer, make sure it's the same type.
411 if (init && node->postDimensions()->length() != init->levels()) {
412 cc_.reportError(node->pos(), Message_ArrayInitializerDepth);
416 Local<Type> check(zone_, init);
417 for (size_t i = node->postDimensions()->length() - 1; i < node->postDimensions()->length(); i--) {
418 Expression *expr = node->postDimensions()->at(i);
422 Local<Type> exprType(zone_, visitForLoad(expr));
426 if (!IsPrimitiveType(exprType, PrimitiveType_Int32)) {
427 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
432 if (EvaluateForConstant(expr, &box) && box.type() == PrimitiveType_Int32) {
435 cc_.reportError(expr->pos(), Message_BadArraySize);
438 if (size >= INT_MAX / sizeof(int)) {
439 cc_.reportError(expr->pos(), Message_ArraySizeTooBig);
444 if (check->elements() == -1) {
445 cc_.reportError(expr->pos(), Message_ArraySizeCannotBeDetermined);
449 if (check->isCharArray()) {
450 if (check->elements() > size) {
451 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
454 } else if (check->elements() != size) {
455 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, unsigned(i));
461 cc_.reportError(node->pos(), Message_DynamicArrayHasInitializer);
465 // here until we get dynamic array support.
466 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
470 // Infer the size from the initializer.
472 cc_.reportError(node->pos(), Message_ArraySizeNotSpecified);
475 if (init->elements() == -1) {
476 cc_.reportError(node->pos(), Message_ArraySizeCannotBeDetermined);
479 size = init->elements();
482 type = zone_->types()->unsafeArray(type, size);
487 check = check->contained();
490 // Right now, any array is allowed on the LIFO heap. In case the
491 // runtime actually decides to use the LIFO heap, we must reserve
492 // a slot so we can unwind the heap when the current scope leaves.
493 scope_->setUsesLifoHeap();
495 if (node->initialization()) {
496 Local<Type> right(zone_, visitForLoad(node->initialization()));
499 if (!typeCheckAssignment(node, type, right, true))
502 if (type->primitive() == PrimitiveType_Char) {
503 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
508 node->variable()->setType(type);
512 SemanticAnalysis::visit(IntegerLiteral *node)
514 node->setType(zone_->types()->getPrimitive(PrimitiveType_Int32));
518 SemanticAnalysis::visit(ExpressionStatement *node)
520 node->expression()->accept(this);
524 SemanticAnalysis::preanalyze(FunctionStatement *node)
526 Local<FixedArray> args(zone_, FixedArray::New(zone_, node->parameters()->length(), Heap::Tenure_Old));
530 // Apply types to arguments.
531 for (size_t i = 0; i < node->parameters()->length(); i++) {
532 Parameter *parameter = node->parameters()->at(i);
534 Local<String> tag(zone_, parameter->tag());
535 Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
539 if (type->primitive() == PrimitiveType_Char) {
540 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
544 if (parameter->reference()) {
545 if (parameter->dimensions()) {
546 cc_.reportError(parameter->variable()->pos(), Message_ArrayCantBeReference);
550 type = zone_->types()->getReference(type);
553 } else if (parameter->dimensions()) {
554 if (parameter->dimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
555 cc_.reportError(node->pos(), Message_MaximumArrayDepth);
559 for (size_t i = parameter->dimensions()->length() - 1;
560 i < parameter->dimensions()->length();
563 int size = Type::UNKNOWN_SIZE;
564 if (Expression *expr = parameter->dimensions()->at(i)) {
566 if (!EvaluateForConstant(expr, &box)) {
567 cc_.reportError(expr->pos(), Message_ArraySizeMustBeConstant);
573 type = Type::NewArray(zone_, type, size, false);
579 args->set(zone_, i, type);
580 parameter->variable()->setType(type);
583 Local<Type> returnType(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
587 Local<Type> funtype(zone_, zone_->types()->newFunction(returnType, args));
591 // If the function already has a type, it was forward declared before, and
592 // now this is our chance to type check the second declaration.
593 if (node->fun()->type()) {
594 Local<Type> forward(zone_, node->fun()->type());
595 if (!Type::Compare(funtype, forward)) {
596 cc_.reportError(node->pos(), Message_ForwardDeclareMismatches);
599 node->fun()->setForwardType(forward);
602 node->fun()->setType(funtype);
608 SemanticAnalysis::visit(FunctionStatement *node)
610 function_ = node->fun()->type();
611 scope_ = node->scope();
613 node->body()->accept(this);
619 SemanticAnalysis::typeCheckArrayAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
621 Local<Type> actual(zone_, argActual);
622 Local<Type> given(zone_, argGiven);
624 if (!given->isArray()) {
625 cc_.reportError(node->pos(), Message_ExpectedArray);
628 if (given->levels() != actual->levels()) {
629 cc_.reportError(node->pos(), Message_ArrayDimensionsMismatch);
634 while (given->isArray()) {
635 if (actual->elements() != -1) {
637 if (given->elements() == -1 || actual->elements() == -1) {
638 cc_.reportError(node->pos(), Message_ArraySizeNotKnown);
642 if (actual->isCharArray()) {
643 // String assignment can have a truncated |given|.
644 if (given->elements() > actual->elements()) {
645 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
649 if (given->elements() != actual->elements()) {
650 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
655 if (actual->elements() != -1 && given->elements() != actual->elements()) {
656 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
661 given = given->contained();
662 actual = actual->contained();
665 if (given->primitive() != actual->primitive()) {
666 // :TODO: leaks an interior pointer.
667 const char *givenTag = given->tag() ? given->tag()->chars() : "_";
668 const char *actualTag = given->tag() ? given->tag()->chars() : "_";
669 cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
677 SemanticAnalysis::typeCheckAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
679 Local<Type> actual(zone_, argActual);
680 Local<Type> given(zone_, argGiven);
682 if (actual->isArray())
683 return typeCheckArrayAssignment(node, given, actual, forAssign);
685 if (given->isArray()) {
686 cc_.reportError(node->pos(), Message_CannotAssignArrayToScalar);
690 // The given type may not have been dereferenced.
691 if (given->isReference())
692 given = given->contained();
693 if (actual->isReference())
694 actual = actual->contained();
696 if (!given->isPrimitive() || !actual->isPrimitive()) {
697 cc_.reportError(node->pos(), Message_UnsupportedType);
701 if (given->primitive() != actual->primitive()) {
702 // :TODO: leaks an interior pointer
703 const char *givenTag = given->tag() ? given->tag()->chars() : "_";
704 const char *actualTag = given->tag() ? given->tag()->chars() : "_";
705 cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
713 SemanticAnalysis::typeCheckParameter(AstNode *node, Handle<Type> given, Handle<Type> actual)
715 return typeCheckAssignment(node, given, actual, false);
719 SemanticAnalysis::visit(CallExpression *node)
721 Local<Type> type(zone_, visitForLoad(node->callee()));
725 if (!type->isFunction()) {
726 cc_.reportError(node->pos(), Message_CalleeNotFunction);
729 if (node->arguments()->length() != type->parameters()->length()) {
730 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
734 // Currently, only calls from a NameProxy are possible.
735 NamedFunction *fun = node->callee()->toNameProxy()->binding()->toNamedFunction();
736 if (fun->isForward()) {
737 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
741 for (unsigned i = 0; i < node->arguments()->length(); i++) {
742 // Note: we don't compute references unless the callee needs a
744 Expression *expression = node->arguments()->at(i);
745 Local<Type> given(zone_, visitAndApplyType(expression));
749 // If it's an IndexExpression, we special case the ability to compute
751 if (expression->isIndexExpression())
752 given = given->contained();
754 Local<Type> actual(zone_, type->parameterAt(i));
755 if (!typeCheckParameter(expression, given, actual))
758 // If the actual is a reference, and the given is not, we'll need to
759 // compute a reference, which may be allocated on the stack.
760 if (actual->isReference() && !given->isReference())
761 scope_->setUsesLifoHeap();
764 node->setType(fun->type()->returnType());
768 SemanticAnalysis::visit(IfStatement *node)
770 Local<Type> type(zone_, visitForLoad(node->condition()));
774 if (!canTest(node, type))
777 node->ifTrue()->accept(this);
779 node->ifFalse()->accept(this);
783 SemanticAnalysis::visit(IndexExpression *node)
785 Local<Type> left(zone_, visitForRef(node->left()));
786 Local<Type> right(zone_, visitForLoad(node->right()));
791 if (!right->isInt32()) {
792 cc_.reportError(node->right()->pos(), Message_IndexMustBeInteger);
795 if (!left->isArray()) {
796 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
803 SemanticAnalysis::visit(EnumStatement *node)
805 // Forbid the blessed types.
806 Local<String> tag(zone_, node->name());
807 if (!strcmp(tag->chars(), "Float") ||
808 !strcmp(tag->chars(), "String") ||
809 !strcmp(tag->chars(), "any") ||
810 !strcmp(tag->chars(), "bool"))
812 cc_.reportError(node->pos(), Message_InvalidEnumName);
816 Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
821 for (size_t i = 0; i < node->entries()->length(); i++) {
822 EnumStatement::Entry &entry = node->entries()->at(i);
824 BoxedPrimitive box = BoxedPrimitive::Int(value);
826 entry.expr->accept(this);
827 if (!EvaluateForConstant(entry.expr, &box)) {
828 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
832 assert(box.type() == PrimitiveType_Int32);
836 entry.name->set(type, box);
842 SemanticAnalysis::visit(StringLiteral *node)
844 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Char));
848 type = Type::NewArray(zone_, type, node->string()->length() + 1, true);
856 SemanticAnalysis::visit(FloatLiteral *node)
858 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
866 SemanticAnalysis::visit(BreakStatement *node)
869 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
873 SemanticAnalysis::visit(ContinueStatement *node)
876 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);