1 /* vim: set ts=4 sw=4 tw=99 et:
3 * Copyright (C) 2012 David Anderson
5 * This file is part of JITCraft.
7 * JITCraft is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License as published by the Free
9 * Software Foundation, either version 3 of the License, or (at your option)
12 * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
13 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with
17 * JITCraft. If not, see http://www.gnu.org/licenses/.
19 #include "SemanticAnalysis.h"
22 #include "TypeManager.h"
30 IsPrimitiveType(Type *type, PrimitiveType primitive)
35 if (!type->isPrimitive())
38 return primitive == type->primitive();
42 EvaluateBinaryOperation(TokenKind kind, const BoxedPrimitive &left, const BoxedPrimitive &right,
47 *out = BoxedPrimitive::Int(left.toInt() + right.toInt());
51 *out = BoxedPrimitive::Int(left.toInt() << right.toInt());
60 EvaluateForConstant(Expression *expression, BoxedPrimitive *out)
62 switch (expression->kind()) {
63 case AstNode::kBinaryExpression:
67 BinaryExpression *b = expression->toBinaryExpression();
68 if (!EvaluateForConstant(b->left(), &left) ||
69 !EvaluateForConstant(b->right(), &right))
73 return EvaluateBinaryOperation(b->token(), left, right, out);
76 case AstNode::kNameProxy:
78 NameProxy *proxy = expression->toNameProxy();
79 if (proxy->binding()->kind() != BoundName::CONSTANT)
82 NamedConstant *c = proxy->binding()->toNamedConstant();
83 if (!IsPrimitiveType(c->type(), PrimitiveType_Int32))
90 case AstNode::kIntegerLiteral:
91 *out = BoxedPrimitive::Int(expression->toIntegerLiteral()->value());
99 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, ParseTree *tree)
109 SemanticAnalysis::analyze()
114 for (size_t i = 0; i < tree_->statements()->length(); i++) {
115 Statement *statement = tree_->statements()->at(i);
116 if (statement->isFunctionStatement()) {
117 FunctionStatement *funstmt = statement->toFunctionStatement();
118 if (!preanalyze(funstmt))
123 for (size_t i = 0; i < tree_->statements()->length(); i++) {
124 Statement *statement = tree_->statements()->at(i);
125 statement->accept(this);
128 return !cc_.failures();
132 SemanticAnalysis::visitAndApplyType(Expression *expression)
134 expression->accept(this);
135 return expression->type();
139 SemanticAnalysis::visitForLoad(Expression *expression)
141 Local<Type> type(zone_, visitAndApplyType(expression));
145 if (type->isReference()) {
146 expression->setType(type->contained());
147 } else if (expression->isIndexExpression()) {
149 expression->setType(type->contained());
152 return expression->type();
156 SemanticAnalysis::visitForRef(Expression *expression)
158 expression->accept(this);
159 return expression->type();
162 // :TODO: this leaks an interior pointer.
163 static inline const char *
164 GetTypeName(Type *type)
168 if (type->isFunction())
170 if (type->isReference())
171 type = type->contained();
173 return type->tag()->chars();
178 SemanticAnalysis::unaryTypeError(AstNode *node, TokenKind token, Handle<Type> type)
180 const char *op = TokenNames[token];
181 const char *name = GetTypeName(type);
183 cc_.reportError(node->pos(), Message_UnaryTypeError, op, name);
187 SemanticAnalysis::binaryTypeError(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
189 const char *op = TokenNames[token];
190 const char *leftName = GetTypeName(left);
191 const char *rightName = GetTypeName(right);
193 cc_.reportError(node->pos(), Message_BinaryTypeError, op, leftName, rightName);
197 SemanticAnalysis::typeCheckBinary(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
199 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
200 (token >= TOK_ASSIGN_ADD && token <= TOK_ASSIGN_DIV))
202 // If either side is a float, the other side must be a float or int.
203 if (left->isFloat() || right->isFloat()) {
204 Type *floatType = left->isFloat() ? left : right;
205 Type *other = left->isFloat() ? right : left;
206 if (other->isFloat() || (other->isInt32() && !other->tag()))
211 if ((!left->isInt32() || left->tag()) ||
212 (!right->isInt32() || right->tag()))
214 binaryTypeError(node, token, left, right);
222 SemanticAnalysis::canTest(AstNode *node, Handle<Type> type)
224 if (type->isArray()) {
225 cc_.reportError(node->pos(), Message_ArrayIsNotBoolean);
232 SemanticAnalysis::visitForLValue(Expression *expression)
234 if (expression->isIndexExpression()) {
235 Type *type = visitAndApplyType(expression);
239 return type->contained();
242 if (!expression->isNameProxy()) {
243 cc_.reportError(expression->pos(), Message_ExpectedLValue);
247 NameProxy *proxy = expression->toNameProxy();
248 if (!proxy->binding()->kind() == BoundName::VARIABLE) {
249 cc_.reportError(expression->pos(), Message_ExpectedLValue);
253 Variable *var = proxy->binding()->toVariable();
257 if (var->type()->isReference())
258 return var->type()->contained();
263 SemanticAnalysis::visit(NameProxy *name)
265 name->setType(name->binding()->type());
269 SemanticAnalysis::visit(Assignment *node)
271 Local<Type> exprType(zone_, visitForLoad(node->expression()));
275 Local<Type> type(zone_, visitForLValue(node->lvalue()));
279 if (node->token() != TOK_ASSIGN) {
280 if (!typeCheckBinary(node, node->token(), type, exprType))
284 if (!typeCheckAssignment(node, exprType, type, true))
291 SemanticAnalysis::visit(IncDecExpression *node)
293 Local<Type> type(zone_, visitForLValue(node->expression()));
297 assert(!type->isReference());
299 if ((!type->isInt32() || (type->isInt32() && type->tag())) && !type->isFloat()) {
300 unaryTypeError(node, node->token(), type);
308 SemanticAnalysis::visit(BinaryExpression *node)
310 Local<Type> left(zone_, visitForLoad(node->left()));
311 Local<Type> right(zone_, visitForLoad(node->right()));
315 Local<Type> result(zone_, typeCheckBinary(node, node->token(), left, right));
319 node->setType(result);
323 SemanticAnalysis::visit(ReturnStatement *node)
325 Local<Type> type(zone_, visitForLoad(node->expression()));
329 Local<Type> returnType(zone_, function_->returnType());
330 if (!typeCheckAssignment(node, type, returnType, true))
335 SemanticAnalysis::visit(ForStatement *node)
339 scope_ = node->scope();
341 if (node->initialization())
342 node->initialization()->accept(this);
344 if (node->condition()) {
345 Local<Type> type(zone_, visitForLoad(node->condition()));
346 if (!type || !canTest(node->condition(), type)) {
353 node->update()->accept(this);
355 node->body()->accept(this);
358 scope_ = scope_->enclosing();
363 SemanticAnalysis::visit(WhileStatement *node)
367 Local<Type> type(zone_, visitForLoad(node->condition()));
368 if (!type || !canTest(node->condition(), type)) {
373 node->body()->accept(this);
378 SemanticAnalysis::visit(BlockStatement *node)
381 scope_ = node->scope();
382 for (size_t i = 0; i < node->statements()->length(); i++) {
383 Statement *statement = node->statements()->at(i);
384 statement->accept(this);
387 scope_ = scope_->enclosing();
391 SemanticAnalysis::visit(VariableDeclaration *node)
393 Local<String> tag(zone_, node->tag());
394 Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
398 if (node->postDimensions()) {
399 Local<Type> init(zone_);
400 if (node->initialization()) {
401 if ((init = visitAndApplyType(node->initialization())) == NULL)
405 if (node->postDimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
406 cc_.reportError(node->pos(), Message_MaximumArrayDepth);
410 // If we have an initializer, make sure it's the same type.
411 if (init && node->postDimensions()->length() != init->levels()) {
412 cc_.reportError(node->pos(), Message_ArrayInitializerDepth);
416 Local<Type> check(zone_, init);
417 for (size_t i = node->postDimensions()->length() - 1; i < node->postDimensions()->length(); i--) {
418 Expression *expr = node->postDimensions()->at(i);
422 Local<Type> exprType(zone_, visitForLoad(expr));
426 if (!IsPrimitiveType(exprType, PrimitiveType_Int32)) {
427 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
432 if (EvaluateForConstant(expr, &box) && box.type() == PrimitiveType_Int32) {
435 cc_.reportError(expr->pos(), Message_BadArraySize);
438 if (size >= INT_MAX / sizeof(int)) {
439 cc_.reportError(expr->pos(), Message_ArraySizeTooBig);
444 if (check->elements() == -1) {
445 cc_.reportError(expr->pos(), Message_ArraySizeCannotBeDetermined);
449 if (check->isCharArray()) {
450 if (check->elements() > size) {
451 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
454 } else if (check->elements() != size) {
455 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, unsigned(i));
461 cc_.reportError(node->pos(), Message_DynamicArrayHasInitializer);
465 // here until we get dynamic array support.
466 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
470 // Infer the size from the initializer.
472 cc_.reportError(node->pos(), Message_ArraySizeNotSpecified);
475 if (init->elements() == -1) {
476 cc_.reportError(node->pos(), Message_ArraySizeCannotBeDetermined);
479 size = init->elements();
482 type = zone_->types()->unsafeArray(type, size);
487 check = check->contained();
490 // Right now, any array is allowed on the LIFO heap. In case the
491 // runtime actually decides to use the LIFO heap, we must reserve
492 // a slot so we can unwind the heap when the current scope leaves.
493 scope_->setUsesLifoHeap();
495 if (node->initialization()) {
496 Local<Type> right(zone_, visitForLoad(node->initialization()));
499 if (!typeCheckAssignment(node, type, right, true))
502 if (type->primitive() == PrimitiveType_Char) {
503 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
508 node->variable()->setType(type);
512 SemanticAnalysis::visit(IntegerLiteral *node)
514 node->setType(zone_->types()->getPrimitive(PrimitiveType_Int32));
518 SemanticAnalysis::visit(ExpressionStatement *node)
520 node->expression()->accept(this);
524 SemanticAnalysis::preanalyze(FunctionStatement *node)
526 Local<FixedArray> args(zone_, FixedArray::New(zone_, node->parameters()->length(), Heap::Tenure_Old));
530 // Apply types to arguments.
531 for (size_t i = 0; i < node->parameters()->length(); i++) {
532 Parameter *parameter = node->parameters()->at(i);
534 Local<String> tag(zone_, parameter->tag());
535 Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
539 if (type->primitive() == PrimitiveType_Char) {
540 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
544 if (parameter->reference()) {
545 type = zone_->types()->getReference(type);
550 args->set(zone_, i, type);
551 parameter->variable()->setType(type);
554 Local<Type> returnType(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
558 Local<Type> funtype(zone_, zone_->types()->newFunction(returnType, args));
562 node->fun()->setType(funtype);
567 SemanticAnalysis::visit(FunctionStatement *node)
569 function_ = node->fun()->type();
570 scope_ = node->scope();
571 node->body()->accept(this);
577 SemanticAnalysis::typeCheckArrayAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
579 Local<Type> actual(zone_, argActual);
580 Local<Type> given(zone_, argGiven);
582 if (!given->isArray()) {
583 cc_.reportError(node->pos(), Message_ExpectedArray);
586 if (given->levels() != actual->levels()) {
587 cc_.reportError(node->pos(), Message_ArrayDimensionsMismatch);
592 while (given->isArray()) {
593 if (actual->elements() != -1) {
595 if (given->elements() == -1 || actual->elements() == -1) {
596 cc_.reportError(node->pos(), Message_ArraySizeNotKnown);
600 if (actual->isCharArray()) {
601 // String assignment can have a truncated |given|.
602 if (given->elements() > actual->elements()) {
603 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
607 if (given->elements() != actual->elements()) {
608 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
613 if (actual->elements() != -1 && given->elements() != actual->elements()) {
614 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
619 given = given->contained();
620 actual = actual->contained();
623 if (given->primitive() != actual->primitive()) {
624 // :TODO: leaks an interior pointer.
625 const char *givenTag = given->tag() ? given->tag()->chars() : "_";
626 const char *actualTag = given->tag() ? given->tag()->chars() : "_";
627 cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
635 SemanticAnalysis::typeCheckAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
637 Local<Type> actual(zone_, argActual);
638 Local<Type> given(zone_, argGiven);
640 if (actual->isArray())
641 return typeCheckArrayAssignment(node, given, actual, forAssign);
643 if (given->isArray()) {
644 cc_.reportError(node->pos(), Message_CannotAssignArrayToScalar);
648 // The given type may not have been dereferenced.
649 if (given->isReference())
650 given = given->contained();
651 if (actual->isReference())
652 actual = actual->contained();
654 if (!given->isPrimitive() || !actual->isPrimitive()) {
655 cc_.reportError(node->pos(), Message_UnsupportedType);
659 if (given->primitive() != actual->primitive()) {
660 // :TODO: leaks an interior pointer
661 const char *givenTag = given->tag() ? given->tag()->chars() : "_";
662 const char *actualTag = given->tag() ? given->tag()->chars() : "_";
663 cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
671 SemanticAnalysis::typeCheckParameter(AstNode *node, Handle<Type> given, Handle<Type> actual)
673 return typeCheckAssignment(node, given, actual, false);
677 SemanticAnalysis::visit(CallExpression *node)
679 Local<Type> type(zone_, visitForLoad(node->callee()));
683 if (!type->isFunction()) {
684 cc_.reportError(node->pos(), Message_CalleeNotFunction);
687 if (node->arguments()->length() != type->parameters()->length()) {
688 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
692 for (unsigned i = 0; i < node->arguments()->length(); i++) {
693 // Note: we don't compute references unless the callee needs a
695 Expression *expression = node->arguments()->at(i);
696 Local<Type> given(zone_, visitAndApplyType(expression));
700 // If it's an IndexExpression, we special case the ability to compute
702 if (expression->isIndexExpression())
703 given = given->contained();
705 Local<Type> actual(zone_, type->parameterAt(i));
706 if (!typeCheckParameter(expression, given, actual))
709 // If the actual is a reference, and the given is not, we'll need to
710 // compute a reference, which may be allocated on the stack.
711 if (actual->isReference() && !given->isReference())
712 scope_->setUsesLifoHeap();
717 SemanticAnalysis::visit(IfStatement *node)
719 Local<Type> type(zone_, visitForLoad(node->condition()));
723 if (!canTest(node, type))
726 node->ifTrue()->accept(this);
728 node->ifFalse()->accept(this);
732 SemanticAnalysis::visit(IndexExpression *node)
734 Local<Type> left(zone_, visitForRef(node->left()));
735 Local<Type> right(zone_, visitForLoad(node->right()));
740 if (!right->isInt32()) {
741 cc_.reportError(node->right()->pos(), Message_IndexMustBeInteger);
744 if (!left->isArray()) {
745 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
752 SemanticAnalysis::visit(EnumStatement *node)
754 // Forbid the blessed types.
755 Local<String> tag(zone_, node->name());
756 if (!strcmp(tag->chars(), "Float") ||
757 !strcmp(tag->chars(), "String") ||
758 !strcmp(tag->chars(), "any") ||
759 !strcmp(tag->chars(), "bool"))
761 cc_.reportError(node->pos(), Message_InvalidEnumName);
765 Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
770 for (size_t i = 0; i < node->entries()->length(); i++) {
771 EnumStatement::Entry &entry = node->entries()->at(i);
773 BoxedPrimitive box = BoxedPrimitive::Int(value);
775 entry.expr->accept(this);
776 if (!EvaluateForConstant(entry.expr, &box)) {
777 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
781 assert(box.type() == PrimitiveType_Int32);
785 entry.name->set(type, box);
791 SemanticAnalysis::visit(StringLiteral *node)
793 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Char));
797 type = Type::NewArray(zone_, type, node->string()->length() + 1, true);
805 SemanticAnalysis::visit(FloatLiteral *node)
807 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
815 SemanticAnalysis::visit(BreakStatement *node)
818 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
822 SemanticAnalysis::visit(ContinueStatement *node)
825 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);