Allow returning arrays from functions.
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"
34 IsPrimitiveType(Type *type, PrimitiveType primitive)
39 if (!type->isPrimitive())
42 return primitive == type->primitive();
46 EvaluateBinaryOperation(TokenKind kind, const BoxedPrimitive &left, const BoxedPrimitive &right,
51 *out = BoxedPrimitive::Int(left.toInt() + right.toInt());
55 *out = BoxedPrimitive::Int(left.toInt() << right.toInt());
64 EvaluateUnaryOperation(TokenKind kind, const BoxedPrimitive &inner, BoxedPrimitive *out)
68 *out = BoxedPrimitive::Int(-inner.toInt());
77 EvaluateForConstant(Expression *expression, BoxedPrimitive *out)
79 switch (expression->kind()) {
80 case AstNode::kBinaryExpression:
84 BinaryExpression *b = expression->toBinaryExpression();
85 if (!EvaluateForConstant(b->left(), &left) ||
86 !EvaluateForConstant(b->right(), &right))
90 return EvaluateBinaryOperation(b->token(), left, right, out);
93 case AstNode::kUnaryExpression:
96 UnaryExpression *u = expression->toUnaryExpression();
97 if (!EvaluateForConstant(u->expression(), &inner))
99 return EvaluateUnaryOperation(u->token(), inner, out);
102 case AstNode::kNameProxy:
104 NameProxy *proxy = expression->toNameProxy();
105 if (proxy->binding()->kind() != BoundName::CONSTANT)
108 NamedConstant *c = proxy->binding()->toNamedConstant();
109 if (!IsPrimitiveType(c->type(), PrimitiveType_Int32))
116 case AstNode::kBooleanLiteral:
117 *out = BoxedPrimitive::Int(expression->toBooleanLiteral()->token() == TOK_TRUE ? 1 : 0);
120 case AstNode::kIntegerLiteral:
121 *out = BoxedPrimitive::Int(expression->toIntegerLiteral()->value());
129 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, ParseTree *tree)
139 SemanticAnalysis::analyze()
144 scope_ = tree_->scope();
146 for (size_t i = 0; i < tree_->statements()->length(); i++) {
147 Statement *statement = tree_->statements()->at(i);
148 if (statement->isFunctionStatement()) {
149 FunctionStatement *funstmt = statement->toFunctionStatement();
150 if (!preanalyze(funstmt))
152 } else if (statement->isEnumStatement()) {
153 EnumStatement *enumstmt = statement->toEnumStatement();
155 // We pre-fill global enum types, since they may occur in function
156 // signatures. This should probably be somewhere else...
157 enumstmt->accept(this);
158 } else if (statement->isStructureStatement()) {
159 StructureStatement *node = statement->toStructureStatement();
161 if (!node->decl()->type())
163 } else if (statement->isFunctionTypeStatement()) {
164 FunctionTypeStatement *node = statement->toFunctionTypeStatement();
166 if (!node->decl()->type())
171 for (size_t i = 0; i < tree_->statements()->length(); i++) {
172 Statement *statement = tree_->statements()->at(i);
174 // We can't double-process these. Maybe put this check somewhere else.
175 if (statement->isEnumStatement())
178 statement->accept(this);
181 if (!determineLiveFunctions())
184 return !cc_.failures();
188 SemanticAnalysis::determineLiveFunctions()
190 Vector<NamedFunction *> worklist;
193 for (size_t i = 0; i < tree_->statements()->length(); i++) {
194 Statement *statement = tree_->statements()->at(i);
195 if (!statement->isFunctionStatement())
198 FunctionStatement *stmt = statement->toFunctionStatement();
199 NamedFunction *fun = stmt->fun();
203 for (size_t i = 0; i < fun->usedGlobals()->length(); i++) {
204 NamedFunction *name = fun->usedGlobals()->at(i)->toNamedFunction();
206 // Names in these lists are always unused, however, we mark them
207 // as used while inserting into the work queue, to avoid double-
212 if (!worklist.append(name))
219 while (!worklist.empty()) {
220 NamedFunction *fun = worklist.popCopy();
222 for (size_t i = 0; i < fun->usedGlobals()->length(); i++) {
223 NamedFunction *name = fun->usedGlobals()->at(i)->toNamedFunction();
226 if (!worklist.append(name))
236 SemanticAnalysis::bindType(const SourcePosition &pos, BoundName *name)
239 return zone_->types()->getPrimitive(PrimitiveType_Int32);
241 if (name->kind() == BoundName::UNBOUND) {
242 cc_.reportError(pos, Message_TypeNotFound, name->name()->chars());
246 if (name->kind() != BoundName::TYPE) {
247 cc_.reportError(pos, Message_IdentifierIsNotAType, name->name()->chars());
258 SemanticAnalysis::visitAndApplyType(Expression *expression)
260 expression->accept(this);
261 return expression->type();
265 SemanticAnalysis::visitForLoad(Expression *expression)
267 Local<Type> type(zone_, visitAndApplyType(expression));
271 if (type->isReference()) {
272 expression->setType(type->contained());
273 } else if (expression->isCallExpression()) {
274 if (type->isVoid()) {
275 CallExpression *call = expression->toCallExpression();
276 cc_.reportError(call->callee()->pos(), Message_FunctionDoesNotReturnValue);
281 return expression->type();
284 // :TODO: this leaks an interior pointer.
286 ke::GetTypeName(Type *type)
290 if (type->isFunction())
294 if (type->isEnum() || type->isStruct())
295 return type->name()->chars();
296 if (type->isReference())
297 type = type->contained();
298 switch (type->primitive()) {
299 case PrimitiveType_Bool:
301 case PrimitiveType_Char:
303 case PrimitiveType_Int32:
305 case PrimitiveType_Float:
313 SemanticAnalysis::unaryTypeError(AstNode *node, TokenKind token, Handle<Type> type)
315 const char *op = TokenNames[token];
316 const char *name = GetTypeName(type);
318 cc_.reportError(node->pos(), Message_UnaryTypeError, op, name);
322 SemanticAnalysis::binaryTypeError(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
324 const char *op = TokenNames[token];
325 const char *leftName = GetTypeName(left);
326 const char *rightName = GetTypeName(right);
328 cc_.reportError(node->pos(), Message_BinaryTypeError, op, leftName, rightName);
332 SemanticAnalysis::typeCheckBinary(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
334 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
335 (token >= TOK_ASSIGN_ADD && token <= TOK_ASSIGN_DIV))
337 // If either side is a float, the other side must be a float or int.
338 if (left->isFloat() || right->isFloat()) {
339 Type *floatType = left->isFloat() ? left : right;
340 Type *other = left->isFloat() ? right : left;
341 if (other->isFloat() || other->isInt32())
346 if (token == TOK_OR || token == TOK_AND) {
347 if (!canTest(node, left) || !canTest(node, right))
349 return zone_->types()->getPrimitive(PrimitiveType_Bool);
352 if (token >= TOK_EQUALS && token <= TOK_GE) {
353 if ((left->isFloat() || left->isInt32()) &&
354 (right->isFloat() || right->isInt32()))
356 return zone_->types()->getPrimitive(PrimitiveType_Bool);
358 binaryTypeError(node, token, left, right);
362 if (!left->isInt32() || !right->isInt32()) {
363 binaryTypeError(node, token, left, right);
371 SemanticAnalysis::canTest(AstNode *node, Handle<Type> type)
373 if (!type->isPrimitive() && !type->isEnum()) {
374 cc_.reportError(node->pos(), Message_ArrayIsNotBoolean);
381 SemanticAnalysis::visitForLValue(Expression *expression)
383 if (expression->isIndexExpression()) {
384 Type *type = visitAndApplyType(expression);
388 // if (type->isConst()) {
389 // cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
396 if (expression->isFieldExpression()) {
397 Type *type = visitAndApplyType(expression);
401 // if (expression->toFieldExpression()->left()->type()->isConst()) {
402 // cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
409 if (!expression->isNameProxy()) {
410 cc_.reportError(expression->pos(), Message_ExpectedLValue);
414 NameProxy *proxy = expression->toNameProxy();
415 if (!proxy->binding()->kind() == BoundName::VARIABLE) {
416 cc_.reportError(expression->pos(), Message_ExpectedLValue);
420 Variable *var = proxy->binding()->toVariable();
424 if (var->type()->isReference()) {
425 if (var->type()->isConst()) {
426 cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
429 return var->type()->contained();
434 SemanticAnalysis::ControlStatus
435 SemanticAnalysis::visitForControl(Statement *statement)
437 ControlScope scope(&control_);
438 statement->accept(this);
439 return scope.status();
443 SemanticAnalysis::visit(NameProxy *name)
445 BoundName *binding = name->binding();
447 if (binding->scope()->kind() == Scope::GLOBAL) {
448 if (!function_ || function_->isPublic()) {
449 // Whatever we're referencing must be kept alive no matter what.
450 // As such, we simply mark it used, and don't do anything special.
452 } else if (!binding->used() && binding->kind() == BoundName::FUNCTION) {
453 // Otherwise, we're inside a normal stock or function. Since we
454 // don't really know if we've been used yet, we shouldn't
455 // prematurely references as alive. Instead, we keep a list of
456 // which names have been used, so we can mark them later if needed.
458 // Note that we skip this step if the binding is already in the
460 if (!function_->addUsedGlobal(binding))
465 name->setType(binding->type());
469 SemanticAnalysis::visit(Assignment *node)
471 Local<Type> exprType(zone_, visitForLoad(node->expression()));
475 Local<Type> type(zone_, visitForLValue(node->lvalue()));
479 if (node->token() != TOK_ASSIGN) {
480 if (!typeCheckBinary(node, node->token(), type, exprType))
484 if (!typeCheckAssignment(node->pos(), exprType, type, true))
491 SemanticAnalysis::visit(IncDecExpression *node)
493 Local<Type> type(zone_, visitForLValue(node->expression()));
497 assert(!type->isReference());
499 if (!type->isInt32() && !type->isFloat()) {
500 unaryTypeError(node, node->token(), type);
508 SemanticAnalysis::visit(UnaryExpression *node)
510 Local<Type> type(zone_, visitForLoad(node->expression()));
514 switch (node->token())
517 if (!canTest(node->expression(), type))
519 type = zone_->types()->getPrimitive(PrimitiveType_Int32);
526 if (!type->isFloat() && !type->isInt32()) {
527 unaryTypeError(node, node->token(), type);
535 Local<Type> to(zone_, bindType(node->pos(), node->type()));
539 if ((!type->isFloat() && !type->isInt32OrEnum()) ||
540 (!to->isFloat() && !to->isInt32OrEnum()))
542 unaryTypeError(node, node->token(), type);
551 assert(node->token() == TOK_TILDE);
552 if (!type->isInt32()) {
553 unaryTypeError(node, node->token(), type);
562 SemanticAnalysis::visit(TernaryExpression *node)
564 Local<Type> type(zone_, visitForLoad(node->condition()));
568 if (!canTest(node->condition(), type))
571 Local<Type> left(zone_, visitForLoad(node->left()));
572 Local<Type> right(zone_, visitForLoad(node->right()));
577 binaryTypeError(node, TOK_QMARK, left, right);
583 SemanticAnalysis::visit(BinaryExpression *node)
585 Local<Type> left(zone_, visitForLoad(node->left()));
586 Local<Type> right(zone_, visitForLoad(node->right()));
590 Local<Type> result(zone_, typeCheckBinary(node, node->token(), left, right));
594 node->setType(result);
598 SemanticAnalysis::visit(ReturnStatement *node)
600 // Set this early, so if we error we don't get more errors.
601 control_->returns(Returns_Always);
603 if (!node->expression()) {
604 if (!function_->type()->returnType()->isVoid())
605 cc_.reportError(node->pos(), Message_NotAllPathsReturnValue);
609 Local<Type> type(zone_, visitForLoad(node->expression()));
613 Local<Type> returnType(zone_, function_->type()->returnType());
614 if (!typeCheckAssignment(node->pos(), type, returnType, true))
619 SemanticAnalysis::visit(ForStatement *node)
621 LoopScope loop(&loop_);
624 scope_ = node->scope();
626 if (node->initialization())
627 node->initialization()->accept(this);
629 if (node->condition()) {
630 Local<Type> type(zone_, visitForLoad(node->condition()));
631 if (!type || !canTest(node->condition(), type)) {
637 node->update()->accept(this);
639 ControlStatus status = visitForControl(node->body());
641 // If there is a condition, we treat this like a while loop. Otherwise,
642 // join point is only reachable if the loop contains a break. The
643 // termination status doesn't tell us anything yet.
644 if (node->condition() || loop.breaks())
645 control_->merge(status, ControlStatus(false, Returns_Never));
647 control_->terminate(status.returns());
650 scope_ = scope_->enclosing();
654 SemanticAnalysis::visit(WhileStatement *node)
656 LoopScope loop(&loop_);
658 Local<Type> type(zone_, visitForLoad(node->condition()));
659 if (!type || !canTest(node->condition(), type)) {
663 ControlStatus status = visitForControl(node->body());
665 // Detect loops that will always have a fork in the control-flow graph.
666 // This will be a |while| loop, or a |do-while| loop whose body does
669 // For now, we treat these as an |if| regardless of the direction the
670 // branch can take. That means the control-flow is always conditional.
671 if (node->token() == TOK_WHILE ||
672 !status.terminates() ||
675 control_->merge(status, ControlStatus(false, Returns_Never));
677 // At this point, we've got a do-while loop with a |return| or
678 // |continue|, meaning that the rest of the block is unreachable.
679 control_->terminate(status.returns());
684 SemanticAnalysis::visit(BlockStatement *node)
687 scope_ = node->scope();
688 for (size_t i = 0; i < node->statements()->length(); i++) {
689 Statement *statement = node->statements()->at(i);
690 statement->accept(this);
693 scope_ = scope_->enclosing();
697 IsScalarString(Type *type)
699 if (type->isPrimitive() && type->primitive() == PrimitiveType_Char)
701 if (type->isReference())
702 return IsScalarString(type->contained());
706 static const int INFER_ARRAY_SIZE = 0;
707 static const int EVAL_ARRAY_SIZE = -1;
708 static const int DYNAMIC_ARRAY_SIZE = -2;
711 SemanticAnalysis::evaluateDimensions(ExpressionList *exprs, int dims[MAX_ARRAY_DEPTH])
713 bool hadEmptySize = false;
715 for (size_t i = 0; i < exprs->length(); i++) {
716 Expression *expr = exprs->at(i);
718 dims[i] = INFER_ARRAY_SIZE;
724 if (EvaluateForConstant(expr, &box) && box.type() == PrimitiveType_Int32) {
725 int size = box.toInt();
727 cc_.reportError(expr->pos(), Message_BadArraySize);
735 Local<Type> exprType(zone_, visitForLoad(expr));
739 if (!IsPrimitiveType(exprType, PrimitiveType_Int32)) {
740 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
745 cc_.reportError(expr->pos(), Message_BadDynamicInitializer);
749 dims[i] = EVAL_ARRAY_SIZE;
756 SemanticAnalysis::inferFixedArrayLiteral(ArrayLiteral *literal, Handle<Type> contained,
757 int dims[MAX_ARRAY_DEPTH],
758 unsigned dimcount, unsigned level)
760 if (dims[level] == EVAL_ARRAY_SIZE) {
761 cc_.reportError(literal->pos(), Message_CannotInitializeEvalArray);
765 if (dims[level] == INFER_ARRAY_SIZE) {
766 // Strings always become dynamic arrays.
767 if (level != dimcount - 1 || !IsPrimitiveType(contained, PrimitiveType_Char))
768 dims[level] = literal->expressions()->length();
769 } else if (dims[level] == DYNAMIC_ARRAY_SIZE) {
770 cc_.reportError(literal->pos(), Message_CannotInitializeEvalArray);
773 if (literal->expressions()->length() != unsigned(dims[level])) {
774 cc_.reportError(literal->pos(), Message_ArrayDimensionSizeMismatch, level + 1);
779 if (level == dimcount - 2 && IsPrimitiveType(contained, PrimitiveType_Char)) {
780 for (size_t i = 0; i < literal->expressions()->length(); i++) {
781 Expression *expr = literal->expressions()->at(i);
782 if (!expr->isStringLiteral()) {
783 cc_.reportError(expr->pos(), Message_ExpectedStringLiteral);
787 StringLiteral *lit = expr->toStringLiteral();
788 if (dims[level + 1] > 0 &&
789 unsigned(dims[level]) < lit->string()->length())
791 cc_.reportError(lit->pos(), Message_ArrayDimensionSizeMismatch, level + 2);
794 if (!visitAndApplyType(lit))
797 } else if (level == dimcount - 1) {
798 Local<Type> type(zone_);
799 for (size_t i = 0; i < literal->expressions()->length(); i++) {
800 Expression *expr = literal->expressions()->at(i);
801 if (expr->isArrayLiteral()) {
802 cc_.reportError(expr->pos(), Message_ArrayDimensionsMismatch);
806 if ((type = visitAndApplyType(expr)) == NULL)
809 if (!typeCheckAssignment(expr->pos(), type, contained, true))
813 for (size_t i = 0; i < literal->expressions()->length(); i++) {
814 Expression *expr = literal->expressions()->at(i);
815 if (!expr->isArrayLiteral()) {
816 cc_.reportError(expr->pos(), Message_ArrayDimensionsMismatch);
820 assert(expr->toArrayLiteral()->isFixed());
822 if (!inferFixedArrayLiteral(expr->toArrayLiteral(),
837 SemanticAnalysis::visit(VariableDeclaration *node)
839 Local<Type> type(zone_, bindType(node->pos(), node->type()));
843 if (node->postDimensions() || type->isArray()) {
844 // The type could be an array type, so sum the type and postDimensions
846 unsigned dimcount = node->postDimensions()->length();
848 dimcount += type->levels();
849 if (dimcount > MAX_ARRAY_DEPTH) {
850 cc_.reportError(node->pos(), Message_MaximumArrayDepth);
854 // Take an initial guess at the array dimension sizes.
855 int dims[MAX_ARRAY_DEPTH];
856 if (!evaluateDimensions(node->postDimensions(), dims))
859 // Now add in the type's array dimensions.
860 Local<Type> contained(zone_, type);
861 for (size_t i = node->postDimensions()->length(); i < dimcount; i++) {
862 if (type->isFixedLength())
863 dims[i] = type->fixedLength();
865 dims[i] = DYNAMIC_ARRAY_SIZE;
866 contained = contained->contained();
869 Expression *initializer = node->initialization();
871 initializer->isArrayLiteral() &&
872 initializer->toArrayLiteral()->isFixed())
874 // Fixed array initializers are special; we use them to infer any
875 // missing information in the original array. We do not evaluate
876 // the array initializer as an expression.
877 if (!inferFixedArrayLiteral(initializer->toArrayLiteral(),
888 // We now have enough information to build the actual array type.
889 // Start from the original dimcount, not the one computed for
891 for (size_t i = node->postDimensions()->length() - 1;
892 i < node->postDimensions()->length();
895 int size = dims[i] > 0
897 : Type::DYNAMIC_ARRAY_SIZE;
899 type = zone_->types()->newArray(type, size, false);
904 // Finally, if we had a non-fixed initializer, make sure it type
907 Local<Type> right(zone_, visitForLoad(initializer));
911 if (!typeCheckAssignment(node->pos(), right, type, true))
915 if (node->initialization()) {
916 Local<Type> right(zone_, visitForLoad(node->initialization()));
919 if (!typeCheckAssignment(node->pos(), right, type, true))
923 if (type->isPrimitive() && type->primitive() == PrimitiveType_Char) {
924 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
929 // If this variable is stack allocated, we could use the LIFO heap
930 // to allocate it. If that's the case, make sure to reserve a slot
931 // so we can unwind the LIFO heap at the end of this scope.
932 if (!node->variable()->needsHeapAllocation()) {
933 if (type->isArray() || type->isStruct())
934 scope_->setUsesLifoHeap();
937 node->variable()->setType(type);
941 SemanticAnalysis::visit(IntegerLiteral *node)
943 node->setType(zone_->types()->getPrimitive(PrimitiveType_Int32));
947 SemanticAnalysis::visit(BooleanLiteral *node)
949 node->setType(zone_->types()->getPrimitive(PrimitiveType_Bool));
953 SemanticAnalysis::visit(ExpressionStatement *node)
955 visitAndApplyType(node->expression());
959 SemanticAnalysis::evaluateDefaultParameter(Handle<Type> type, Parameter *parameter)
961 Local<Type> given(zone_, visitForLoad(parameter->initializer()));
964 if (EvaluateForConstant(parameter->initializer(), &prim)) {
965 if (!typeCheckAssignment(parameter->initializer()->pos(), given, type, false))
968 if (prim.type() == PrimitiveType_Int32)
969 return Box::New(zone_, given, prim.toInt());
970 return Box::New(zone_, given, prim.toFloat());
971 } else if (parameter->initializer()->isStringLiteral()) {
972 StringLiteral *literal = parameter->initializer()->toStringLiteral();
974 if (!typeCheckAssignment(parameter->initializer()->pos(), given, type, false))
977 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, given));
981 Local<Array> array(zone_,
982 Array::NewString(zone_,
984 literal->string()->raw(),
985 literal->string()->length(),
990 return Box::NewObj(zone_, given, array, Heap::Tenure_Old);
993 cc_.reportError(parameter->initializer()->pos(), Message_MustBeConstant);
998 SemanticAnalysis::buildFunctionArgs(AstNode *node, TokenKind kind, const FunctionSignature &sig,
999 FixedArray **argsp, FixedArray **defaultsp)
1001 Local<FixedArray> args(zone_, FixedArray::New(zone_, sig.parameters()->length(), Heap::Tenure_Old));
1005 Local<FixedArray> defaults(zone_);
1007 // Apply types to arguments.
1008 for (size_t i = 0; i < sig.parameters()->length(); i++) {
1009 Parameter *parameter = sig.parameters()->at(i);
1011 Local<Type> type(zone_, bindType(parameter->variable()->pos(), parameter->type()));
1015 if (parameter->reference()) {
1016 if (parameter->dimensions()) {
1017 cc_.reportError(parameter->variable()->pos(), Message_ArrayCantBeReference);
1021 if (type->isStruct()) {
1022 cc_.reportError(parameter->variable()->pos(), Message_StructCantBeReference);
1026 type = zone_->types()->getReference(type, parameter->isConst());
1029 } else if (parameter->dimensions()) {
1030 type = buildArrayType(type, parameter->dimensions(), parameter->isConst());
1034 if (kind == TOK_NATIVE && type->levels() > 1) {
1035 cc_.reportError(parameter->variable()->pos(), Message_MultiArrayInNative);
1040 if (IsScalarString(type)) {
1041 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
1045 args->set(zone_, i, type);
1046 parameter->variable()->setType(type);
1048 if (parameter->initializer()) {
1050 defaults = FixedArray::New(zone_, sig.parameters()->length(), Heap::Tenure_Old);
1055 Local<Box> box(zone_, evaluateDefaultParameter(type, parameter));
1059 defaults->set(zone_, i, box);
1064 *defaultsp = defaults;
1070 SemanticAnalysis::visit(FunctionTypeStatement *node)
1072 if (node->decl()->type())
1075 Local<FixedArray> args(zone_);
1076 Local<FixedArray> defaults(zone_);
1078 const FunctionSignature &sig= node->signature();
1079 if (!buildFunctionArgs(node,
1083 defaults.address()))
1088 Local<Type> returnType(zone_);
1089 if (sig.returnType())
1090 returnType = bindType(node->pos(), sig.returnType());
1092 returnType = zone_->types()->getPrimitive(PrimitiveType_Int32);
1097 Local<Type> funtype(zone_, zone_->types()->newFunction(returnType, args, defaults));
1101 node->decl()->setType(funtype);
1105 SemanticAnalysis::buildArrayType(Handle<Type> type, ExpressionList *dimensions, bool isConst)
1107 Local<Type> arrayType(zone_, type);
1109 unsigned dimcount = dimensions->length();
1110 if (type->isArray())
1111 dimcount += type->levels();
1113 if (dimcount > MAX_ARRAY_DEPTH) {
1114 cc_.reportError(dimensions->at(dimensions->length() - 1)->pos(),
1115 Message_MaximumArrayDepth);
1119 // Note: constness is sort of bogus. Fix this sometime.
1120 for (size_t i = dimensions->length() - 1; i < dimensions->length(); i--) {
1121 Expression *expr = dimensions->at(i);
1123 arrayType = zone_->types()->newArray(arrayType, Type::DYNAMIC_ARRAY_SIZE, isConst);
1131 if (!EvaluateForConstant(expr, &box) || box.type() != PrimitiveType_Int32) {
1132 cc_.reportError(expr->pos(), Message_ArraySizeMustBeConstant);
1136 if (box.toInt() <= 0) {
1137 cc_.reportError(expr->pos(), Message_BadArraySize);
1141 arrayType = zone_->types()->newArray(arrayType, box.toInt(), isConst);
1150 SemanticAnalysis::preanalyze(FunctionStatement *node)
1152 Local<FixedArray> args(zone_);
1153 Local<FixedArray> defaults(zone_);
1155 const FunctionSignature &sig = node->signature();
1156 if (!buildFunctionArgs(node,
1157 node->fun()->token(),
1160 defaults.address()))
1165 Local<Type> returnType(zone_);
1166 if (sig.returnType() ||
1167 node->hasExplicitReturn() ||
1168 node->fun()->isNative())
1170 returnType = bindType(node->pos(), sig.returnType());
1172 returnType = zone_->types()->getVoid();
1177 if (sig.returnDimensions()) {
1178 returnType = buildArrayType(returnType, sig.returnDimensions(), false);
1183 if (IsScalarString(returnType)) {
1184 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
1188 Local<Type> funtype(zone_);
1189 if (node->fun()->isNative())
1190 funtype = zone_->types()->newNative(returnType, args, defaults, node->fun()->isNativeVariadic());
1192 funtype = zone_->types()->newFunction(returnType, args, defaults);
1196 // If the function already has a type, it was forward declared before, and
1197 // now this is our chance to type check the second declaration.
1198 if (node->fun()->type()) {
1199 Local<Type> forward(zone_, node->fun()->type());
1200 if (!Type::Compare(funtype, forward)) {
1201 cc_.reportError(node->pos(), Message_ForwardDeclareMismatches);
1204 node->fun()->setForwardType(forward);
1207 node->fun()->setType(funtype);
1213 SemanticAnalysis::visit(FunctionStatement *node)
1215 function_ = node->fun();
1216 scope_ = node->scope();
1218 ControlScope control(&control_);
1220 node->body()->accept(this);
1222 ControlStatus status = control.status();
1223 if (status.returns() == Returns_Sometimes) {
1224 cc_.reportError(node->pos(), Message_NotAllPathsReturnValue);
1225 } else if (status.returns() == Returns_Never) {
1226 if (!function_->type()->returnType()->isVoid())
1227 cc_.reportError(node->pos(), Message_MissingReturnValue);
1236 SemanticAnalysis::typeMismatch(const SourcePosition &pos, Handle<Type> actual, Handle<Type> given)
1238 cc_.reportError(pos, Message_TypeMismatch,
1239 GetTypeName(actual),
1240 GetTypeName(given));
1244 SemanticAnalysis::typeCheckArrayAssignment(const SourcePosition &pos, Handle<Type> argGiven,
1245 Handle<Type> argActual, bool forAssign)
1247 Local<Type> actual(zone_, argActual);
1248 Local<Type> given(zone_, argGiven);
1250 if (!given->isArray()) {
1251 cc_.reportError(pos, Message_ExpectedArray);
1254 if (given->levels() != actual->levels()) {
1255 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
1260 while (given->isArray()) {
1261 if (actual->isFixedLength()) {
1263 if (!given->isFixedLength()) {
1264 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1268 if (actual->isCharArray()) {
1269 // String assignment can have a truncated |given|.
1270 if (given->fixedLength() > actual->fixedLength()) {
1271 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
1275 if (given->fixedLength() != actual->fixedLength()) {
1276 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1281 } else if (given->isFixedLength()) {
1282 // We do not allow assignments in the form:
1285 // Otherwise, the following code could break the size guarantees
1286 // of the right-hand side:
1295 // Now |x[0]| contains a 4-length array.
1297 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1301 given = given->contained();
1302 actual = actual->contained();
1306 return typeCheckAssignment(pos, given, actual, forAssign);
1310 SemanticAnalysis::typeCheckAssignment(const SourcePosition &pos, Handle<Type> argGiven,
1311 Handle<Type> argActual, bool forAssign)
1313 Local<Type> actual(zone_, argActual);
1314 Local<Type> given(zone_, argGiven);
1316 if (actual->isArray())
1317 return typeCheckArrayAssignment(pos, given, actual, forAssign);
1319 if (given->isArray()) {
1320 cc_.reportError(pos, Message_CannotAssignArrayToScalar);
1324 // The given type may not have been dereferenced.
1325 if (given->isReference())
1326 given = given->contained();
1327 if (actual->isReference())
1328 actual = actual->contained();
1330 // We coerce unchecked to a few things.
1331 if (actual->isUnchecked() || given->isUnchecked()) {
1332 Type *check = actual->isUnchecked() ? given : actual;
1333 if (check->isUnchecked() ||
1341 typeMismatch(pos, actual, given);
1345 if (given->isFunction() && actual->isFunction()) {
1346 if (!Type::Compare(given, actual)) {
1347 typeMismatch(pos, actual, given);
1353 if (actual->isEnum()) {
1354 if (!given->isEnum() || actual != given) {
1355 typeMismatch(pos, actual, given);
1361 if (actual->isStruct()) {
1362 if (!given->isStruct() || actual != given) {
1363 typeMismatch(pos, actual, given);
1369 if (given->isEnum() || given->isFunction() || given->isStruct()) {
1370 typeMismatch(pos, actual, given);
1374 // This coercion is trivial.
1375 if (given->isBool() && actual->isInt32())
1378 if (given->primitive() != actual->primitive()) {
1379 typeMismatch(pos, actual, given);
1387 SemanticAnalysis::typeCheckParameter(AstNode *node, Handle<Type> given, Handle<Type> actual)
1389 return typeCheckAssignment(node->pos(), given, actual, false);
1393 SemanticAnalysis::checkArgumentCount(Handle<Type> type, unsigned actual)
1395 if (type->parameters()->length() == actual)
1398 if (actual > type->parameters()->length()) {
1399 if (!type->isNative() || !type->isNativeVariadic())
1404 if (!type->defaults())
1407 // Missing arguments. See if there's a default argument for each missing
1409 for (unsigned i = actual; i < type->parameters()->length(); i++) {
1410 if (!type->defaults()->at(i))
1418 SemanticAnalysis::visit(CallExpression *node)
1420 Local<Type> type(zone_, visitForLoad(node->callee()));
1424 if (!type->isFunction()) {
1425 cc_.reportError(node->pos(), Message_CalleeNotFunction);
1429 if (!checkArgumentCount(type, node->arguments()->length())) {
1430 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
1434 // NamedFunction *fun = node->callee()->toNameProxy()->binding()->toNamedFunction();
1435 // if (fun->isForward()) {
1436 // cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
1440 for (unsigned i = 0; i < node->arguments()->length(); i++) {
1441 // Note: we don't compute references unless the callee needs a
1443 Expression *expression = node->arguments()->at(i);
1444 Local<Type> given(zone_, visitAndApplyType(expression));
1448 // Since we skip a load, check for a call expression that returns void.
1449 if (given->isVoid()) {
1450 assert(expression->isCallExpression());
1451 CallExpression *call = expression->toCallExpression();
1452 cc_.reportError(call->callee()->pos(), Message_FunctionDoesNotReturnValue);
1456 bool mustComputeReference;
1457 if (i >= type->parameters()->length()) {
1458 // Special handling for natives. Arguments past the formal must
1459 // always have references computed. However, arrays are already
1460 // references for natives.
1461 assert(type->isNative() && type->isNativeVariadic());
1462 mustComputeReference = !given->isReference() && !given->isArray();
1464 Local<Type> actual(zone_, type->parameterAt(i));
1466 if (expression->isIndexExpression()) {
1467 // Disabled until we can make it work.
1469 if (actual->isArray()) {
1470 // We special case the ability to pass x[y] into x[], which
1471 // creates an array slice. We only do this if we know the
1472 // assignment would otherwise not type-check.
1473 IndexExpression *index = expression->toIndexExpression();
1474 if (index->left()->type()->levels() == actual->levels())
1475 given = index->left()->type();
1478 if (actual->isReference()) {
1479 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
1484 if (!typeCheckParameter(expression, given, actual))
1486 mustComputeReference = actual->isReference() && !given->isReference();
1489 // If the actual is a reference, and the given is not, we'll need to
1490 // compute a reference, which may be allocated on the stack.
1491 if (mustComputeReference)
1492 scope_->setUsesLifoHeap();
1495 node->setType(type->returnType());
1499 SemanticAnalysis::ControlScope::inherit(const ControlStatus &other)
1501 if (other.returns() < status().returns())
1504 if (other.terminates())
1505 terminate(other.returns());
1507 returns(other.returns());
1511 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
1513 // If both sides terminate in a return, we consider this a return as well.
1514 if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
1515 terminate(Returns_Always);
1519 ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
1521 : Returns_Sometimes;
1523 if (left.terminates() && right.terminates())
1530 SemanticAnalysis::visit(IfStatement *node)
1532 Local<Type> type(zone_, visitForLoad(node->condition()));
1536 if (!canTest(node, type))
1539 ControlStatus trueBranch = visitForControl(node->ifTrue());
1540 ControlStatus falseBranch = ControlStatus(false, Returns_Never);
1542 if (node->ifFalse())
1543 falseBranch = visitForControl(node->ifFalse());
1545 control_->merge(trueBranch, falseBranch);
1549 SemanticAnalysis::visit(IndexExpression *node)
1551 Local<Type> left(zone_, visitForLoad(node->left()));
1552 Local<Type> right(zone_, visitForLoad(node->right()));
1554 if (!left || !right)
1557 if (!right->isInt32() && !right->isEnum()) {
1558 cc_.reportError(node->right()->pos(), Message_IndexMustBeInteger);
1561 if (!left->isArray()) {
1562 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
1566 // Note: char arrays are automatically up-casted to return an int32.
1567 if (left->isCharArray())
1568 node->setType(zone_->types()->getPrimitive(PrimitiveType_Int32));
1570 node->setType(left->contained());
1574 SemanticAnalysis::visit(FieldExpression *node)
1576 Local<Type> left(zone_, visitForLoad(node->left()));
1580 if (!left->isStruct()) {
1581 cc_.reportError(node->pos(), Message_PropertyNotFound, node->field()->chars(),
1586 Local<String> field(zone_, node->field());
1589 Local<Descriptor> desc(zone_, left->lookupField(field, &offset));
1591 cc_.reportError(node->pos(), Message_PropertyNotFound, node->field()->chars(),
1596 node->setFieldIndex(offset);
1597 node->setType(desc->type());
1601 SemanticAnalysis::visit(EnumStatement *node)
1603 Local<String> name(zone_, node->name());
1604 Local<Type> type(zone_);
1606 type = zone_->types()->newEnum(name);
1608 type = zone_->types()->getPrimitive(PrimitiveType_Int32);
1614 node->decl()->setType(type);
1617 for (size_t i = 0; i < node->entries()->length(); i++) {
1618 EnumStatement::Entry &entry = node->entries()->at(i);
1620 BoxedPrimitive box = BoxedPrimitive::Int(value);
1622 entry.expr->accept(this);
1623 if (!EvaluateForConstant(entry.expr, &box) || box.type() != PrimitiveType_Int32) {
1624 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
1628 assert(box.type() == PrimitiveType_Int32);
1629 value = box.toInt();
1632 entry.name->set(type, box);
1638 SortCaseIntValues(const void *p1, const void *p2)
1640 CaseValue *v1 = (CaseValue *)p1;
1641 CaseValue *v2 = (CaseValue *)p2;
1643 return v1->box.toInt() - v2->box.toInt();
1647 SemanticAnalysis::visit(SwitchStatement *node)
1649 Local<Type> caseType(zone_, visitForLoad(node->expression()));
1653 if (!caseType->isEnum() && !caseType->isInt32()) {
1654 cc_.reportError(node->pos(), Message_CaseMustBeInteger);
1658 PoolList<CaseValue> *values = new (zone_->pool()) PoolList<CaseValue>();
1659 ControlStatus status = ControlStatus(false, Returns_Never);
1661 Local<Type> check(zone_);
1662 for (size_t i = 0; i < node->cases()->length(); i++) {
1663 Case *c = node->cases()->at(i);
1665 check = visitForLoad(c->expression());
1669 if (!typeCheckAssignment(c->expression()->pos(), check, caseType, false))
1673 if (!EvaluateForConstant(c->expression(), &v.box)) {
1674 cc_.reportError(c->expression()->pos(), Message_CaseMustBeConstant);
1677 if (!values->append(v))
1681 for (size_t j = 0; j < c->others()->length(); j++) {
1682 Expression *expr = c->others()->at(j);
1683 check = visitForLoad(expr);
1687 if (!typeCheckAssignment(expr->pos(), check, caseType, false))
1691 if (!EvaluateForConstant(expr, &v.box)) {
1692 cc_.reportError(expr->pos(), Message_CaseMustBeConstant);
1695 if (!values->append(v))
1700 ControlStatus latest = visitForControl(c->statement());
1703 control_->merge(status, latest);
1708 if (node->defaultCase()) {
1709 ControlStatus latest = visitForControl(node->defaultCase());
1711 if (node->cases()->length()) {
1712 // If we had any other cases, we must merge.
1713 control_->merge(status, latest);
1715 // Otherwise, control-flow always flows through here.
1716 control_->inherit(latest);
1718 } else if (node->cases()->length()) {
1719 control_->merge(status, ControlStatus(false, Returns_Never));
1722 if (values->length() > 1) {
1723 qsort(values->buffer(), values->length(), sizeof(CaseValue), SortCaseIntValues);
1725 for (size_t i = 1; i < values->length(); i++) {
1726 CaseValue &prev = values->at(i - 1);
1727 CaseValue &cur = values->at(i);
1728 if (prev.box.toInt() == cur.box.toInt()) {
1729 cc_.reportError(node->cases()->at(cur.statement)->expression()->pos(), Message_CaseHasSameValue);
1735 node->setCaseValueList(values);
1739 SemanticAnalysis::visit(StructureStatement *node)
1741 // If this node already has a type, it was pre-analyzed, so skip it.
1742 if (node->decl()->type())
1745 FieldList *fields = node->fields();
1746 Local<FixedArray> desctable(zone_, FixedArray::New(zone_, fields->length(), Heap::Tenure_Old));
1750 Vector<unsigned> composedList;
1751 StructureBufferBuilder builder;
1753 Local<Type> type(zone_);
1754 Local<String> name(zone_);
1755 Local<Descriptor> desc(zone_);
1756 for (size_t i = 0; i < fields->length(); i++) {
1757 StructureStatement::Field *field = fields->at(i);
1759 type = bindType(field->pos(), field->type());
1763 if (type->isPrimitive() && type->primitive() == PrimitiveType_Char) {
1764 cc_.reportError(field->pos(), Message_CannotDeclareStringCell);
1769 if (!builder.add(type, &offset))
1772 name = field->name();
1773 desc = Descriptor::New(zone_, name, type, offset);
1777 desctable->set(zone_, i, desc);
1779 if (type->isStruct() || type->isArray()) {
1780 if (!composedList.append(i))
1785 Local<FixedArray> composed(zone_);
1786 if (composedList.length()) {
1787 composed = FixedArray::New(zone_, composedList.length(), Heap::Tenure_Old);
1791 for (unsigned i = 0; i < composedList.length(); i++)
1792 composed->set(zone_, i, desctable->at(i));
1795 Local<StructMap> map(zone_, StructMap::New(zone_, builder, composed));
1799 name = node->decl()->name();
1800 type = zone_->types()->newStruct(name, desctable, map);
1805 node->decl()->setType(type);
1809 SemanticAnalysis::visit(StringLiteral *node)
1811 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Char));
1815 type = Type::NewArray(zone_, type, node->string()->length() + 1, true);
1819 node->setType(type);
1823 SemanticAnalysis::visit(FloatLiteral *node)
1825 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
1829 node->setType(type);
1833 SemanticAnalysis::visit(BreakStatement *node)
1836 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
1840 // Note: ignore breaks that occur in unreachable control-flow.
1841 if (!control_->status().terminates())
1844 control_->terminate(Returns_Never);
1848 SemanticAnalysis::visit(ContinueStatement *node)
1851 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
1855 // Note: ignore continues that occur in unreachable control-flow.
1856 if (!control_->status().terminates())
1857 loop_->addContinue();
1859 control_->terminate(Returns_Never);
1863 SemanticAnalysis::visit(ArrayLiteral *node)
1865 // We should never visit this.
1866 cc_.reportError(node->pos(), Message_UnexpectedArrayLiteral);