Handleize NameBinding.
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)
394 Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(node->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()->size() > 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()->size() != init->levels()) {
412 cc_.reportError(node->pos(), Message_ArrayInitializerDepth);
416 Local<Type> check(zone_, init);
417 for (size_t i = node->postDimensions()->size() - 1; i < node->postDimensions()->size(); 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 Type *right = 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()->size(), Heap::Tenure_Old));
530 // Apply types to arguments.
531 for (size_t i = 0; i < node->parameters()->size(); i++) {
532 Parameter *parameter = node->parameters()->at(i);
534 Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(parameter->tag()));
538 if (type->primitive() == PrimitiveType_Char) {
539 cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
543 if (parameter->reference()) {
544 type = zone_->types()->getReference(type);
549 args->set(zone_, i, type);
550 parameter->variable()->setType(type);
553 Local<Type> returnType(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
557 Local<Type> funtype(zone_, zone_->types()->newFunction(returnType, args));
561 node->fun()->setType(funtype);
566 SemanticAnalysis::visit(FunctionStatement *node)
568 function_ = node->fun()->type();
569 scope_ = node->scope();
570 node->body()->accept(this);
576 SemanticAnalysis::typeCheckArrayAssignment(AstNode *node, Type *given, Type *actual, bool forAssign)
578 if (!given->isArray()) {
579 cc_.reportError(node->pos(), Message_ExpectedArray);
582 if (given->levels() != actual->levels()) {
583 cc_.reportError(node->pos(), Message_ArrayDimensionsMismatch);
588 while (given->isArray()) {
589 if (actual->elements() != -1) {
591 if (given->elements() == -1 || actual->elements() == -1) {
592 cc_.reportError(node->pos(), Message_ArraySizeNotKnown);
596 if (actual->isCharArray()) {
597 // String assignment can have a truncated |given|.
598 if (given->elements() > actual->elements()) {
599 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
603 if (given->elements() != actual->elements()) {
604 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
609 if (actual->elements() != -1 && given->elements() != actual->elements()) {
610 cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
615 given = given->contained();
616 actual = actual->contained();
619 if (given->primitive() != actual->primitive()) {
620 const char *givenTag = given->tag() ? given->tag() : "_";
621 const char *actualTag = given->tag() ? given->tag() : "_";
622 cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
630 SemanticAnalysis::typeCheckAssignment(AstNode *node, Type *given, Type *actual, bool forAssign)
632 if (actual->isArray())
633 return typeCheckArrayAssignment(node, given, actual, forAssign);
635 if (given->isArray()) {
636 cc_.reportError(node->pos(), Message_CannotAssignArrayToScalar);
640 if (!given->isPrimitive() || !actual->primitive()) {
641 cc_.reportError(node->pos(), Message_UnsupportedType);
645 // The given type may not have been dereferenced.
646 if (given->isReference())
647 given = given->contained();
648 if (actual->isReference())
649 actual = given->contained();
651 if (given->primitive() != actual->primitive()) {
652 const char *givenTag = given->tag() ? given->tag() : "_";
653 const char *actualTag = given->tag() ? given->tag() : "_";
654 cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
662 SemanticAnalysis::typeCheckParameter(AstNode *node, Type *given, Type *actual)
664 return typeCheckAssignment(node, given, actual, false);
668 SemanticAnalysis::visit(CallExpression *node)
670 Type *type = visitForLoad(node->callee());
674 if (!type->isFunction()) {
675 cc_.reportError(node->pos(), Message_CalleeNotFunction);
678 if (node->arguments()->size() != type->parameters()->length()) {
679 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
683 for (unsigned i = 0; i < node->arguments()->size(); i++) {
684 // Note: we don't compute references unless the callee needs a
686 Expression *expression = node->arguments()->at(i);
687 Type *given = visitAndApplyType(expression);
691 // If it's an IndexExpression, we special case the ability to compute
693 if (expression->isIndexExpression())
694 given = given->contained();
696 Type *actual = type->parameterAt(i);
697 if (!typeCheckParameter(expression, given, actual))
700 // If the actual is a reference, and the given is not, we'll need to
701 // compute a reference, which may be allocated on the stack.
702 if (actual->isReference() && !given->isReference())
703 scope_->setUsesLifoHeap();
708 SemanticAnalysis::visit(IfStatement *node)
710 Type *type = visitForLoad(node->condition());
714 if (!canTest(node, type))
717 node->ifTrue()->accept(this);
719 node->ifFalse()->accept(this);
723 SemanticAnalysis::visit(IndexExpression *node)
726 Type *left = visitForRef(node->left());
727 Type *right = visitForLoad(node->right());
732 if (!right->isInt32()) {
733 cc_.reportError(node->right()->pos(), Message_IndexMustBeInteger);
736 if (!left->isArray()) {
737 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
744 SemanticAnalysis::visit(EnumStatement *node)
746 // Forbid the blessed types.
747 Name *tag = node->name();
748 if (!strcmp(tag, "Float") ||
749 !strcmp(tag, "String") ||
750 !strcmp(tag, "any") ||
751 !strcmp(tag, "bool"))
753 cc_.reportError(node->pos(), Message_InvalidEnumName);
757 Type *type = zone_->types()->getPrimitiveForTag(tag);
762 for (size_t i = 0; i < node->entries()->size(); i++) {
763 EnumStatement::Entry &entry = node->entries()->at(i);
765 BoxedPrimitive box = BoxedPrimitive::Int(value);
767 entry.expr->accept(this);
768 if (!EvaluateForConstant(entry.expr, &box)) {
769 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
773 assert(box.type() == PrimitiveType_Int32);
777 entry.name->set(type, box);
783 SemanticAnalysis::visit(StringLiteral *node)
785 Type *type = zone_->types()->getPrimitive(PrimitiveType_Char);
789 type = Type::NewArray(zone_, type, node->string()->length() + 1, true);
797 SemanticAnalysis::visit(FloatLiteral *node)
799 Type *type = zone_->types()->getPrimitive(PrimitiveType_Float);
807 SemanticAnalysis::visit(BreakStatement *node)
810 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
814 SemanticAnalysis::visit(ContinueStatement *node)
817 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);