src/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Mon Jul 30 12:13:22 2012 -0700 (2012-07-30)
changeset 142 a000bafece09
parent 137 be919b22085b
child 143 393f1b8ac8c3
permissions -rw-r--r--
Implement re-tag unary expression.
     1 /* vim: set ts=4 sw=4 tw=99 et:
     2  *
     3  * Copyright (C) 2012 David Anderson
     4  *
     5  * This file is part of JITCraft.
     6  *
     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)
    10  * any later version.
    11  * 
    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.
    15  *
    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/.
    18  */
    19 #include <string.h>
    20 #include "SemanticAnalysis.h"
    21 #include "Types.h"
    22 #include "Zone.h"
    23 #include "TypeManager.h"
    24 #include "Scopes.h"
    25 #include "NameBinding.h"
    26 #include "Heap-inl.h"
    27 #include "Strings.h"
    28 
    29 using namespace ke;
    30 
    31 static inline bool
    32 IsPrimitiveType(Type *type, PrimitiveType primitive)
    33 {
    34     if (!type)
    35         return false;
    36 
    37     if (!type->isPrimitive())
    38         return false;
    39 
    40     return primitive == type->primitive();
    41 }
    42 
    43 static inline bool
    44 EvaluateBinaryOperation(TokenKind kind, const BoxedPrimitive &left, const BoxedPrimitive &right,
    45                         BoxedPrimitive *out)
    46 {
    47     switch (kind) {
    48       case TOK_PLUS:
    49         *out = BoxedPrimitive::Int(left.toInt() + right.toInt());
    50         return true;
    51 
    52       case TOK_SHL:
    53         *out = BoxedPrimitive::Int(left.toInt() << right.toInt());
    54         return true;
    55 
    56       default:
    57         return false;
    58     }
    59 }
    60 
    61 static bool
    62 EvaluateForConstant(Expression *expression, BoxedPrimitive *out)
    63 {
    64     switch (expression->kind()) {
    65       case AstNode::kBinaryExpression:
    66       {
    67         BoxedPrimitive left;
    68         BoxedPrimitive right;
    69         BinaryExpression *b = expression->toBinaryExpression();
    70         if (!EvaluateForConstant(b->left(), &left) ||
    71             !EvaluateForConstant(b->right(), &right))
    72         {
    73             return false;
    74         }
    75         return EvaluateBinaryOperation(b->token(), left, right, out);
    76       }
    77 
    78       case AstNode::kNameProxy:
    79       {
    80         NameProxy *proxy = expression->toNameProxy();
    81         if (proxy->binding()->kind() != BoundName::CONSTANT)
    82             return false;
    83 
    84         NamedConstant *c = proxy->binding()->toNamedConstant();
    85         if (!IsPrimitiveType(c->type(), PrimitiveType_Int32))
    86             return false;
    87 
    88         *out = c->value();
    89         return true;
    90       }
    91 
    92       case AstNode::kIntegerLiteral:
    93         *out = BoxedPrimitive::Int(expression->toIntegerLiteral()->value());
    94         return true;
    95 
    96       default:
    97         return false;
    98     }
    99 }
   100 
   101 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, ParseTree *tree)
   102   : zone_(zone),
   103     cc_(cc),
   104     tree_(tree),
   105     scope_(NULL),
   106     loop_(NULL)
   107 {
   108 }
   109 
   110 bool
   111 SemanticAnalysis::analyze()
   112 {
   113     if (cc_.failures())
   114         return false;
   115 
   116     scope_ = tree_->scope();
   117 
   118     for (size_t i = 0; i < tree_->statements()->length(); i++) {
   119         Statement *statement = tree_->statements()->at(i);
   120         if (statement->isFunctionStatement()) {
   121             FunctionStatement *funstmt = statement->toFunctionStatement();
   122             if (!preanalyze(funstmt))
   123                 return false;
   124         }
   125     }
   126 
   127     for (size_t i = 0; i < tree_->statements()->length(); i++) {
   128         Statement *statement = tree_->statements()->at(i);
   129         statement->accept(this);
   130     }
   131 
   132     if (!determineLiveFunctions())
   133         return false;
   134 
   135     return !cc_.failures();
   136 }
   137 
   138 bool
   139 SemanticAnalysis::determineLiveFunctions()
   140 {
   141     Vector<NamedFunction *> worklist;
   142 
   143     // Add the root set.
   144     for (size_t i = 0; i < tree_->statements()->length(); i++) {
   145         Statement *statement = tree_->statements()->at(i);
   146         if (!statement->isFunctionStatement())
   147             continue;
   148 
   149         FunctionStatement *stmt = statement->toFunctionStatement();
   150         NamedFunction  *fun = stmt->fun();
   151         if (!fun->used())
   152             continue;
   153 
   154         for (size_t i = 0; i < fun->usedGlobals()->length(); i++) {
   155             NamedFunction *name = fun->usedGlobals()->at(i)->toNamedFunction();
   156 
   157             // Names in these lists are always unused, however, we mark them
   158             // as used while inserting into the work queue, to avoid double-
   159             // insertion.
   160             if (name->used())
   161                 continue;
   162 
   163             if (!worklist.append(name))
   164                 return false;
   165 
   166             name->setUsed();
   167         }
   168     }
   169 
   170     while (!worklist.empty()) {
   171         NamedFunction *fun = worklist.popCopy();
   172 
   173         for (size_t i = 0; i < fun->usedGlobals()->length(); i++) {
   174             NamedFunction *name = fun->usedGlobals()->at(i)->toNamedFunction();
   175             if (name->used())
   176                 continue;
   177             if (!worklist.append(name))
   178                 return false;
   179             name->setUsed();
   180         }
   181     }
   182 
   183     return true;
   184 }
   185 
   186 
   187 Type *
   188 SemanticAnalysis::visitAndApplyType(Expression *expression)
   189 {
   190     expression->accept(this);
   191     return expression->type();
   192 }
   193 
   194 Type *
   195 SemanticAnalysis::visitForLoad(Expression *expression)
   196 {
   197     Local<Type> type(zone_, visitAndApplyType(expression));
   198     if (!type)
   199         return NULL;
   200 
   201     if (type->isReference()) {
   202         expression->setType(type->contained());
   203     } else if (expression->isIndexExpression()) {
   204         if (type->isArray())
   205             expression->setType(type->contained());
   206     } else if (expression->isCallExpression()) {
   207         if (type->isVoid()) {
   208             CallExpression *call = expression->toCallExpression();
   209             cc_.reportError(call->callee()->pos(), Message_FunctionDoesNotReturnValue);
   210             return NULL;
   211         }
   212     }
   213 
   214     return expression->type();
   215 }
   216 
   217 // :TODO: this leaks an interior pointer.
   218 static inline const char *
   219 GetTypeName(Type *type)
   220 {
   221     if (type->isArray())
   222         return "array";
   223     if (type->isFunction())
   224         return "function";
   225     if (type->isVoid())
   226         return "void";
   227     if (type->isReference())
   228         type = type->contained();
   229     if (type->tag())
   230         return type->tag()->chars();
   231     return "int";
   232 }
   233 
   234 void
   235 SemanticAnalysis::unaryTypeError(AstNode *node, TokenKind token, Handle<Type> type)
   236 {
   237     const char *op = TokenNames[token];
   238     const char *name = GetTypeName(type);
   239 
   240     cc_.reportError(node->pos(), Message_UnaryTypeError, op, name);
   241 }
   242 
   243 void
   244 SemanticAnalysis::binaryTypeError(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
   245 {
   246     const char *op = TokenNames[token];
   247     const char *leftName = GetTypeName(left);
   248     const char *rightName = GetTypeName(right);
   249 
   250     cc_.reportError(node->pos(), Message_BinaryTypeError, op, leftName, rightName);
   251 }
   252 
   253 Type *
   254 SemanticAnalysis::typeCheckBinary(AstNode *node, TokenKind token, Handle<Type> left, Handle<Type> right)
   255 {
   256     if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
   257         (token >= TOK_ASSIGN_ADD && token <= TOK_ASSIGN_DIV))
   258     {
   259         // If either side is a float, the other side must be a float or int.
   260         if (left->isFloat() || right->isFloat()) {
   261             Type *floatType = left->isFloat() ? left : right;
   262             Type *other = left->isFloat() ? right : left;
   263             if (other->isFloat() || (other->isInt32() && !other->tag()))
   264                 return floatType;
   265         }
   266     }
   267 
   268     if (token == TOK_OR || token == TOK_AND) {
   269         if (!canTest(node, left) || !canTest(node, right))
   270             return NULL;
   271         return zone_->types()->getPrimitive(PrimitiveType_Int32);
   272     }
   273 
   274     if (token >= TOK_EQUALS && token <= TOK_GE) {
   275         if ((left->isFloat() || (left->isInt32() && !left->tag())) &&
   276             (right->isFloat() || (right->isInt32() && !right->tag())))
   277         {
   278             return zone_->types()->getPrimitive(PrimitiveType_Int32);
   279         }
   280         binaryTypeError(node, token, left, right);
   281         return NULL;
   282     }
   283 
   284     if ((!left->isInt32() || left->tag()) ||
   285         (!right->isInt32() || right->tag()))
   286     {
   287         binaryTypeError(node, token, left, right);
   288         return NULL;
   289     }
   290 
   291     return left;
   292 }
   293 
   294 bool
   295 SemanticAnalysis::canTest(AstNode *node, Handle<Type> type)
   296 {
   297     if (type->isArray() || (type->isInt32() && type->tag())) {
   298         cc_.reportError(node->pos(), Message_ArrayIsNotBoolean);
   299         return false;
   300     }
   301     return true;
   302 }
   303 
   304 Type *
   305 SemanticAnalysis::visitForLValue(Expression *expression)
   306 {
   307     if (expression->isIndexExpression()) {
   308         Type *type = visitAndApplyType(expression);
   309         if (!type)
   310             return NULL;
   311 
   312         if (type->isConst()) {
   313             cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
   314             return NULL;
   315         }
   316 
   317         return type->contained();
   318     }
   319 
   320     if (!expression->isNameProxy()) {
   321         cc_.reportError(expression->pos(), Message_ExpectedLValue);
   322         return NULL;
   323     }
   324 
   325     NameProxy *proxy = expression->toNameProxy();
   326     if (!proxy->binding()->kind() == BoundName::VARIABLE) {
   327         cc_.reportError(expression->pos(), Message_ExpectedLValue);
   328         return NULL;
   329     }
   330 
   331     Variable *var = proxy->binding()->toVariable();
   332     if (!var->type())
   333         return NULL;
   334 
   335     if  (var->type()->isReference()) {
   336         if (var->type()->isConst()) {
   337             cc_.reportError(expression->pos(), Message_ReferenceIsConstant);
   338             return NULL;
   339         }
   340         return var->type()->contained();
   341     }
   342     return var->type();
   343 }
   344 
   345 SemanticAnalysis::ControlStatus
   346 SemanticAnalysis::visitForControl(Statement *statement)
   347 {
   348     ControlScope scope(&control_);
   349     statement->accept(this);
   350     return scope.status();
   351 }
   352 
   353 void
   354 SemanticAnalysis::visit(NameProxy *name)
   355 {
   356     BoundName *binding = name->binding();
   357 
   358     if (binding->scope()->kind() == Scope::GLOBAL) {
   359         if (!function_ || function_->isPublic()) {
   360             // Whatever we're referencing must be kept alive no matter what.
   361             // As such, we simply mark it used, and don't do anything special.
   362             binding->setUsed();
   363         } else if (!binding->used() && binding->kind() == BoundName::FUNCTION) {
   364             // Otherwise, we're inside a normal stock or function. Since we
   365             // don't really know if we've been used yet, we shouldn't
   366             // prematurely references as alive. Instead, we keep a list of
   367             // which names have been used, so we can mark them later if needed.
   368             //
   369             // Note that we skip this step if the binding is already in the
   370             // root set.
   371             if (!function_->addUsedGlobal(binding))
   372                 return;
   373         }
   374     }
   375 
   376     name->setType(binding->type());
   377 }
   378 
   379 void
   380 SemanticAnalysis::visit(Assignment *node)
   381 {
   382     Local<Type> exprType(zone_, visitForLoad(node->expression()));
   383     if (!exprType)
   384         return ;
   385 
   386     Local<Type> type(zone_, visitForLValue(node->lvalue()));
   387     if (!type)
   388         return;
   389 
   390     if (node->token() != TOK_ASSIGN) {
   391         if (!typeCheckBinary(node, node->token(), type, exprType))
   392             return;
   393     }
   394 
   395     if (!typeCheckAssignment(node, exprType, type, true))
   396         return;
   397 
   398     node->setType(type);
   399 }
   400 
   401 void
   402 SemanticAnalysis::visit(IncDecExpression *node)
   403 {
   404     Local<Type> type(zone_, visitForLValue(node->expression()));
   405     if (!type)
   406         return;
   407 
   408     assert(!type->isReference());
   409 
   410     if ((!type->isInt32() || (type->isInt32() && type->tag())) && !type->isFloat()) {
   411         unaryTypeError(node, node->token(), type);
   412         return;
   413     }
   414 
   415     node->setType(type);
   416 }
   417 
   418 void
   419 SemanticAnalysis::visit(UnaryExpression *node)
   420 {
   421     Local<Type> type(zone_, visitForLoad(node->expression()));
   422     if (!type)
   423         return;
   424 
   425     switch (node->token())
   426     {
   427       case TOK_NOT:
   428         if (!canTest(node->expression(), type))
   429             return;
   430         type = zone_->types()->getPrimitive(PrimitiveType_Int32);
   431         if (!type)
   432             return;
   433         node->setType(type);
   434         break;
   435 
   436       case TOK_MINUS:
   437         if (!type->isFloat() && (!type->isInt32() || type->tag())) {
   438             unaryTypeError(node, node->token(), type);
   439             return;
   440         }
   441         node->setType(type);
   442         break;
   443 
   444       case TOK_LABEL:
   445       {
   446         Local<String> tag(zone_, node->tag());
   447         Local<Type> to(zone_, zone_->types()->getPrimitiveForTag(tag));
   448         if (!to)
   449             return;
   450 
   451         if ((!type->isFloat() && !type->isInt32()) ||
   452             (!to->isFloat() && !to->isInt32()))
   453         {
   454             unaryTypeError(node, node->token(), type);
   455             return;
   456         }
   457 
   458         node->setType(to);
   459         break;
   460       }
   461 
   462       default:
   463         assert(node->token() == TOK_TILDE);
   464         if (!type->isInt32() || type->tag()) {
   465             unaryTypeError(node, node->token(), type);
   466             return;
   467         }
   468         node->setType(type);
   469         break;
   470     }
   471 }
   472 
   473 void
   474 SemanticAnalysis::visit(TernaryExpression *node)
   475 {
   476     Local<Type> type(zone_, visitForLoad(node->condition()));
   477     if (!type)
   478         return;
   479 
   480     if (!canTest(node->condition(), type))
   481         return;
   482 
   483     Local<Type> left(zone_, visitForLoad(node->left()));
   484     Local<Type> right(zone_, visitForLoad(node->right()));
   485     if (!left || !right)
   486         return;
   487 
   488     if (left != right) {
   489         binaryTypeError(node, TOK_QMARK, left, right);
   490         return;
   491     }
   492 }
   493 
   494 void
   495 SemanticAnalysis::visit(BinaryExpression *node)
   496 {
   497     Local<Type> left(zone_, visitForLoad(node->left()));
   498     Local<Type> right(zone_, visitForLoad(node->right()));
   499     if (!left || !right)
   500         return;
   501 
   502     Local<Type> result(zone_, typeCheckBinary(node, node->token(), left, right));
   503     if (!result)
   504         return;
   505 
   506     node->setType(result);
   507 }
   508 
   509 void
   510 SemanticAnalysis::visit(ReturnStatement *node)
   511 {
   512     // Set this early, so if we error we don't get more errors.
   513     control_->returns(Returns_Always);
   514 
   515     if (!node->expression()) {
   516         if (!function_->type()->returnType()->isVoid())
   517             cc_.reportError(node->pos(), Message_NotAllPathsReturnValue);
   518         return;
   519     }
   520 
   521     Local<Type> type(zone_, visitForLoad(node->expression()));
   522     if (!type)
   523         return;
   524 
   525     Local<Type> returnType(zone_, function_->type()->returnType());
   526     if (!typeCheckAssignment(node, type, returnType, true))
   527         return;
   528 }
   529 
   530 void
   531 SemanticAnalysis::visit(ForStatement *node)
   532 {
   533     LoopScope loop(&loop_);
   534 
   535     if (node->scope())
   536         scope_ = node->scope();
   537 
   538     if (node->initialization())
   539         node->initialization()->accept(this);
   540 
   541     if (node->condition()) {
   542         Local<Type> type(zone_, visitForLoad(node->condition()));
   543         if (!type || !canTest(node->condition(), type)) {
   544             return;
   545         }
   546     }
   547 
   548     if (node->update())
   549         node->update()->accept(this);
   550 
   551     ControlStatus status = visitForControl(node->body());
   552 
   553     // If there is a condition, we treat this like a while loop. Otherwise,
   554     // join point is only reachable if the loop contains a break. The
   555     // termination status doesn't tell us anything yet.
   556     if (node->condition() || loop.breaks())
   557         control_->merge(status, ControlStatus(false, Returns_Never));
   558     else
   559         control_->terminate(status.returns());
   560 
   561     if (node->scope())
   562         scope_ = scope_->enclosing();
   563 }
   564 
   565 void 
   566 SemanticAnalysis::visit(WhileStatement *node)
   567 {
   568     LoopScope loop(&loop_);
   569 
   570     Local<Type> type(zone_, visitForLoad(node->condition()));
   571     if (!type || !canTest(node->condition(), type)) {
   572         return;
   573     }
   574 
   575     ControlStatus status = visitForControl(node->body());
   576 
   577     // Detect loops that will always have a fork in the control-flow graph.
   578     // This will be a |while| loop, or a |do-while| loop whose body does
   579     // not terminate.
   580     //
   581     // For now, we treat these as an |if| regardless of the direction the
   582     // branch can take. That means the control-flow is always conditional.
   583     if (node->token() == TOK_WHILE ||
   584         !status.terminates() ||
   585         loop.breaks())
   586     {
   587         control_->merge(status, ControlStatus(false, Returns_Never));
   588     } else {
   589         // At this point, we've got a do-while loop with a |return| or
   590         // |continue|, meaning that the rest of the block is unreachable.
   591         control_->terminate(status.returns());
   592     }
   593 }
   594 
   595 void
   596 SemanticAnalysis::visit(BlockStatement *node)
   597 {
   598     if (node->scope())
   599         scope_ = node->scope();
   600     for (size_t i = 0; i < node->statements()->length(); i++) {
   601         Statement *statement = node->statements()->at(i);
   602         statement->accept(this);
   603     }
   604     if (node->scope())
   605         scope_ = scope_->enclosing();
   606 }
   607 
   608 void
   609 SemanticAnalysis::visit(VariableDeclaration *node)
   610 {
   611     Local<String> tag(zone_, node->tag());
   612     Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
   613     if (!type)
   614         return;
   615 
   616     if (node->postDimensions()) {
   617         Local<Type> init(zone_);
   618         if (node->initialization()) {
   619             if ((init = visitForLoad(node->initialization())) == NULL)
   620                 return;
   621         }
   622 
   623         if (node->postDimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
   624             cc_.reportError(node->pos(), Message_MaximumArrayDepth);
   625             return;
   626         }
   627 
   628         // If we have an initializer, make sure it's the same type.
   629         if (init && node->postDimensions()->length() != init->levels()) {
   630             cc_.reportError(node->pos(), Message_ArrayInitializerDepth);
   631             return;
   632         }
   633 
   634         Local<Type> check(zone_, init);
   635         for (size_t i = node->postDimensions()->length() - 1; i < node->postDimensions()->length(); i--) {
   636             Expression *expr = node->postDimensions()->at(i);
   637             int size = -1;
   638 
   639             if (expr) {
   640                 Local<Type> exprType(zone_, visitForLoad(expr));
   641                 if (!exprType)
   642                     return;
   643 
   644                 if (!IsPrimitiveType(exprType, PrimitiveType_Int32)) {
   645                     cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
   646                     return;
   647                 }
   648 
   649                 BoxedPrimitive box;
   650                 if (EvaluateForConstant(expr, &box) && box.type() == PrimitiveType_Int32) {
   651                     size = box.toInt();
   652                     if (size <= 0) {
   653                         cc_.reportError(expr->pos(), Message_BadArraySize);
   654                         return;
   655                     }
   656                     if (size >= int(INT_MAX / sizeof(int))) {
   657                         cc_.reportError(expr->pos(), Message_ArraySizeTooBig);
   658                         return;
   659                     }
   660 
   661                     if (check) {
   662                         if (check->elements() == -1) {
   663                             cc_.reportError(expr->pos(), Message_ArraySizeCannotBeDetermined);
   664                             return;
   665                         }
   666 
   667                         if (check->isCharArray()) {
   668                             if (check->elements() > size) {
   669                                 cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
   670                                 return;
   671                             }
   672                         } else if (check->elements() != size) {
   673                             cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, unsigned(i));
   674                             return;
   675                         }
   676                     }
   677                 } else {
   678                     if (init) {
   679                         cc_.reportError(node->pos(), Message_DynamicArrayHasInitializer);
   680                         return;
   681                     }
   682 
   683                     // here until we get dynamic array support.
   684                     cc_.reportError(expr->pos(), Message_ArrayDimensionNotInteger);
   685                     return;
   686                 }
   687             } else {
   688                 // Infer the size from the initializer.
   689                 if (!init) {
   690                     cc_.reportError(node->pos(), Message_ArraySizeNotSpecified);
   691                     return;
   692                 }
   693                 if (init->elements() == -1) {
   694                     cc_.reportError(node->pos(), Message_ArraySizeCannotBeDetermined);
   695                     return;
   696                 }
   697                 size = init->elements();
   698             }
   699 
   700             type = zone_->types()->unsafeArray(type, size, false);
   701             if (!type)
   702                 return;
   703 
   704             if (check)
   705                 check = check->contained();
   706         }
   707 
   708         // If this variable is stack allocated, we could use the LIFO heap
   709         // to allocate it. If that's the case, make sure to reserve a slot
   710         // so we can unwind the LIFO heap at the end of this scope.
   711         if (!node->variable()->needsHeapAllocation())
   712             scope_->setUsesLifoHeap();
   713     } else {
   714         if (node->initialization()) {
   715             Local<Type> right(zone_, visitForLoad(node->initialization()));
   716             if (!right)
   717                 return;
   718             if (!typeCheckAssignment(node, type, right, true))
   719                 return;
   720         }
   721         if (type->primitive() == PrimitiveType_Char) {
   722             cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
   723             return;
   724         }
   725     }
   726 
   727     node->variable()->setType(type);
   728 }
   729 
   730 void
   731 SemanticAnalysis::visit(IntegerLiteral *node)
   732 {
   733     node->setType(zone_->types()->getPrimitive(PrimitiveType_Int32));
   734 }
   735 
   736 void
   737 SemanticAnalysis::visit(ExpressionStatement *node)
   738 {
   739     visitAndApplyType(node->expression());
   740 }
   741 
   742 bool
   743 SemanticAnalysis::preanalyze(FunctionStatement *node)
   744 {
   745     Local<FixedArray> args(zone_, FixedArray::New(zone_, node->parameters()->length(), Heap::Tenure_Old));
   746     if (!args)
   747         return false;
   748 
   749     // Apply types to arguments.
   750     for (size_t i = 0; i < node->parameters()->length(); i++) {
   751         Parameter *parameter = node->parameters()->at(i);
   752         
   753         Local<String> tag(zone_, parameter->tag());
   754         Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
   755         if (!type)
   756             return false;
   757 
   758         if (parameter->reference()) {
   759             if (parameter->dimensions()) {
   760                 cc_.reportError(parameter->variable()->pos(), Message_ArrayCantBeReference);
   761                 return NULL;
   762             }
   763 
   764             type = zone_->types()->getReference(type, parameter->isConst());
   765             if (!type)
   766                 return false;
   767         } else if (parameter->dimensions()) {
   768             if (parameter->dimensions()->length() > Type::MAX_UNSAFE_ARRAY_DEPTH) {
   769                 cc_.reportError(parameter->variable()->pos(), Message_MaximumArrayDepth);
   770                 return false;
   771             }
   772 
   773             if (node->fun()->isNative() && parameter->dimensions()->length() > 1) {
   774                 cc_.reportError(parameter->variable()->pos(), Message_MultiArrayInNative);
   775                 return false;
   776             }
   777 
   778             for (size_t i = parameter->dimensions()->length() - 1;
   779                  i < parameter->dimensions()->length();
   780                  i++)
   781             {
   782                 int size = Type::UNKNOWN_SIZE;
   783                 if (Expression *expr = parameter->dimensions()->at(i)) {
   784                     BoxedPrimitive box;
   785                     if (!EvaluateForConstant(expr, &box)) {
   786                         cc_.reportError(expr->pos(), Message_ArraySizeMustBeConstant);
   787                         return false;
   788                     }
   789                     size = box.toInt();
   790                 }
   791 
   792                 type = zone_->types()->unsafeArray(type, size, parameter->isConst());
   793                 if (!type)
   794                     return false;
   795             }
   796         }
   797 
   798         if ((type->isPrimitive() && type->primitive() == PrimitiveType_Char) ||
   799             (type->isReference() && type->contained()->primitive() == PrimitiveType_Char))
   800         {
   801             cc_.reportError(node->pos(), Message_CannotDeclareStringCell);
   802             return false;
   803         }
   804 
   805         args->set(zone_, i, type);
   806         parameter->variable()->setType(type);
   807     }
   808 
   809     Local<Type> returnType(zone_);
   810     if (node->returnTag()) {
   811         Local<String> tag(zone_, node->returnTag());
   812         returnType = zone_->types()->getPrimitiveForTag(tag);
   813     } else if (node->hasExplicitReturn() || node->fun()->isNative()) {
   814         returnType = zone_->types()->getPrimitive(PrimitiveType_Int32);
   815     } else {
   816         returnType = zone_->types()->getVoid();
   817     }
   818     if (!returnType)
   819         return false;
   820 
   821     Local<Type> funtype(zone_);
   822     if (node->fun()->isNative())
   823         funtype = zone_->types()->newNative(returnType, args, node->fun()->isNativeVariadic());
   824     else
   825         funtype = zone_->types()->newFunction(returnType, args);
   826     if (!funtype)
   827         return false;
   828     
   829     // If the function already has a type, it was forward declared before, and
   830     // now this is our chance to type check the second declaration.
   831     if (node->fun()->type()) {
   832         Local<Type> forward(zone_, node->fun()->type());
   833         if (!Type::Compare(funtype, forward)) {
   834             cc_.reportError(node->pos(), Message_ForwardDeclareMismatches);
   835             return false;
   836         }
   837         node->fun()->setForwardType(forward);
   838     }
   839 
   840     node->fun()->setType(funtype);
   841 
   842     return true;
   843 }
   844 
   845 void
   846 SemanticAnalysis::visit(FunctionStatement *node)
   847 {
   848     function_ = node->fun();
   849     scope_ = node->scope();
   850 
   851     ControlScope control(&control_);
   852     if (node->body()) {
   853         node->body()->accept(this);
   854 
   855         ControlStatus status = control.status();
   856         if (status.returns() == Returns_Sometimes) {
   857             cc_.reportError(node->pos(), Message_NotAllPathsReturnValue);
   858         } else if (status.returns() == Returns_Never) {
   859             if (!function_->type()->returnType()->isVoid())
   860                 cc_.reportError(node->pos(), Message_MissingReturnValue);
   861         }
   862     }
   863 
   864     scope_ = NULL;
   865     function_ = NULL;
   866 }
   867 
   868 bool
   869 SemanticAnalysis::typeCheckArrayAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
   870 {
   871     Local<Type> actual(zone_, argActual);
   872     Local<Type> given(zone_, argGiven);
   873 
   874     if (!given->isArray()) {
   875         cc_.reportError(node->pos(), Message_ExpectedArray);
   876         return false;
   877     }
   878     if (given->levels() != actual->levels()) {
   879         cc_.reportError(node->pos(), Message_ArrayDimensionsMismatch);
   880         return false;
   881     }
   882 
   883     unsigned level = 0;
   884     while (given->isArray()) {
   885         if (actual->elements() != -1) {
   886             if (forAssign) {
   887                 if (given->elements() == -1 || actual->elements() == -1) {
   888                     cc_.reportError(node->pos(), Message_ArraySizeNotKnown);
   889                     return false;
   890                 }
   891 
   892                 if (actual->isCharArray()) {
   893                     // String assignment can have a truncated |given|.
   894                     if (given->elements() > actual->elements()) {
   895                         cc_.reportError(node->pos(), Message_ArrayAssignmentTooBig);
   896                         return false;
   897                     }
   898                 } else {
   899                     if (given->elements() != actual->elements()) {
   900                         cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
   901                         return false;
   902                     }
   903                 }
   904             } else {
   905                 if (actual->elements() != -1 && given->elements() != actual->elements()) {
   906                     cc_.reportError(node->pos(), Message_ArrayDimensionSizeMismatch, level);
   907                     return false;
   908                 }
   909             }
   910         }
   911         given = given->contained();
   912         actual = actual->contained();
   913     }
   914 
   915     if (given->primitive() != actual->primitive()) {
   916         // :TODO: leaks an interior pointer.
   917         const char *givenTag = given->tag() ? given->tag()->chars() : "_";
   918         const char *actualTag = given->tag() ? given->tag()->chars() : "_";
   919         cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
   920         return false;
   921     }
   922 
   923     return true;
   924 }
   925 
   926 bool
   927 SemanticAnalysis::typeCheckAssignment(AstNode *node, Handle<Type> argGiven, Handle<Type> argActual, bool forAssign)
   928 {
   929     Local<Type> actual(zone_, argActual);
   930     Local<Type> given(zone_, argGiven);
   931 
   932     if (actual->isArray())
   933         return typeCheckArrayAssignment(node, given, actual, forAssign);
   934 
   935     if (given->isArray()) {
   936         cc_.reportError(node->pos(), Message_CannotAssignArrayToScalar);
   937         return false;
   938     }
   939 
   940     // The given type may not have been dereferenced.
   941     if (given->isReference())
   942         given = given->contained();
   943     if (actual->isReference())
   944         actual = actual->contained();
   945 
   946     if (!given->isPrimitive() || !actual->isPrimitive()) {
   947         cc_.reportError(node->pos(), Message_UnsupportedType);
   948         return false;
   949     }
   950     
   951     if (given->primitive() != actual->primitive()) {
   952         // :TODO: leaks an interior pointer
   953         const char *givenTag = given->tag() ? given->tag()->chars() : "_";
   954         const char *actualTag = actual->tag() ? actual->tag()->chars() : "_";
   955         cc_.reportError(node->pos(), Message_TagMismatch, actualTag, givenTag);
   956         return false;
   957     }
   958 
   959     return true;
   960 }
   961 
   962 bool
   963 SemanticAnalysis::typeCheckParameter(AstNode *node, Handle<Type> given, Handle<Type> actual)
   964 {
   965     return typeCheckAssignment(node, given, actual, false);
   966 }
   967 
   968 void
   969 SemanticAnalysis::visit(CallExpression *node)
   970 {
   971     Local<Type> type(zone_, visitForLoad(node->callee()));
   972     if (!type)
   973         return;
   974 
   975     if (!type->isFunction()) {
   976         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   977         return;
   978     }
   979     if (node->arguments()->length() != type->parameters()->length()) {
   980         if (!type->isNative() ||
   981             !type->isNativeVariadic() ||
   982             node->arguments()->length() < type->parameters()->length())
   983         {
   984             cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   985             return;
   986         }
   987     }
   988 
   989     // Currently, only calls from a NameProxy are possible.
   990     NamedFunction *fun = node->callee()->toNameProxy()->binding()->toNamedFunction();
   991     if (fun->isForward()) {
   992         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   993         return;
   994     }
   995 
   996     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   997         // Note: we don't compute references unless the callee needs a
   998         // reference type.
   999         Expression *expression = node->arguments()->at(i);
  1000         Local<Type> given(zone_, visitAndApplyType(expression));
  1001         if (!given)
  1002             return;
  1003 
  1004         // Since we skip a load, check for a call expression that returns void.
  1005         if (given->isVoid()) {
  1006             assert(expression->isCallExpression());
  1007             CallExpression *call = expression->toCallExpression();
  1008             cc_.reportError(call->callee()->pos(), Message_FunctionDoesNotReturnValue);
  1009             return;
  1010         }
  1011         
  1012         // If it's an IndexExpression, we special case the ability to compute
  1013         // a reference.
  1014         if (expression->isIndexExpression())
  1015             given = given->contained();
  1016 
  1017         bool mustComputeReference;
  1018         if (i >= type->parameters()->length()) {
  1019             // Special handling for natives. Arguments past the formal must
  1020             // always have references computed. However, arrays are already
  1021             // references for natives.  
  1022             assert(type->isNative() && type->isNativeVariadic());
  1023             mustComputeReference = !given->isReference() && !given->isArray();
  1024         } else {
  1025             Local<Type> actual(zone_, type->parameterAt(i));
  1026             if (!typeCheckParameter(expression, given, actual))
  1027                 return;
  1028             mustComputeReference = actual->isReference() && !given->isReference();
  1029         }
  1030 
  1031         // If the actual is a reference, and the given is not, we'll need to
  1032         // compute a reference, which may be allocated on the stack.
  1033         if (mustComputeReference)
  1034             scope_->setUsesLifoHeap();
  1035     }
  1036 
  1037     node->setType(fun->type()->returnType());
  1038 }
  1039 
  1040 void
  1041 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
  1042 {
  1043     // If both sides terminate in a return, we consider this a return as well.
  1044     if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
  1045         terminate(Returns_Always);
  1046         return;
  1047     }
  1048 
  1049     ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
  1050                           ? Returns_Never
  1051                           : Returns_Sometimes;
  1052 
  1053     if (left.terminates() && right.terminates())
  1054         terminate(status);
  1055     else
  1056         returns(status);
  1057 }
  1058 
  1059 void
  1060 SemanticAnalysis::visit(IfStatement *node)
  1061 {
  1062     Local<Type> type(zone_, visitForLoad(node->condition()));
  1063     if (!type)
  1064         return;
  1065 
  1066     if (!canTest(node, type))
  1067         return;
  1068 
  1069     ControlStatus trueBranch = visitForControl(node->ifTrue());
  1070     ControlStatus falseBranch = ControlStatus(false, Returns_Never);
  1071 
  1072     if (node->ifFalse())
  1073         falseBranch = visitForControl(node->ifFalse());
  1074 
  1075     control_->merge(trueBranch, falseBranch);
  1076 }
  1077 
  1078 void
  1079 SemanticAnalysis::visit(IndexExpression *node)
  1080 {
  1081     Local<Type> left(zone_, visitForLoad(node->left()));
  1082     Local<Type> right(zone_, visitForLoad(node->right()));
  1083 
  1084     if (!left || !right)
  1085         return;
  1086 
  1087     if (!right->isInt32()) {
  1088         cc_.reportError(node->right()->pos(), Message_IndexMustBeInteger);
  1089         return;
  1090     }
  1091     if (!left->isArray()) {
  1092         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
  1093         return;
  1094     }
  1095     node->setType(left);
  1096 }
  1097 
  1098 void
  1099 SemanticAnalysis::visit(EnumStatement *node)
  1100 {
  1101     // Forbid the blessed types.
  1102     Local<String> tag(zone_, node->name());
  1103     if (!strcmp(tag->chars(), "Float") ||
  1104         !strcmp(tag->chars(), "String") ||
  1105         !strcmp(tag->chars(), "any") ||
  1106         !strcmp(tag->chars(), "bool"))
  1107     {
  1108         cc_.reportError(node->pos(), Message_InvalidEnumName);
  1109         return;
  1110     }
  1111 
  1112     Local<Type> type(zone_, zone_->types()->getPrimitiveForTag(tag));
  1113     if (!type)
  1114         return;
  1115 
  1116     int value = 0;
  1117     for (size_t i = 0; i < node->entries()->length(); i++) {
  1118         EnumStatement::Entry &entry = node->entries()->at(i);
  1119 
  1120         BoxedPrimitive box = BoxedPrimitive::Int(value);
  1121         if (entry.expr) {
  1122             entry.expr->accept(this);
  1123             if (!EvaluateForConstant(entry.expr, &box)) {
  1124                 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
  1125                 return;
  1126             }
  1127 
  1128             assert(box.type() == PrimitiveType_Int32);
  1129             value = box.toInt();
  1130         }
  1131 
  1132         entry.name->set(type, box);
  1133         value++;
  1134     }
  1135 }
  1136 
  1137 void
  1138 SemanticAnalysis::visit(StringLiteral *node)
  1139 {
  1140     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Char));
  1141     if (!type)
  1142         return;
  1143 
  1144     type = Type::NewArray(zone_, type, node->string()->length() + 1, true);
  1145     if (!type)
  1146         return;
  1147 
  1148     node->setType(type);
  1149 }
  1150 
  1151 void
  1152 SemanticAnalysis::visit(FloatLiteral *node)
  1153 {
  1154     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
  1155     if (!type)
  1156         return;
  1157 
  1158     node->setType(type);
  1159 }
  1160 
  1161 void
  1162 SemanticAnalysis::visit(BreakStatement *node)
  1163 {
  1164     if (!loop_) {
  1165         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
  1166         return;
  1167     }
  1168 
  1169     // Note: ignore breaks that occur in unreachable control-flow.
  1170     if (!control_->status().terminates())
  1171         loop_->addBreak();
  1172 
  1173     control_->terminate(Returns_Never);
  1174 }
  1175 
  1176 void
  1177 SemanticAnalysis::visit(ContinueStatement *node)
  1178 {
  1179     if (!loop_) {
  1180         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
  1181         return;
  1182     }
  1183 
  1184     // Note: ignore continues that occur in unreachable control-flow.
  1185     if (!control_->status().terminates())
  1186         loop_->addContinue();
  1187 
  1188     control_->terminate(Returns_Never);
  1189 }