Basic support for parsing and creating types from structure syntax.
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 statement->accept(this);
167 for (size_t i = 0; i < tree_->statements()->length(); i++) {
168 Statement *statement = tree_->statements()->at(i);
169 statement->accept(this);
172 if (!determineLiveFunctions())
175 return !cc_.failures();
179 SemanticAnalysis::determineLiveFunctions()
181 Vector<NamedFunction *> worklist;
184 for (size_t i = 0; i < tree_->statements()->length(); i++) {
185 Statement *statement = tree_->statements()->at(i);
186 if (!statement->isFunctionStatement())
189 FunctionStatement *stmt = statement->toFunctionStatement();
190 NamedFunction *fun = stmt->fun();
194 for (size_t i = 0; i < fun->usedGlobals()->length(); i++) {
195 NamedFunction *name = fun->usedGlobals()->at(i)->toNamedFunction();
197 // Names in these lists are always unused, however, we mark them
198 // as used while inserting into the work queue, to avoid double-
203 if (!worklist.append(name))
210 while (!worklist.empty()) {
211 NamedFunction *fun = worklist.popCopy();
213 for (size_t i = 0; i < fun->usedGlobals()->length(); i++) {
214 NamedFunction *name = fun->usedGlobals()->at(i)->toNamedFunction();
217 if (!worklist.append(name))
227 SemanticAnalysis::bindType(const SourcePosition &pos, BoundName *name)
230 return zone_->types()->getPrimitive(PrimitiveType_Int32);
232 if (name->kind() == BoundName::UNBOUND) {
233 cc_.reportError(pos, Message_TypeNotFound, name->name()->chars());
237 if (name->kind() != BoundName::TYPE) {
238 cc_.reportError(pos, Message_IdentifierIsNotAType, name->name()->chars());
249 SemanticAnalysis::visitAndApplyType(Expression *expression)
251 expression->accept(this);
252 return expression->type();
256 SemanticAnalysis::visitForLoad(Expression *expression)
258 Local<Type> type(zone_, visitAndApplyType(expression));
262 if (type->isReference()) {
263 expression->setType(type->contained());
264 } else if (expression->isIndexExpression()) {
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())
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);
387 return type->contained();
390 if (!expression->isNameProxy()) {
391 cc_.reportError(expression->pos(), Message_ExpectedLValue);
395 NameProxy *proxy = expression->toNameProxy();
396 if (!proxy->binding()->kind() == BoundName::VARIABLE) {
397 cc_.reportError(expression->pos(), Message_ExpectedLValue);
401 Variable *var = proxy->binding()->toVariable();
405 if (var->type()->isReference()) {
406 if (var->type()->isConst()) {
407 cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
410 return var->type()->contained();
415 SemanticAnalysis::ControlStatus
416 SemanticAnalysis::visitForControl(Statement *statement)
418 ControlScope scope(&control_);
419 statement->accept(this);
420 return scope.status();
424 SemanticAnalysis::visit(NameProxy *name)
426 BoundName *binding = name->binding();
428 if (binding->scope()->kind() == Scope::GLOBAL) {
429 if (!function_ || function_->isPublic()) {
430 // Whatever we're referencing must be kept alive no matter what.
431 // As such, we simply mark it used, and don't do anything special.
433 } else if (!binding->used() && binding->kind() == BoundName::FUNCTION) {
434 // Otherwise, we're inside a normal stock or function. Since we
435 // don't really know if we've been used yet, we shouldn't
436 // prematurely references as alive. Instead, we keep a list of
437 // which names have been used, so we can mark them later if needed.
439 // Note that we skip this step if the binding is already in the
441 if (!function_->addUsedGlobal(binding))
446 name->setType(binding->type());
450 SemanticAnalysis::visit(Assignment *node)
452 Local<Type> exprType(zone_, visitForLoad(node->expression()));
456 Local<Type> type(zone_, visitForLValue(node->lvalue()));
460 if (node->token() != TOK_ASSIGN) {
461 if (!typeCheckBinary(node, node->token(), type, exprType))
465 if (!typeCheckAssignment(node, exprType, type, true))
472 SemanticAnalysis::visit(IncDecExpression *node)
474 Local<Type> type(zone_, visitForLValue(node->expression()));
478 assert(!type->isReference());
480 if (!type->isInt32() && !type->isFloat()) {
481 unaryTypeError(node, node->token(), type);
489 SemanticAnalysis::visit(UnaryExpression *node)
491 Local<Type> type(zone_, visitForLoad(node->expression()));
495 switch (node->token())
498 if (!canTest(node->expression(), type))
500 type = zone_->types()->getPrimitive(PrimitiveType_Int32);
507 if (!type->isFloat() && !type->isInt32()) {
508 unaryTypeError(node, node->token(), type);
516 Local<Type> to(zone_, bindType(node->pos(), node->type()));
520 if ((!type->isFloat() && !type->isInt32OrEnum()) ||
521 (!to->isFloat() && !to->isInt32OrEnum()))
523 unaryTypeError(node, node->token(), type);
532 assert(node->token() == TOK_TILDE);
533 if (!type->isInt32()) {
534 unaryTypeError(node, node->token(), type);
543 SemanticAnalysis::visit(TernaryExpression *node)
545 Local<Type> type(zone_, visitForLoad(node->condition()));
549 if (!canTest(node->condition(), type))
552 Local<Type> left(zone_, visitForLoad(node->left()));
553 Local<Type> right(zone_, visitForLoad(node->right()));
558 binaryTypeError(node, TOK_QMARK, left, right);
564 SemanticAnalysis::visit(BinaryExpression *node)
566 Local<Type> left(zone_, visitForLoad(node->left()));
567 Local<Type> right(zone_, visitForLoad(node->right()));
571 Local<Type> result(zone_, typeCheckBinary(node, node->token(), left, right));
575 node->setType(result);
579 SemanticAnalysis::visit(ReturnStatement *node)
581 // Set this early, so if we error we don't get more errors.
582 control_->returns(Returns_Always);
584 if (!node->expression()) {
585 if (!function_->type()->returnType()->isVoid())
586 cc_.reportError(node->pos(), Message_NotAllPathsReturnValue);
590 Local<Type> type(zone_, visitForLoad(node->expression()));
594 Local<Type> returnType(zone_, function_->type()->returnType());
595 if (!typeCheckAssignment(node, type, returnType, true))
600 SemanticAnalysis::visit(ForStatement *node)
602 LoopScope loop(&loop_);
605 scope_ = node->scope();
607 if (node->initialization())
608 node->initialization()->accept(this);
610 if (node->condition()) {
611 Local<Type> type(zone_, visitForLoad(node->condition()));
612 if (!type || !canTest(node->condition(), type)) {
618 node->update()->accept(this);
620 ControlStatus status = visitForControl(node->body());
622 // If there is a condition, we treat this like a while loop. Otherwise,
623 // join point is only reachable if the loop contains a break. The
624 // termination status doesn't tell us anything yet.
625 if (node->condition() || loop.breaks())
626 control_->merge(status, ControlStatus(false, Returns_Never));
628 control_->terminate(status.returns());
631 scope_ = scope_->enclosing();
635 SemanticAnalysis::visit(WhileStatement *node)
637 LoopScope loop(&loop_);
639 Local<Type> type(zone_, visitForLoad(node->condition()));
640 if (!type || !canTest(node->condition(), type)) {
644 ControlStatus status = visitForControl(node->body());
646 // Detect loops that will always have a fork in the control-flow graph.
647 // This will be a |while| loop, or a |do-while| loop whose body does
650 // For now, we treat these as an |if| regardless of the direction the
651 // branch can take. That means the control-flow is always conditional.
652 if (node->token() == TOK_WHILE ||
653 !status.terminates() ||
656 control_->merge(status, ControlStatus(false, Returns_Never));
658 // At this point, we've got a do-while loop with a |return| or
659 // |continue|, meaning that the rest of the block is unreachable.
660 control_->terminate(status.returns());
665 SemanticAnalysis::visit(BlockStatement *node)
668 scope_ = node->scope();
669 for (size_t i = 0; i < node->statements()->length(); i++) {
670 Statement *statement = node->statements()->at(i);
671 statement->accept(this);
674 scope_ = scope_->enclosing();
678 IsScalarString(Type *type)
680 if (type->isPrimitive() && type->primitive() == PrimitiveType_Char)
682 if (type->isReference())
683 return IsScalarString(type->contained());
688 SemanticAnalysis::visit(VariableDeclaration *node)
690 Local<Type> type(zone_, bindType(node->pos(), node->type()));
694 if (node->postDimensions()) {
695 Local<Type> init(zone_);
696 if (node->initialization()) {
697 if ((init = visitForLoad(node->initialization())) == NULL)
701 if (node->postDimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
702 cc_.reportError(node->pos(), Message_MaximumArrayDepth);
706 // If we have an initializer, make sure it's the same type.
707 if (init && node->postDimensions()->length() != init->levels()) {
708 cc_.reportError(node->pos(), Message_ArrayInitializerDepth);
712 Local<Type> check(zone_, init);
713 for (size_t i = node->postDimensions()->length() - 1; i < node->postDimensions()->length(); i--) {
714 Expression *expr = node->postDimensions()->at(i);
718 Local<Type> exprType(zone_, visitForLoad(expr));
722 if (!IsPrimitiveType(exprType, PrimitiveType_Int32)) {
723 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
728 if (EvaluateForConstant(expr, &box) && box.type() == PrimitiveType_Int32) {
731 cc_.reportError(expr->pos(), Message_BadArraySize);
734 if (size >= int(INT_MAX / sizeof(int))) {
735 cc_.reportError(expr->pos(), Message_ArraySizeTooBig);
740 if (check->elements() == -1) {
741 cc_.reportError(expr->pos(), Message_ArraySizeCannotBeDetermined);
745 if (check->isCharArray()) {
746 if (check->elements() > size) {
747 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
750 } else if (check->elements() != size) {
751 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, unsigned(i));
757 cc_.reportError(node->pos(), Message_DynamicArrayHasInitializer);
761 // here until we get dynamic array support.
762 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
766 // Infer the size from the initializer.
768 cc_.reportError(node->pos(), Message_ArraySizeNotSpecified);
771 if (init->elements() == -1) {
772 cc_.reportError(node->pos(), Message_ArraySizeCannotBeDetermined);
775 size = init->elements();
778 type = zone_->types()->unsafeArray(type, size, false);
783 check = check->contained();
786 // If this variable is stack allocated, we could use the LIFO heap
787 // to allocate it. If that's the case, make sure to reserve a slot
788 // so we can unwind the LIFO heap at the end of this scope.
789 if (!node->variable()->needsHeapAllocation())
790 scope_->setUsesLifoHeap();
792 if (node->initialization()) {
793 Local<Type> right(zone_, visitForLoad(node->initialization()));
796 if (!typeCheckAssignment(node, type, right, true))
799 if (type->primitive() == PrimitiveType_Char) {
800 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
805 node->variable()->setType(type);
809 SemanticAnalysis::visit(IntegerLiteral *node)
811 node->setType(zone_->types()->getPrimitive(PrimitiveType_Int32));
815 SemanticAnalysis::visit(BooleanLiteral *node)
817 node->setType(zone_->types()->getPrimitive(PrimitiveType_Bool));
821 SemanticAnalysis::visit(ExpressionStatement *node)
823 visitAndApplyType(node->expression());
827 SemanticAnalysis::preanalyze(FunctionStatement *node)
829 Local<FixedArray> args(zone_, FixedArray::New(zone_, node->parameters()->length(), Heap::Tenure_Old));
833 // Apply types to arguments.
834 for (size_t i = 0; i < node->parameters()->length(); i++) {
835 Parameter *parameter = node->parameters()->at(i);
837 Local<Type> type(zone_, bindType(parameter->variable()->pos(), parameter->type()));
841 if (parameter->reference()) {
842 if (parameter->dimensions()) {
843 cc_.reportError(parameter->variable()->pos(), Message_ArrayCantBeReference);
847 type = zone_->types()->getReference(type, parameter->isConst());
850 } else if (parameter->dimensions()) {
851 if (parameter->dimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
852 cc_.reportError(parameter->variable()->pos(), Message_MaximumArrayDepth);
856 if (node->fun()->isNative() && parameter->dimensions()->length() > 1) {
857 cc_.reportError(parameter->variable()->pos(), Message_MultiArrayInNative);
861 for (size_t i = parameter->dimensions()->length() - 1;
862 i < parameter->dimensions()->length();
865 int size = Type::UNKNOWN_SIZE;
866 if (Expression *expr = parameter->dimensions()->at(i)) {
868 if (!EvaluateForConstant(expr, &box)) {
869 cc_.reportError(expr->pos(), Message_ArraySizeMustBeConstant);
875 type = zone_->types()->unsafeArray(type, size, parameter->isConst());
881 if (IsScalarString(type)) {
882 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
886 args->set(zone_, i, type);
887 parameter->variable()->setType(type);
890 Local<Type> returnType(zone_);
891 if (node->returnType() ||
892 node->hasExplicitReturn() ||
893 node->fun()->isNative())
895 returnType = bindType(node->pos(), node->returnType());
897 returnType = zone_->types()->getVoid();
902 Local<Type> funtype(zone_);
903 if (node->fun()->isNative())
904 funtype = zone_->types()->newNative(returnType, args, node->fun()->isNativeVariadic());
906 funtype = zone_->types()->newFunction(returnType, args);
910 // If the function already has a type, it was forward declared before, and
911 // now this is our chance to type check the second declaration.
912 if (node->fun()->type()) {
913 Local<Type> forward(zone_, node->fun()->type());
914 if (!Type::Compare(funtype, forward)) {
915 cc_.reportError(node->pos(), Message_ForwardDeclareMismatches);
918 node->fun()->setForwardType(forward);
921 node->fun()->setType(funtype);
927 SemanticAnalysis::visit(FunctionStatement *node)
929 function_ = node->fun();
930 scope_ = node->scope();
932 ControlScope control(&control_);
934 node->body()->accept(this);
936 ControlStatus status = control.status();
937 if (status.returns() == Returns_Sometimes) {
938 cc_.reportError(node->pos(), Message_NotAllPathsReturnValue);
939 } else if (status.returns() == Returns_Never) {
940 if (!function_->type()->returnType()->isVoid())
941 cc_.reportError(node->pos(), Message_MissingReturnValue);
950 SemanticAnalysis::typeMismatch(AstNode *node, Handle<Type> actual, Handle<Type> given)
952 cc_.reportError(node->pos(),Message_TypeMismatch,
958 SemanticAnalysis::typeCheckArrayAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
960 Local<Type> actual(zone_, argActual);
961 Local<Type> given(zone_, argGiven);
963 if (!given->isArray()) {
964 cc_.reportError(node->pos(), Message_ExpectedArray);
967 if (given->levels() != actual->levels()) {
968 cc_.reportError(node->pos(), Message_ArrayDimensionsMismatch);
973 while (given->isArray()) {
974 if (actual->elements() != -1) {
976 if (given->elements() == -1 || actual->elements() == -1) {
977 cc_.reportError(node->pos(), Message_ArraySizeNotKnown);
981 if (actual->isCharArray()) {
982 // String assignment can have a truncated |given|.
983 if (given->elements() > actual->elements()) {
984 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
988 if (given->elements() != actual->elements()) {
989 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
994 if (actual->elements() != -1 && given->elements() != actual->elements()) {
995 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
1000 given = given->contained();
1001 actual = actual->contained();
1004 return typeCheckAssignment(node, given, actual, forAssign);
1008 SemanticAnalysis::typeCheckAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
1010 Local<Type> actual(zone_, argActual);
1011 Local<Type> given(zone_, argGiven);
1013 if (actual->isArray())
1014 return typeCheckArrayAssignment(node, given, actual, forAssign);
1016 if (given->isArray()) {
1017 cc_.reportError(node->pos(), Message_CannotAssignArrayToScalar);
1021 // The given type may not have been dereferenced.
1022 if (given->isReference())
1023 given = given->contained();
1024 if (actual->isReference())
1025 actual = actual->contained();
1027 if (actual->isEnum()) {
1028 if (!given->isEnum() || actual != given) {
1029 typeMismatch(node, actual, given);
1035 if (given->isEnum() || given->isFunction()) {
1036 typeMismatch(node, actual, given);
1040 if (given->primitive() != actual->primitive()) {
1041 typeMismatch(node, actual, given);
1049 SemanticAnalysis::typeCheckParameter(AstNode *node, Handle<Type> given, Handle<Type> actual)
1051 return typeCheckAssignment(node, given, actual, false);
1055 SemanticAnalysis::visit(CallExpression *node)
1057 Local<Type> type(zone_, visitForLoad(node->callee()));
1061 if (!type->isFunction()) {
1062 cc_.reportError(node->pos(), Message_CalleeNotFunction);
1065 if (node->arguments()->length() != type->parameters()->length()) {
1066 if (!type->isNative() ||
1067 !type->isNativeVariadic() ||
1068 node->arguments()->length() < type->parameters()->length())
1070 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
1075 // Currently, only calls from a NameProxy are possible.
1076 NamedFunction *fun = node->callee()->toNameProxy()->binding()->toNamedFunction();
1077 if (fun->isForward()) {
1078 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
1082 for (unsigned i = 0; i < node->arguments()->length(); i++) {
1083 // Note: we don't compute references unless the callee needs a
1085 Expression *expression = node->arguments()->at(i);
1086 Local<Type> given(zone_, visitAndApplyType(expression));
1090 // Since we skip a load, check for a call expression that returns void.
1091 if (given->isVoid()) {
1092 assert(expression->isCallExpression());
1093 CallExpression *call = expression->toCallExpression();
1094 cc_.reportError(call->callee()->pos(), Message_FunctionDoesNotReturnValue);
1098 // If it's an IndexExpression, we special case the ability to compute
1100 if (expression->isIndexExpression())
1101 given = given->contained();
1103 bool mustComputeReference;
1104 if (i >= type->parameters()->length()) {
1105 // Special handling for natives. Arguments past the formal must
1106 // always have references computed. However, arrays are already
1107 // references for natives.
1108 assert(type->isNative() && type->isNativeVariadic());
1109 mustComputeReference = !given->isReference() && !given->isArray();
1111 Local<Type> actual(zone_, type->parameterAt(i));
1112 if (!typeCheckParameter(expression, given, actual))
1114 mustComputeReference = actual->isReference() && !given->isReference();
1117 // If the actual is a reference, and the given is not, we'll need to
1118 // compute a reference, which may be allocated on the stack.
1119 if (mustComputeReference)
1120 scope_->setUsesLifoHeap();
1123 node->setType(fun->type()->returnType());
1127 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
1129 // If both sides terminate in a return, we consider this a return as well.
1130 if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
1131 terminate(Returns_Always);
1135 ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
1137 : Returns_Sometimes;
1139 if (left.terminates() && right.terminates())
1146 SemanticAnalysis::visit(IfStatement *node)
1148 Local<Type> type(zone_, visitForLoad(node->condition()));
1152 if (!canTest(node, type))
1155 ControlStatus trueBranch = visitForControl(node->ifTrue());
1156 ControlStatus falseBranch = ControlStatus(false, Returns_Never);
1158 if (node->ifFalse())
1159 falseBranch = visitForControl(node->ifFalse());
1161 control_->merge(trueBranch, falseBranch);
1165 SemanticAnalysis::visit(IndexExpression *node)
1167 Local<Type> left(zone_, visitForLoad(node->left()));
1168 Local<Type> right(zone_, visitForLoad(node->right()));
1170 if (!left || !right)
1173 if (!right->isInt32() && !right->isEnum()) {
1174 cc_.reportError(node->right()->pos(), Message_IndexMustBeInteger);
1177 if (!left->isArray()) {
1178 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
1181 node->setType(left);
1185 SemanticAnalysis::visit(EnumStatement *node)
1187 Local<Type> type(zone_, node->decl()->type());
1192 for (size_t i = 0; i < node->entries()->length(); i++) {
1193 EnumStatement::Entry &entry = node->entries()->at(i);
1195 BoxedPrimitive box = BoxedPrimitive::Int(value);
1197 entry.expr->accept(this);
1198 if (!EvaluateForConstant(entry.expr, &box)) {
1199 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
1203 assert(box.type() == PrimitiveType_Int32);
1204 value = box.toInt();
1207 entry.name->set(type, box);
1213 SemanticAnalysis::visit(StructureStatement *node)
1215 // If this node already has a type, it was pre-analyzed, so skip it.
1216 if (node->decl()->type())
1219 FieldList *fields = node->fields();
1220 Local<FixedArray> desctable(zone_, FixedArray::New(zone_, fields->length(), Heap::Tenure_Old));
1224 StructureBufferBuilder builder;
1226 Local<Type> type(zone_);
1227 Local<String> name(zone_);
1228 Local<Descriptor> desc(zone_);
1229 for (size_t i = 0; i < fields->length(); i++) {
1230 StructureStatement::Field *field = fields->at(i);
1232 type = bindType(field->pos(), field->type());
1237 if (!builder.add(type, &offset))
1240 name = field->name();
1241 desc = Descriptor::New(zone_, name, type, offset);
1245 desctable->set(zone_, i, desc);
1248 name = node->decl()->name();
1249 type = zone_->types()->newStruct(name, desctable);
1253 node->decl()->setType(type);
1257 SemanticAnalysis::visit(StringLiteral *node)
1259 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Char));
1263 type = Type::NewArray(zone_, type, node->string()->length() + 1, true);
1267 node->setType(type);
1271 SemanticAnalysis::visit(FloatLiteral *node)
1273 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
1277 node->setType(type);
1281 SemanticAnalysis::visit(BreakStatement *node)
1284 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
1288 // Note: ignore breaks that occur in unreachable control-flow.
1289 if (!control_->status().terminates())
1292 control_->terminate(Returns_Never);
1296 SemanticAnalysis::visit(ContinueStatement *node)
1299 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
1303 // Note: ignore continues that occur in unreachable control-flow.
1304 if (!control_->status().terminates())
1305 loop_->addContinue();
1307 control_->terminate(Returns_Never);