Enable struct composition.
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/.
20 #include "SemanticAnalysis.h"
23 #include "TypeManager.h"
25 #include "NameBinding.h"
32 IsPrimitiveType(Type *type, PrimitiveType primitive)
37 if (!type->isPrimitive())
40 return primitive == type->primitive();
44 EvaluateBinaryOperation(TokenKind kind, const BoxedPrimitive &left, const BoxedPrimitive &right,
49 *out = BoxedPrimitive::Int(left.toInt() + right.toInt());
53 *out = BoxedPrimitive::Int(left.toInt() << right.toInt());
62 EvaluateUnaryOperation(TokenKind kind, const BoxedPrimitive &inner, BoxedPrimitive *out)
66 *out = BoxedPrimitive::Int(-inner.toInt());
75 EvaluateForConstant(Expression *expression, BoxedPrimitive *out)
77 switch (expression->kind()) {
78 case AstNode::kBinaryExpression:
82 BinaryExpression *b = expression->toBinaryExpression();
83 if (!EvaluateForConstant(b->left(), &left) ||
84 !EvaluateForConstant(b->right(), &right))
88 return EvaluateBinaryOperation(b->token(), left, right, out);
91 case AstNode::kUnaryExpression:
94 UnaryExpression *u = expression->toUnaryExpression();
95 if (!EvaluateForConstant(u->expression(), &inner))
97 return EvaluateUnaryOperation(u->token(), inner, out);
100 case AstNode::kNameProxy:
102 NameProxy *proxy = expression->toNameProxy();
103 if (proxy->binding()->kind() != BoundName::CONSTANT)
106 NamedConstant *c = proxy->binding()->toNamedConstant();
107 if (!IsPrimitiveType(c->type(), PrimitiveType_Int32))
114 case AstNode::kIntegerLiteral:
115 *out = BoxedPrimitive::Int(expression->toIntegerLiteral()->value());
123 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, ParseTree *tree)
133 SemanticAnalysis::analyze()
138 scope_ = tree_->scope();
140 for (size_t i = 0; i < tree_->statements()->length(); i++) {
141 Statement *statement = tree_->statements()->at(i);
142 if (statement->isFunctionStatement()) {
143 FunctionStatement *funstmt = statement->toFunctionStatement();
144 if (!preanalyze(funstmt))
146 } else if (statement->isEnumStatement()) {
147 EnumStatement *enumstmt = statement->toEnumStatement();
149 // We pre-fill global enum types, since they may occur in function
150 // signatures. This should probably be somewhere else...
151 Local<String> name(zone_, enumstmt->name());
152 Local<Type> type(zone_);
154 type = zone_->types()->newEnum(name);
156 type = zone_->types()->getPrimitive(PrimitiveType_Int32);
161 enumstmt->decl()->setType(type);
162 } else if (statement->isStructureStatement()) {
163 StructureStatement *node = statement->toStructureStatement();
165 if (!node->decl()->type())
170 for (size_t i = 0; i < tree_->statements()->length(); i++) {
171 Statement *statement = tree_->statements()->at(i);
172 statement->accept(this);
175 if (!determineLiveFunctions())
178 return !cc_.failures();
182 SemanticAnalysis::determineLiveFunctions()
184 Vector<NamedFunction *> worklist;
187 for (size_t i = 0; i < tree_->statements()->length(); i++) {
188 Statement *statement = tree_->statements()->at(i);
189 if (!statement->isFunctionStatement())
192 FunctionStatement *stmt = statement->toFunctionStatement();
193 NamedFunction *fun = stmt->fun();
197 for (size_t i = 0; i < fun->usedGlobals()->length(); i++) {
198 NamedFunction *name = fun->usedGlobals()->at(i)->toNamedFunction();
200 // Names in these lists are always unused, however, we mark them
201 // as used while inserting into the work queue, to avoid double-
206 if (!worklist.append(name))
213 while (!worklist.empty()) {
214 NamedFunction *fun = worklist.popCopy();
216 for (size_t i = 0; i < fun->usedGlobals()->length(); i++) {
217 NamedFunction *name = fun->usedGlobals()->at(i)->toNamedFunction();
220 if (!worklist.append(name))
230 SemanticAnalysis::bindType(const SourcePosition &pos, BoundName *name)
233 return zone_->types()->getPrimitive(PrimitiveType_Int32);
235 if (name->kind() == BoundName::UNBOUND) {
236 cc_.reportError(pos, Message_TypeNotFound, name->name()->chars());
240 if (name->kind() != BoundName::TYPE) {
241 cc_.reportError(pos, Message_IdentifierIsNotAType, name->name()->chars());
252 SemanticAnalysis::visitAndApplyType(Expression *expression)
254 expression->accept(this);
255 return expression->type();
259 SemanticAnalysis::visitForLoad(Expression *expression)
261 Local<Type> type(zone_, visitAndApplyType(expression));
265 if (type->isReference()) {
266 expression->setType(type->contained());
267 } else if (expression->isCallExpression()) {
268 if (type->isVoid()) {
269 CallExpression *call = expression->toCallExpression();
270 cc_.reportError(call->callee()->pos(), Message_FunctionDoesNotReturnValue);
275 return expression->type();
278 // :TODO: this leaks an interior pointer.
280 ke::GetTypeName(Type *type)
284 if (type->isFunction())
288 if (type->isEnum() || type->isStruct())
289 return type->name()->chars();
290 if (type->isReference())
291 type = type->contained();
292 switch (type->primitive()) {
293 case PrimitiveType_Bool:
295 case PrimitiveType_Char:
297 case PrimitiveType_Int32:
299 case PrimitiveType_Float:
307 SemanticAnalysis::unaryTypeError(AstNode *node, TokenKind token, Handle<Type> type)
309 const char *op = TokenNames[token];
310 const char *name = GetTypeName(type);
312 cc_.reportError(node->pos(), Message_UnaryTypeError, op, name);
316 SemanticAnalysis::binaryTypeError(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
318 const char *op = TokenNames[token];
319 const char *leftName = GetTypeName(left);
320 const char *rightName = GetTypeName(right);
322 cc_.reportError(node->pos(), Message_BinaryTypeError, op, leftName, rightName);
326 SemanticAnalysis::typeCheckBinary(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
328 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
329 (token >= TOK_ASSIGN_ADD && token <= TOK_ASSIGN_DIV))
331 // If either side is a float, the other side must be a float or int.
332 if (left->isFloat() || right->isFloat()) {
333 Type *floatType = left->isFloat() ? left : right;
334 Type *other = left->isFloat() ? right : left;
335 if (other->isFloat() || other->isInt32())
340 if (token == TOK_OR || token == TOK_AND) {
341 if (!canTest(node, left) || !canTest(node, right))
343 return zone_->types()->getPrimitive(PrimitiveType_Bool);
346 if (token >= TOK_EQUALS && token <= TOK_GE) {
347 if ((left->isFloat() || left->isInt32()) &&
348 (right->isFloat() || right->isInt32()))
350 return zone_->types()->getPrimitive(PrimitiveType_Bool);
352 binaryTypeError(node, token, left, right);
356 if (!left->isInt32() || !right->isInt32()) {
357 binaryTypeError(node, token, left, right);
365 SemanticAnalysis::canTest(AstNode *node, Handle<Type> type)
367 if (!type->isPrimitive() && !type->isEnum()) {
368 cc_.reportError(node->pos(), Message_ArrayIsNotBoolean);
375 SemanticAnalysis::visitForLValue(Expression *expression)
377 if (expression->isIndexExpression()) {
378 Type *type = visitAndApplyType(expression);
382 if (type->isConst()) {
383 cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
390 if (expression->isFieldExpression()) {
391 Type *type = visitAndApplyType(expression);
395 // if (expression->toFieldExpression()->left()->type()->isConst()) {
396 // cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
403 if (!expression->isNameProxy()) {
404 cc_.reportError(expression->pos(), Message_ExpectedLValue);
408 NameProxy *proxy = expression->toNameProxy();
409 if (!proxy->binding()->kind() == BoundName::VARIABLE) {
410 cc_.reportError(expression->pos(), Message_ExpectedLValue);
414 Variable *var = proxy->binding()->toVariable();
418 if (var->type()->isReference()) {
419 if (var->type()->isConst()) {
420 cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
423 return var->type()->contained();
428 SemanticAnalysis::ControlStatus
429 SemanticAnalysis::visitForControl(Statement *statement)
431 ControlScope scope(&control_);
432 statement->accept(this);
433 return scope.status();
437 SemanticAnalysis::visit(NameProxy *name)
439 BoundName *binding = name->binding();
441 if (binding->scope()->kind() == Scope::GLOBAL) {
442 if (!function_ || function_->isPublic()) {
443 // Whatever we're referencing must be kept alive no matter what.
444 // As such, we simply mark it used, and don't do anything special.
446 } else if (!binding->used() && binding->kind() == BoundName::FUNCTION) {
447 // Otherwise, we're inside a normal stock or function. Since we
448 // don't really know if we've been used yet, we shouldn't
449 // prematurely references as alive. Instead, we keep a list of
450 // which names have been used, so we can mark them later if needed.
452 // Note that we skip this step if the binding is already in the
454 if (!function_->addUsedGlobal(binding))
459 name->setType(binding->type());
463 SemanticAnalysis::visit(Assignment *node)
465 Local<Type> exprType(zone_, visitForLoad(node->expression()));
469 Local<Type> type(zone_, visitForLValue(node->lvalue()));
473 if (node->token() != TOK_ASSIGN) {
474 if (!typeCheckBinary(node, node->token(), type, exprType))
478 if (!typeCheckAssignment(node, exprType, type, true))
485 SemanticAnalysis::visit(IncDecExpression *node)
487 Local<Type> type(zone_, visitForLValue(node->expression()));
491 assert(!type->isReference());
493 if (!type->isInt32() && !type->isFloat()) {
494 unaryTypeError(node, node->token(), type);
502 SemanticAnalysis::visit(UnaryExpression *node)
504 Local<Type> type(zone_, visitForLoad(node->expression()));
508 switch (node->token())
511 if (!canTest(node->expression(), type))
513 type = zone_->types()->getPrimitive(PrimitiveType_Int32);
520 if (!type->isFloat() && !type->isInt32()) {
521 unaryTypeError(node, node->token(), type);
529 Local<Type> to(zone_, bindType(node->pos(), node->type()));
533 if ((!type->isFloat() && !type->isInt32OrEnum()) ||
534 (!to->isFloat() && !to->isInt32OrEnum()))
536 unaryTypeError(node, node->token(), type);
545 assert(node->token() == TOK_TILDE);
546 if (!type->isInt32()) {
547 unaryTypeError(node, node->token(), type);
556 SemanticAnalysis::visit(TernaryExpression *node)
558 Local<Type> type(zone_, visitForLoad(node->condition()));
562 if (!canTest(node->condition(), type))
565 Local<Type> left(zone_, visitForLoad(node->left()));
566 Local<Type> right(zone_, visitForLoad(node->right()));
571 binaryTypeError(node, TOK_QMARK, left, right);
577 SemanticAnalysis::visit(BinaryExpression *node)
579 Local<Type> left(zone_, visitForLoad(node->left()));
580 Local<Type> right(zone_, visitForLoad(node->right()));
584 Local<Type> result(zone_, typeCheckBinary(node, node->token(), left, right));
588 node->setType(result);
592 SemanticAnalysis::visit(ReturnStatement *node)
594 // Set this early, so if we error we don't get more errors.
595 control_->returns(Returns_Always);
597 if (!node->expression()) {
598 if (!function_->type()->returnType()->isVoid())
599 cc_.reportError(node->pos(), Message_NotAllPathsReturnValue);
603 Local<Type> type(zone_, visitForLoad(node->expression()));
607 Local<Type> returnType(zone_, function_->type()->returnType());
608 if (!typeCheckAssignment(node, type, returnType, true))
613 SemanticAnalysis::visit(ForStatement *node)
615 LoopScope loop(&loop_);
618 scope_ = node->scope();
620 if (node->initialization())
621 node->initialization()->accept(this);
623 if (node->condition()) {
624 Local<Type> type(zone_, visitForLoad(node->condition()));
625 if (!type || !canTest(node->condition(), type)) {
631 node->update()->accept(this);
633 ControlStatus status = visitForControl(node->body());
635 // If there is a condition, we treat this like a while loop. Otherwise,
636 // join point is only reachable if the loop contains a break. The
637 // termination status doesn't tell us anything yet.
638 if (node->condition() || loop.breaks())
639 control_->merge(status, ControlStatus(false, Returns_Never));
641 control_->terminate(status.returns());
644 scope_ = scope_->enclosing();
648 SemanticAnalysis::visit(WhileStatement *node)
650 LoopScope loop(&loop_);
652 Local<Type> type(zone_, visitForLoad(node->condition()));
653 if (!type || !canTest(node->condition(), type)) {
657 ControlStatus status = visitForControl(node->body());
659 // Detect loops that will always have a fork in the control-flow graph.
660 // This will be a |while| loop, or a |do-while| loop whose body does
663 // For now, we treat these as an |if| regardless of the direction the
664 // branch can take. That means the control-flow is always conditional.
665 if (node->token() == TOK_WHILE ||
666 !status.terminates() ||
669 control_->merge(status, ControlStatus(false, Returns_Never));
671 // At this point, we've got a do-while loop with a |return| or
672 // |continue|, meaning that the rest of the block is unreachable.
673 control_->terminate(status.returns());
678 SemanticAnalysis::visit(BlockStatement *node)
681 scope_ = node->scope();
682 for (size_t i = 0; i < node->statements()->length(); i++) {
683 Statement *statement = node->statements()->at(i);
684 statement->accept(this);
687 scope_ = scope_->enclosing();
691 IsScalarString(Type *type)
693 if (type->isPrimitive() && type->primitive() == PrimitiveType_Char)
695 if (type->isReference())
696 return IsScalarString(type->contained());
701 SemanticAnalysis::visit(VariableDeclaration *node)
703 Local<Type> type(zone_, bindType(node->pos(), node->type()));
707 if (node->postDimensions()) {
708 Local<Type> init(zone_);
709 if (node->initialization()) {
710 if ((init = visitForLoad(node->initialization())) == NULL)
714 if (node->postDimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
715 cc_.reportError(node->pos(), Message_MaximumArrayDepth);
719 // If we have an initializer, make sure it's the same type.
720 if (init && node->postDimensions()->length() != init->levels()) {
721 cc_.reportError(node->pos(), Message_ArrayInitializerDepth);
725 Local<Type> check(zone_, init);
726 for (size_t i = node->postDimensions()->length() - 1; i < node->postDimensions()->length(); i--) {
727 Expression *expr = node->postDimensions()->at(i);
731 Local<Type> exprType(zone_, visitForLoad(expr));
735 if (!IsPrimitiveType(exprType, PrimitiveType_Int32)) {
736 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
741 if (EvaluateForConstant(expr, &box) && box.type() == PrimitiveType_Int32) {
744 cc_.reportError(expr->pos(), Message_BadArraySize);
747 if (size >= int(INT_MAX / sizeof(int))) {
748 cc_.reportError(expr->pos(), Message_ArraySizeTooBig);
753 if (check->elements() == -1) {
754 cc_.reportError(expr->pos(), Message_ArraySizeCannotBeDetermined);
758 if (check->isCharArray()) {
759 if (check->elements() > size) {
760 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
763 } else if (check->elements() != size) {
764 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, unsigned(i));
770 cc_.reportError(node->pos(), Message_DynamicArrayHasInitializer);
774 // here until we get dynamic array support.
775 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
779 // Infer the size from the initializer.
781 cc_.reportError(node->pos(), Message_ArraySizeNotSpecified);
784 if (init->elements() == -1) {
785 cc_.reportError(node->pos(), Message_ArraySizeCannotBeDetermined);
788 size = init->elements();
791 type = zone_->types()->unsafeArray(type, size, false);
796 check = check->contained();
799 if (node->initialization()) {
800 Local<Type> right(zone_, visitForLoad(node->initialization()));
803 if (!typeCheckAssignment(node, type, right, true))
807 if (type->isPrimitive() && type->primitive() == PrimitiveType_Char) {
808 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
813 // If this variable is stack allocated, we could use the LIFO heap
814 // to allocate it. If that's the case, make sure to reserve a slot
815 // so we can unwind the LIFO heap at the end of this scope.
816 if (!node->variable()->needsHeapAllocation()) {
817 if (type->isArray() || type->isStruct())
818 scope_->setUsesLifoHeap();
821 node->variable()->setType(type);
825 SemanticAnalysis::visit(IntegerLiteral *node)
827 node->setType(zone_->types()->getPrimitive(PrimitiveType_Int32));
831 SemanticAnalysis::visit(BooleanLiteral *node)
833 node->setType(zone_->types()->getPrimitive(PrimitiveType_Bool));
837 SemanticAnalysis::visit(ExpressionStatement *node)
839 visitAndApplyType(node->expression());
843 SemanticAnalysis::preanalyze(FunctionStatement *node)
845 Local<FixedArray> args(zone_, FixedArray::New(zone_, node->parameters()->length(), Heap::Tenure_Old));
849 // Apply types to arguments.
850 for (size_t i = 0; i < node->parameters()->length(); i++) {
851 Parameter *parameter = node->parameters()->at(i);
853 Local<Type> type(zone_, bindType(parameter->variable()->pos(), parameter->type()));
857 if (parameter->reference()) {
858 if (parameter->dimensions()) {
859 cc_.reportError(parameter->variable()->pos(), Message_ArrayCantBeReference);
863 type = zone_->types()->getReference(type, parameter->isConst());
866 } else if (parameter->dimensions()) {
867 if (parameter->dimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
868 cc_.reportError(parameter->variable()->pos(), Message_MaximumArrayDepth);
872 if (node->fun()->isNative() && parameter->dimensions()->length() > 1) {
873 cc_.reportError(parameter->variable()->pos(), Message_MultiArrayInNative);
877 for (size_t i = parameter->dimensions()->length() - 1;
878 i < parameter->dimensions()->length();
881 int size = Type::UNKNOWN_SIZE;
882 if (Expression *expr = parameter->dimensions()->at(i)) {
884 if (!EvaluateForConstant(expr, &box)) {
885 cc_.reportError(expr->pos(), Message_ArraySizeMustBeConstant);
891 type = zone_->types()->unsafeArray(type, size, parameter->isConst());
897 if (IsScalarString(type)) {
898 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
902 args->set(zone_, i, type);
903 parameter->variable()->setType(type);
906 Local<Type> returnType(zone_);
907 if (node->returnType() ||
908 node->hasExplicitReturn() ||
909 node->fun()->isNative())
911 returnType = bindType(node->pos(), node->returnType());
913 returnType = zone_->types()->getVoid();
918 Local<Type> funtype(zone_);
919 if (node->fun()->isNative())
920 funtype = zone_->types()->newNative(returnType, args, node->fun()->isNativeVariadic());
922 funtype = zone_->types()->newFunction(returnType, args);
926 // If the function already has a type, it was forward declared before, and
927 // now this is our chance to type check the second declaration.
928 if (node->fun()->type()) {
929 Local<Type> forward(zone_, node->fun()->type());
930 if (!Type::Compare(funtype, forward)) {
931 cc_.reportError(node->pos(), Message_ForwardDeclareMismatches);
934 node->fun()->setForwardType(forward);
937 node->fun()->setType(funtype);
943 SemanticAnalysis::visit(FunctionStatement *node)
945 function_ = node->fun();
946 scope_ = node->scope();
948 ControlScope control(&control_);
950 node->body()->accept(this);
952 ControlStatus status = control.status();
953 if (status.returns() == Returns_Sometimes) {
954 cc_.reportError(node->pos(), Message_NotAllPathsReturnValue);
955 } else if (status.returns() == Returns_Never) {
956 if (!function_->type()->returnType()->isVoid())
957 cc_.reportError(node->pos(), Message_MissingReturnValue);
966 SemanticAnalysis::typeMismatch(AstNode *node, Handle<Type> actual, Handle<Type> given)
968 cc_.reportError(node->pos(),Message_TypeMismatch,
974 SemanticAnalysis::typeCheckArrayAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
976 Local<Type> actual(zone_, argActual);
977 Local<Type> given(zone_, argGiven);
979 if (!given->isArray()) {
980 cc_.reportError(node->pos(), Message_ExpectedArray);
983 if (given->levels() != actual->levels()) {
984 cc_.reportError(node->pos(), Message_ArrayDimensionsMismatch);
989 while (given->isArray()) {
990 if (actual->elements() != -1) {
992 if (given->elements() == -1 || actual->elements() == -1) {
993 cc_.reportError(node->pos(), Message_ArraySizeNotKnown);
997 if (actual->isCharArray()) {
998 // String assignment can have a truncated |given|.
999 if (given->elements() > actual->elements()) {
1000 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
1004 if (given->elements() != actual->elements()) {
1005 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
1010 if (actual->elements() != -1 && given->elements() != actual->elements()) {
1011 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
1016 given = given->contained();
1017 actual = actual->contained();
1020 return typeCheckAssignment(node, given, actual, forAssign);
1024 SemanticAnalysis::typeCheckAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
1026 Local<Type> actual(zone_, argActual);
1027 Local<Type> given(zone_, argGiven);
1029 if (actual->isArray())
1030 return typeCheckArrayAssignment(node, given, actual, forAssign);
1032 if (given->isArray()) {
1033 cc_.reportError(node->pos(), Message_CannotAssignArrayToScalar);
1037 // The given type may not have been dereferenced.
1038 if (given->isReference())
1039 given = given->contained();
1040 if (actual->isReference())
1041 actual = actual->contained();
1043 if (actual->isEnum()) {
1044 if (!given->isEnum() || actual != given) {
1045 typeMismatch(node, actual, given);
1051 if (actual->isStruct()) {
1052 if (!given->isStruct() || actual != given) {
1053 typeMismatch(node, actual, given);
1059 if (given->isEnum() || given->isFunction() || given->isStruct()) {
1060 typeMismatch(node, actual, given);
1064 if (given->primitive() != actual->primitive()) {
1065 typeMismatch(node, actual, given);
1073 SemanticAnalysis::typeCheckParameter(AstNode *node, Handle<Type> given, Handle<Type> actual)
1075 return typeCheckAssignment(node, given, actual, false);
1079 SemanticAnalysis::visit(CallExpression *node)
1081 Local<Type> type(zone_, visitForLoad(node->callee()));
1085 if (!type->isFunction()) {
1086 cc_.reportError(node->pos(), Message_CalleeNotFunction);
1089 if (node->arguments()->length() != type->parameters()->length()) {
1090 if (!type->isNative() ||
1091 !type->isNativeVariadic() ||
1092 node->arguments()->length() < type->parameters()->length())
1094 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
1099 // Currently, only calls from a NameProxy are possible.
1100 NamedFunction *fun = node->callee()->toNameProxy()->binding()->toNamedFunction();
1101 if (fun->isForward()) {
1102 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
1106 for (unsigned i = 0; i < node->arguments()->length(); i++) {
1107 // Note: we don't compute references unless the callee needs a
1109 Expression *expression = node->arguments()->at(i);
1110 Local<Type> given(zone_, visitAndApplyType(expression));
1114 // Since we skip a load, check for a call expression that returns void.
1115 if (given->isVoid()) {
1116 assert(expression->isCallExpression());
1117 CallExpression *call = expression->toCallExpression();
1118 cc_.reportError(call->callee()->pos(), Message_FunctionDoesNotReturnValue);
1122 bool mustComputeReference;
1123 if (i >= type->parameters()->length()) {
1124 // Special handling for natives. Arguments past the formal must
1125 // always have references computed. However, arrays are already
1126 // references for natives.
1127 assert(type->isNative() && type->isNativeVariadic());
1128 mustComputeReference = !given->isReference() && !given->isArray();
1130 Local<Type> actual(zone_, type->parameterAt(i));
1131 if (!typeCheckParameter(expression, given, actual))
1133 mustComputeReference = actual->isReference() && !given->isReference();
1136 // If the actual is a reference, and the given is not, we'll need to
1137 // compute a reference, which may be allocated on the stack.
1138 if (mustComputeReference)
1139 scope_->setUsesLifoHeap();
1142 node->setType(fun->type()->returnType());
1146 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
1148 // If both sides terminate in a return, we consider this a return as well.
1149 if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
1150 terminate(Returns_Always);
1154 ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
1156 : Returns_Sometimes;
1158 if (left.terminates() && right.terminates())
1165 SemanticAnalysis::visit(IfStatement *node)
1167 Local<Type> type(zone_, visitForLoad(node->condition()));
1171 if (!canTest(node, type))
1174 ControlStatus trueBranch = visitForControl(node->ifTrue());
1175 ControlStatus falseBranch = ControlStatus(false, Returns_Never);
1177 if (node->ifFalse())
1178 falseBranch = visitForControl(node->ifFalse());
1180 control_->merge(trueBranch, falseBranch);
1184 SemanticAnalysis::visit(IndexExpression *node)
1186 Local<Type> left(zone_, visitForLoad(node->left()));
1187 Local<Type> right(zone_, visitForLoad(node->right()));
1189 if (!left || !right)
1192 if (!right->isInt32() && !right->isEnum()) {
1193 cc_.reportError(node->right()->pos(), Message_IndexMustBeInteger);
1196 if (!left->isArray()) {
1197 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
1200 node->setType(left->contained());
1204 SemanticAnalysis::visit(FieldExpression *node)
1206 Local<Type> left(zone_, visitForLoad(node->left()));
1210 if (!left->isStruct()) {
1211 cc_.reportError(node->pos(), Message_PropertyNotFound, node->field()->chars(),
1216 Local<String> field(zone_, node->field());
1219 Local<Descriptor> desc(zone_, left->lookupField(field, &offset));
1221 cc_.reportError(node->pos(), Message_PropertyNotFound, node->field()->chars(),
1226 node->setFieldIndex(offset);
1227 node->setType(desc->type());
1231 SemanticAnalysis::visit(EnumStatement *node)
1233 Local<Type> type(zone_, node->decl()->type());
1238 for (size_t i = 0; i < node->entries()->length(); i++) {
1239 EnumStatement::Entry &entry = node->entries()->at(i);
1241 BoxedPrimitive box = BoxedPrimitive::Int(value);
1243 entry.expr->accept(this);
1244 if (!EvaluateForConstant(entry.expr, &box)) {
1245 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
1249 assert(box.type() == PrimitiveType_Int32);
1250 value = box.toInt();
1253 entry.name->set(type, box);
1259 SemanticAnalysis::visit(StructureStatement *node)
1261 // If this node already has a type, it was pre-analyzed, so skip it.
1262 if (node->decl()->type())
1265 FieldList *fields = node->fields();
1266 Local<FixedArray> desctable(zone_, FixedArray::New(zone_, fields->length(), Heap::Tenure_Old));
1270 Vector<unsigned> composedList;
1271 StructureBufferBuilder builder;
1273 Local<Type> type(zone_);
1274 Local<String> name(zone_);
1275 Local<Descriptor> desc(zone_);
1276 for (size_t i = 0; i < fields->length(); i++) {
1277 StructureStatement::Field *field = fields->at(i);
1279 type = bindType(field->pos(), field->type());
1284 if (!builder.add(type, &offset))
1287 name = field->name();
1288 desc = Descriptor::New(zone_, name, type, offset);
1292 desctable->set(zone_, i, desc);
1294 if (type->isStruct() || type->isArray()) {
1295 if (!composedList.append(i))
1300 Local<FixedArray> composed(zone_);
1301 if (composedList.length()) {
1302 composed = FixedArray::New(zone_, composedList.length(), Heap::Tenure_Old);
1306 for (unsigned i = 0; i < composedList.length(); i++)
1307 composed->set(zone_, i, desctable->at(i));
1310 Local<StructMap> map(zone_, StructMap::New(zone_, builder, composed));
1314 name = node->decl()->name();
1315 type = zone_->types()->newStruct(name, desctable, map);
1320 node->decl()->setType(type);
1324 SemanticAnalysis::visit(StringLiteral *node)
1326 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Char));
1330 type = Type::NewArray(zone_, type, node->string()->length() + 1, true);
1334 node->setType(type);
1338 SemanticAnalysis::visit(FloatLiteral *node)
1340 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
1344 node->setType(type);
1348 SemanticAnalysis::visit(BreakStatement *node)
1351 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
1355 // Note: ignore breaks that occur in unreachable control-flow.
1356 if (!control_->status().terminates())
1359 control_->terminate(Returns_Never);
1363 SemanticAnalysis::visit(ContinueStatement *node)
1366 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
1370 // Note: ignore continues that occur in unreachable control-flow.
1371 if (!control_->status().terminates())
1372 loop_->addContinue();
1374 control_->terminate(Returns_Never);