Remove calls to ZONE().
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"
29 IsPrimitiveType(Type *type, PrimitiveType primitive)
34 if (!type->isPrimitive())
37 return primitive == type->primitive();
41 EvaluateBinaryOperation(TokenKind kind, const BoxedPrimitive &left, const BoxedPrimitive &right,
46 *out = BoxedPrimitive::Int(left.toInt() + right.toInt());
50 *out = BoxedPrimitive::Int(left.toInt() << right.toInt());
59 EvaluateForConstant(Expression *expression, BoxedPrimitive *out)
61 switch (expression->kind()) {
62 case AstNode::kBinaryExpression:
66 BinaryExpression *b = expression->toBinaryExpression();
67 if (!EvaluateForConstant(b->left(), &left) ||
68 !EvaluateForConstant(b->right(), &right))
72 return EvaluateBinaryOperation(b->token(), left, right, out);
75 case AstNode::kNameProxy:
77 NameProxy *proxy = expression->toNameProxy();
78 if (proxy->binding()->kind() != BoundName::CONSTANT)
81 NamedConstant *c = proxy->binding()->toNamedConstant();
82 if (!IsPrimitiveType(c->type(), PrimitiveType_Int32))
89 case AstNode::kIntegerLiteral:
90 *out = BoxedPrimitive::Int(expression->toIntegerLiteral()->value());
98 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, ParseTree *tree)
108 SemanticAnalysis::analyze()
113 for (size_t i = 0; i < tree_->statements()->length(); i++) {
114 Statement *statement = tree_->statements()->at(i);
115 if (statement->isFunctionStatement()) {
116 FunctionStatement *funstmt = statement->toFunctionStatement();
117 if (!preanalyze(funstmt))
122 for (size_t i = 0; i < tree_->statements()->length(); i++) {
123 Statement *statement = tree_->statements()->at(i);
124 statement->accept(this);
127 return !cc_.failures();
131 SemanticAnalysis::visitAndApplyType(Expression *expression)
133 expression->accept(this);
134 return expression->type();
138 SemanticAnalysis::visitForLoad(Expression *expression)
141 Type *type = 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 static inline const char *
163 GetTypeName(Type *type)
167 if (type->isFunction())
169 if (type->isReference())
170 type = type->contained();
177 SemanticAnalysis::unaryTypeError(AstNode *node, TokenKind token, Type *type)
179 const char *op = TokenNames[token];
180 const char *name = GetTypeName(type);
182 cc_.reportError(node->pos(), Message_UnaryTypeError, op, name);
186 SemanticAnalysis::binaryTypeError(AstNode *node, TokenKind token, Type *left, Type *right)
188 const char *op = TokenNames[token];
189 const char *leftName = GetTypeName(left);
190 const char *rightName = GetTypeName(right);
192 cc_.reportError(node->pos(), Message_BinaryTypeError, op, leftName, rightName);
196 SemanticAnalysis::typeCheckBinary(AstNode *node, TokenKind token, Type *left, Type *right)
198 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
199 (token >= TOK_ASSIGN_ADD && token <= TOK_ASSIGN_DIV))
201 // If either side is a float, the other side must be a float or int.
202 if (left->isFloat() || right->isFloat()) {
203 Type *floatType = left->isFloat() ? left : right;
204 Type *other = left->isFloat() ? right : left;
205 if (other->isFloat() || (other->isInt32() && !other->tag()))
210 if ((!left->isInt32() || left->tag()) ||
211 (!right->isInt32() || right->tag()))
213 binaryTypeError(node, token, left, right);
221 SemanticAnalysis::canTest(AstNode *node, Type *type)
223 if (type->isArray()) {
224 cc_.reportError(node->pos(), Message_ArrayIsNotBoolean);
231 SemanticAnalysis::visitForLValue(Expression *expression)
233 if (expression->isIndexExpression()) {
234 Type *type = visitAndApplyType(expression);
238 return type->contained();
241 if (!expression->isNameProxy()) {
242 cc_.reportError(expression->pos(), Message_ExpectedLValue);
246 NameProxy *proxy = expression->toNameProxy();
247 if (!proxy->binding()->kind() == BoundName::VARIABLE) {
248 cc_.reportError(expression->pos(), Message_ExpectedLValue);
252 Variable *var = proxy->binding()->toVariable();
256 if (var->type()->isReference())
257 return var->type()->contained();
262 SemanticAnalysis::visit(NameProxy *name)
264 name->setType(name->binding()->type());
268 SemanticAnalysis::visit(Assignment *node)
270 Type *exprType = visitForLoad(node->expression());
275 Type *type = 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)
294 Type *type = visitForLValue(node->expression());
298 assert(!type->isReference());
300 if ((!type->isInt32() || (type->isInt32() && type->tag())) && !type->isFloat()) {
301 unaryTypeError(node, node->token(), type);
309 SemanticAnalysis::visit(BinaryExpression *node)
312 Type *left = visitForLoad(node->left());
313 Type *right = visitForLoad(node->right());
317 Type *result = typeCheckBinary(node, node->token(), left, right);
321 node->setType(result);
325 SemanticAnalysis::visit(ReturnStatement *node)
327 Type *type = visitForLoad(node->expression());
331 if (!typeCheckAssignment(node, type, function_->returnType(), true))
336 SemanticAnalysis::visit(ForStatement *node)
340 scope_ = node->scope();
342 if (node->initialization())
343 node->initialization()->accept(this);
345 if (node->condition()) {
346 Type *type = visitForLoad(node->condition());
347 if (!type || !canTest(node->condition(), type)) {
354 node->update()->accept(this);
356 node->body()->accept(this);
359 scope_ = scope_->enclosing();
364 SemanticAnalysis::visit(WhileStatement *node)
368 Type *type = visitForLoad(node->condition());
369 if (!type || !canTest(node->condition(), type)) {
374 node->body()->accept(this);
379 SemanticAnalysis::visit(BlockStatement *node)
382 scope_ = node->scope();
383 for (size_t i = 0; i < node->statements()->length(); i++) {
384 Statement *statement = node->statements()->at(i);
385 statement->accept(this);
388 scope_ = scope_->enclosing();
392 SemanticAnalysis::visit(VariableDeclaration *node)
395 Type *type = zone_->types()->getPrimitiveForTag(node->tag());
399 if (node->postDimensions()) {
401 if (node->initialization()) {
402 if ((init = visitAndApplyType(node->initialization())) == NULL)
406 if (node->postDimensions()->size() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
407 cc_.reportError(node->pos(), Message_MaximumArrayDepth);
411 // If we have an initializer, make sure it's the same type.
412 if (init && node->postDimensions()->size() != init->levels()) {
413 cc_.reportError(node->pos(), Message_ArrayInitializerDepth);
418 for (size_t i = node->postDimensions()->size() - 1; i < node->postDimensions()->size(); i--) {
419 Expression *expr = node->postDimensions()->at(i);
423 Type *exprType = visitForLoad(expr);
427 if (!IsPrimitiveType(exprType, PrimitiveType_Int32)) {
428 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
433 if (EvaluateForConstant(expr, &box) && box.type() == PrimitiveType_Int32) {
436 cc_.reportError(expr->pos(), Message_BadArraySize);
439 if (size >= INT_MAX / sizeof(int)) {
440 cc_.reportError(expr->pos(), Message_ArraySizeTooBig);
445 if (check->elements() == -1) {
446 cc_.reportError(expr->pos(), Message_ArraySizeCannotBeDetermined);
450 if (check->isCharArray()) {
451 if (check->elements() > size) {
452 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
455 } else if (check->elements() != size) {
456 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, unsigned(i));
462 cc_.reportError(node->pos(), Message_DynamicArrayHasInitializer);
466 // here until we get dynamic array support.
467 cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
471 // Infer the size from the initializer.
473 cc_.reportError(node->pos(), Message_ArraySizeNotSpecified);
476 if (init->elements() == -1) {
477 cc_.reportError(node->pos(), Message_ArraySizeCannotBeDetermined);
480 size = init->elements();
483 type = zone_->types()->unsafeArray(type, size);
488 check = check->contained();
491 // Right now, any array is allowed on the LIFO heap. In case the
492 // runtime actually decides to use the LIFO heap, we must reserve
493 // a slot so we can unwind the heap when the current scope leaves.
494 scope_->setUsesLifoHeap();
496 if (node->initialization()) {
497 Type *right = visitForLoad(node->initialization());
500 if (!typeCheckAssignment(node, type, right, true))
503 if (type->primitive() == PrimitiveType_Char) {
504 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
509 node->variable()->setType(type);
513 SemanticAnalysis::visit(IntegerLiteral *node)
515 node->setType(zone_->types()->getPrimitive(PrimitiveType_Int32));
519 SemanticAnalysis::visit(ExpressionStatement *node)
521 node->expression()->accept(this);
525 SemanticAnalysis::preanalyze(FunctionStatement *node)
529 FixedArray *args = FixedArray::New(zone_, node->parameters()->size(), Heap::Tenure_Old);
533 // Apply types to arguments.
534 for (size_t i = 0; i < node->parameters()->size(); i++) {
535 Parameter *parameter = node->parameters()->at(i);
537 Type *type = zone_->types()->getPrimitiveForTag(parameter->tag());
541 if (type->primitive() == PrimitiveType_Char) {
542 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
546 if (parameter->reference()) {
547 type = zone_->types()->getReference(type);
552 args->set(zone_, i, type);
553 parameter->variable()->setType(type);
556 Type *returnType = zone_->types()->getPrimitive(PrimitiveType_Int32);
560 Type *funtype = zone_->types()->newFunction(returnType, args);
564 node->fun()->setType(funtype);
569 SemanticAnalysis::visit(FunctionStatement *node)
571 function_ = node->fun()->type();
572 scope_ = node->scope();
573 node->body()->accept(this);
579 SemanticAnalysis::typeCheckArrayAssignment(AstNode *node, Type *given, Type *actual, bool forAssign)
581 if (!given->isArray()) {
582 cc_.reportError(node->pos(), Message_ExpectedArray);
585 if (given->levels() != actual->levels()) {
586 cc_.reportError(node->pos(), Message_ArrayDimensionsMismatch);
591 while (given->isArray()) {
592 if (actual->elements() != -1) {
594 if (given->elements() == -1 || actual->elements() == -1) {
595 cc_.reportError(node->pos(), Message_ArraySizeNotKnown);
599 if (actual->isCharArray()) {
600 // String assignment can have a truncated |given|.
601 if (given->elements() > actual->elements()) {
602 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
606 if (given->elements() != actual->elements()) {
607 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
612 if (actual->elements() != -1 && given->elements() != actual->elements()) {
613 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
618 given = given->contained();
619 actual = actual->contained();
622 if (given->primitive() != actual->primitive()) {
623 const char *givenTag = given->tag() ? given->tag() : "_";
624 const char *actualTag = given->tag() ? given->tag() : "_";
625 cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
633 SemanticAnalysis::typeCheckAssignment(AstNode *node, Type *given, Type *actual, bool forAssign)
635 if (actual->isArray())
636 return typeCheckArrayAssignment(node, given, actual, forAssign);
638 if (given->isArray()) {
639 cc_.reportError(node->pos(), Message_CannotAssignArrayToScalar);
643 if (!given->isPrimitive() || !actual->primitive()) {
644 cc_.reportError(node->pos(), Message_UnsupportedType);
648 // The given type may not have been dereferenced.
649 if (given->isReference())
650 given = given->contained();
651 if (actual->isReference())
652 actual = given->contained();
654 if (given->primitive() != actual->primitive()) {
655 const char *givenTag = given->tag() ? given->tag() : "_";
656 const char *actualTag = given->tag() ? given->tag() : "_";
657 cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
665 SemanticAnalysis::typeCheckParameter(AstNode *node, Type *given, Type *actual)
667 return typeCheckAssignment(node, given, actual, false);
671 SemanticAnalysis::visit(CallExpression *node)
673 Type *type = visitForLoad(node->callee());
677 if (!type->isFunction()) {
678 cc_.reportError(node->pos(), Message_CalleeNotFunction);
681 if (node->arguments()->size() != type->parameters()->length()) {
682 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
686 for (unsigned i = 0; i < node->arguments()->size(); i++) {
687 // Note: we don't compute references unless the callee needs a
689 Expression *expression = node->arguments()->at(i);
690 Type *given = visitAndApplyType(expression);
694 // If it's an IndexExpression, we special case the ability to compute
696 if (expression->isIndexExpression())
697 given = given->contained();
699 Type *actual = type->parameterAt(i);
700 if (!typeCheckParameter(expression, given, actual))
703 // If the actual is a reference, and the given is not, we'll need to
704 // compute a reference, which may be allocated on the stack.
705 if (actual->isReference() && !given->isReference())
706 scope_->setUsesLifoHeap();
711 SemanticAnalysis::visit(IfStatement *node)
713 Type *type = visitForLoad(node->condition());
717 if (!canTest(node, type))
720 node->ifTrue()->accept(this);
722 node->ifFalse()->accept(this);
726 SemanticAnalysis::visit(IndexExpression *node)
729 Type *left = visitForRef(node->left());
730 Type *right = visitForLoad(node->right());
735 if (!right->isInt32()) {
736 cc_.reportError(node->right()->pos(), Message_IndexMustBeInteger);
739 if (!left->isArray()) {
740 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
747 SemanticAnalysis::visit(EnumStatement *node)
749 // Forbid the blessed types.
750 Name *tag = node->name();
751 if (!strcmp(tag, "Float") ||
752 !strcmp(tag, "String") ||
753 !strcmp(tag, "any") ||
754 !strcmp(tag, "bool"))
756 cc_.reportError(node->pos(), Message_InvalidEnumName);
760 Type *type = zone_->types()->getPrimitiveForTag(tag);
765 for (size_t i = 0; i < node->entries()->size(); i++) {
766 EnumStatement::Entry &entry = node->entries()->at(i);
768 BoxedPrimitive box = BoxedPrimitive::Int(value);
770 entry.expr->accept(this);
771 if (!EvaluateForConstant(entry.expr, &box)) {
772 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
776 assert(box.type() == PrimitiveType_Int32);
780 entry.name->set(type, box);
786 SemanticAnalysis::visit(StringLiteral *node)
788 Type *type = zone_->types()->getPrimitive(PrimitiveType_Char);
792 type = Type::NewArray(zone_, type, node->string()->length() + 1, true);
800 SemanticAnalysis::visit(FloatLiteral *node)
802 Type *type = zone_->types()->getPrimitive(PrimitiveType_Float);
810 SemanticAnalysis::visit(BreakStatement *node)
813 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
817 SemanticAnalysis::visit(ContinueStatement *node)
820 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);