src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Mon Dec 24 16:09:13 2012 -0800 (2012-12-24)
changeset 236 072f1114ea5d
parent 235 43287eef2fff
child 237 c77540a61905
permissions -rw-r--r--
Re-implement array assignment.
     1 /* vim: set ts=4 sw=4 tw=99 et:
     2  *
     3  * Copyright (C) 2012 David Anderson
     4  *
     5  * This file is part of SourcePawn.
     6  *
     7  * SourcePawn 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  * SourcePawn 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  * SourcePawn. If not, see http://www.gnu.org/licenses/.
    18  */
    19 #include <assert.h>
    20 #include "../Zone.h"
    21 #include "../Strings.h"
    22 #include "../NativeTable.h"
    23 #include "../TypeManager.h"
    24 #include "../Modules.h"
    25 #include "../Code.h"
    26 #include "SemanticAnalysis.h"
    27 #include "../Heap-inl.h"
    28 
    29 using namespace ke;
    30 
    31 #define __ emitter_.
    32 
    33 typedef BytecodeEmitter::Label Label;
    34 
    35 class AutoEnterScope
    36 {
    37   public:
    38     AutoEnterScope(Scope **prevp, Scope *scope)
    39       : prevp_(prevp),
    40         prev_(*prevp),
    41         scope_(scope)
    42     {
    43         if (!scope_)
    44             return;
    45         prev_ = *prevp_;
    46         *prevp_ = scope;
    47         assert(prev_ == scope->enclosing());
    48     }
    49     ~AutoEnterScope()
    50     {
    51         if (scope_)
    52             *prevp_ = prev_;
    53     }
    54   private:
    55     Scope **prevp_;
    56     Scope *prev_;
    57     Scope *scope_;
    58 };
    59 
    60 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, TranslationUnit *unit)
    61   : zone_(zone),
    62     pool_(zone->pool()),
    63     cc_(cc),
    64     unit_(unit),
    65     hir_(NULL),
    66     emitter_(pool_),
    67     module_(NULL),
    68     loop_(NULL)
    69 {
    70 }
    71 
    72 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
    73   : zone_(parent->zone_),
    74     pool_(parent->pool_),
    75     cc_(parent->cc_),
    76     unit_(parent->unit_),
    77     hir_(NULL),
    78     scope_(parent->scope_),
    79     emitter_(pool_),
    80     module_(parent->module_),
    81     fun_(fun),
    82     loop_(NULL),
    83     control_(NULL)
    84 {
    85 
    86 }
    87 
    88 void
    89 SemanticAnalysis::analyze()
    90 {
    91     scope_ = unit_->globalScope();
    92 
    93     module_ = Module::New(zone_);
    94 
    95     for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
    96         Statement *stmt = unit_->tree()->statements()->at(i);
    97         stmt->accept(this);
    98     }
    99 
   100     Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
   101     if (!globals)
   102         return;
   103     module_->setGlobals(globals);
   104 
   105     Local<Code> code(zone_, __ finish());
   106     if (!code)
   107         return;
   108     code->setModule(module_);
   109     module_->setCode(code);
   110 
   111 #ifndef NDEBUG
   112 //    Disassemble(code, stdout);
   113 #endif
   114 
   115     unit_->module_ = module_;
   116 }
   117 
   118 void
   119 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
   120 {
   121     FunctionSymbol *sym = stmt->sym();
   122     Local<FunctionType> type(zone_, sym->type());
   123 
   124     assert(scope_->kind() == Scope::GLOBAL);
   125 
   126     if (stmt->token() == TOK_NATIVE) {
   127         // Define the native now.
   128         size_t index;
   129         if (!zone_->nativeTable()->add(stmt->name(), &index))
   130             return;
   131 
   132         Local<Native> native(zone_, Native::New(zone_, type, index));
   133         if (!native)
   134             return;
   135 
   136         __ object(native);
   137         __ setglobal(sym);
   138         __ pop();
   139     }
   140 
   141     // If the function is a forward or native, we don't have to do anything.
   142     if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
   143         return;
   144 
   145     SemanticAnalysis child(this, type);
   146     Local<Function> funobj(zone_, child.compile(stmt));
   147     if (!funobj)
   148         return;
   149 
   150     __ object(funobj);
   151     __ setglobal(sym);
   152     if (stmt->token() == TOK_PUBLIC)
   153         __ public_();
   154     else
   155         __ pop();
   156 }
   157 
   158 Function *
   159 SemanticAnalysis::compile(FunctionStatement *stmt)
   160 {
   161     __ setFirstLine(stmt->pos().line);
   162 
   163     AutoEnterScope argScope(&scope_, stmt->argScope());
   164 
   165     for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
   166         Parameter *param = stmt->signature().parameters()->at(i);
   167         param->sym()->allocate(VariableSymbol::Arg, i);
   168     }
   169 
   170     AutoEnterScope varScope(&scope_, stmt->varScope());
   171     ControlStatus status = visitForControl(stmt->body());
   172 
   173     if (!fun_->returnType()->isVoid()) {
   174         // If the function is not void, report if not all paths return a value.
   175         // All other incorrect return cases have been caught already.
   176         if (status.returns() == Returns_Sometimes) {
   177             cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
   178             return NULL;
   179         }
   180 
   181         if (status.returns() == Returns_Never) {
   182             cc_.reportError(stmt->pos(), Message_MissingReturnValue);
   183             return NULL;
   184         }
   185     }
   186 
   187     Local<Code> code(zone_, __ finish());
   188     if (!code)
   189         return NULL;
   190     code->setModule(module_);
   191 
   192     Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
   193     if (!fun)
   194         return NULL;
   195 
   196 #ifndef NDEBUG
   197 //    Disassemble(code, stdout);
   198 #endif
   199 
   200     return fun;
   201 }
   202 
   203 void 
   204 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
   205 {
   206     AutoEnterScope scope(&scope_, node->scope());
   207 
   208     for (size_t i = 0; i < node->statements()->length(); i++) {
   209         Statement *stmt = node->statements()->at(i);
   210         __ note_position(stmt->pos());
   211         stmt->accept(this);
   212         assert(__ stackDepth() == 0);
   213     }
   214 }
   215 
   216 void
   217 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
   218 {
   219 }
   220 
   221 void
   222 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
   223 {
   224     // While building HIR, we enter new pool and root scopes, since HIR
   225     // creation is purely temporary.
   226     PoolScope poolScope(zone_->pool());
   227     RootScope rootScope(zone_);
   228 
   229     HIR *hir = eval(node->expression());
   230     if (!hir)
   231         return;
   232 
   233     discharge(hir);
   234     if (!hir->type()->isVoid())
   235         __ pop();
   236 }
   237 
   238 void
   239 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
   240 {
   241     // If both sides terminate in a return, we consider this a return as well.
   242     if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
   243         terminate(Returns_Always);
   244         return;
   245     }
   246 
   247     ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
   248                           ? Returns_Never
   249                           : Returns_Sometimes;
   250 
   251     if (left.terminates() && right.terminates())
   252         terminate(status);
   253     else
   254         returns(status);
   255 }
   256 
   257 SemanticAnalysis::ControlStatus
   258 SemanticAnalysis::visitForControl(Statement *statement)
   259 {
   260     ControlScope scope(&control_);
   261     statement->accept(this);
   262     return scope.status();
   263 }
   264 
   265 void
   266 SemanticAnalysis::visitIfStatement(IfStatement *node)
   267 {
   268     Label join;
   269 
   270     ControlStatus trueBranch;
   271     ControlStatus falseBranch(false, Returns_Never);
   272 
   273     if (!node->ifFalse()) {
   274         Label success;
   275 
   276         visitForTest(node->condition(), &success, &join, &success);
   277         __ bind(&success);
   278         trueBranch = visitForControl(node->ifTrue());
   279     } else {
   280         Label success, next;
   281 
   282         visitForTest(node->condition(), &success, &next, &success);
   283         __ bind(&success);
   284         trueBranch = visitForControl(node->ifTrue());
   285         __ jump(&join);
   286         __ bind(&next);
   287         falseBranch = visitForControl(node->ifFalse());
   288     }
   289 
   290     __ bind(&join);
   291 
   292     control_->merge(trueBranch, falseBranch);
   293 }
   294 
   295 void
   296 SemanticAnalysis::requireLifoStack()
   297 {
   298     if (!loop_)
   299         return;
   300 
   301     loop_->setUsesLifoStack();
   302 }
   303 
   304 SemanticAnalysis::ControlStatus
   305 SemanticAnalysis::visitLoopBody(Statement *stmt)
   306 {
   307     // We always mark off a loop body, so on each edge, we can balance the
   308     // LIFO stack. Right now, we don't have the ability to budget the LIFO
   309     // stack ahead of time. If we turn out to never need the LIFO stack, we
   310     // mark it as unnecessary. (The interpreter can't really make use of this,
   311     // but the JIT can).
   312     //
   313     // Note that balancing the LIFO stack isn't even necessary, so this
   314     // feature may be removed. All this mechanism does is mitigate the
   315     // possibility that a long-running loop will overflow the LIFO region
   316     // and therefore start requiring nursery allocations.
   317     int pos = __ enterloop();
   318     ControlStatus status = visitForControl(stmt);
   319     __ leaveloop();
   320 
   321     if (loop_->usesLifoStack())
   322         __ setLoopUsesLifoStack(pos);
   323 
   324     return status;
   325 }
   326 
   327 void
   328 SemanticAnalysis::visitForStatement(ForStatement *node)
   329 {
   330     AutoEnterScope scope(&scope_, node->scope());
   331     PoolScope poolScope(zone_->pool());
   332     RootScope rootScope(zone_);
   333 
   334     Label join, update;
   335     LoopScope loop(scope_, &join, &update, &loop_);
   336 
   337     if (node->initialization())
   338         node->initialization()->accept(this);
   339 
   340     Label header, test;
   341     if (node->condition())
   342         __ jump(&test);
   343 
   344     __ bind(&header);
   345     ControlStatus status = visitLoopBody(node->body());
   346 
   347     __ bind(&update);
   348     if (node->update())
   349         node->update()->accept(this);
   350 
   351     if (node->condition()) {
   352         __ bind(&test);
   353         visitForTest(node->condition(), &header, &join, &join);
   354     } else {
   355         __ jump(&header);
   356     }
   357 
   358     __ bind(&join);
   359     
   360     // If there was a condition, we treat this like a while loop. Otherwise,
   361     // the join point is only reachable if the loop contains a break. The
   362     // termination status doesn't tell us anything yet.
   363     if (node->condition() || loop.breaks())
   364         control_->merge(status, ControlStatus(false, Returns_Never));
   365     else
   366         control_->terminate(status.returns());
   367 
   368     assert(__ stackDepth() == 0);
   369 }
   370 
   371 void
   372 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
   373 {
   374     PoolScope poolScope(zone_->pool());
   375     RootScope rootScope(zone_);
   376 
   377     Label header, join;
   378 
   379     __ bind(&header);
   380 
   381     ControlStatus status;
   382 
   383     LoopScope loop(scope_, &join, &header, &loop_);
   384     if (node->token() == TOK_WHILE) {
   385         Label body;
   386         visitForTest(node->condition(), &body, &join, &body);
   387         status = visitLoopBody(node->body());
   388         __ jump(&header);
   389     } else {
   390         status = visitLoopBody(node->body());
   391         visitForTest(node->condition(), &header, &join, &join);
   392     }
   393 
   394     __ bind(&join);
   395 
   396     // Detect loops that will always have a fork in the contro-flow graph.
   397     // This will be a |while| loop, or a |do-while| loop whose body does
   398     // not terminate. For now, we treat these as an |if| regardless of the
   399     // direction the branch can take. That means the control-flow is always
   400     // conditional.
   401     if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
   402         control_->merge(status, ControlStatus(false, Returns_Never));
   403     } else {
   404         // At this point, we've got a do-while loop with a |return| or
   405         // |continue|, meaning that the rest of the block is unreachable.
   406         control_->terminate(status.returns());
   407     }
   408 
   409     assert(__ stackDepth() == 0);
   410 }
   411 
   412 static inline Heap::Tenure
   413 InferTenure(Symbol *sym)
   414 {
   415     if (sym->scope()->kind() == Scope::GLOBAL)
   416         return Heap::Tenure_Old;
   417 
   418     // SP2's array semantics allow any array kind to escape, so we must use
   419     // the normal heap. (Hopefully escape analysis can ease this pain later).
   420     if (sym->type()->isArray())
   421         return Heap::Tenure_Default;
   422 
   423     return Heap::Tenure_Default;
   424 }
   425 
   426 void
   427 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   428 {
   429     PoolScope poolScope(zone_->pool());
   430     RootScope rootScope(zone_);
   431 
   432     Local<Type> type(zone_, node->sym()->type());
   433 
   434     if (node->initialization()) {
   435         HIR *hir = NULL;
   436 
   437         if ((hir = eval(node->initialization())) == NULL)
   438             return;
   439         if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
   440             return;
   441 
   442         discharge(hir);
   443     } else {
   444         if (type->isInt32() || type->isEnum() ||
   445             type->isChar() || type->isBool())
   446         {
   447             __ int_(0);
   448         } else if (type->isFloat()) {
   449             __ float_(0);
   450         } else if (type->isArray()) {
   451             Local<ArrayType> atype(zone_, ArrayType::cast(type));
   452             Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, atype));
   453             if (!map)
   454                 return;
   455 
   456             if (atype->isFixedLength()) {
   457                 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
   458             } else if (node->dims()->at(0)) {
   459                 // This may not be true if we allow typedefing, so :TODO:
   460                 // figure out proper semantics.
   461                 assert(node->dims()->length() == atype->levels());
   462 
   463                 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   464                 for (size_t i = 0; i < node->dims()->length(); i++) {
   465                     Expression *expr = node->dims()->at(i);
   466                     if (expr) {
   467                         HIR *hir = eval(expr);
   468                         if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
   469                             return;
   470                         discharge(hir);
   471                     } else {
   472                         __ int_(0);
   473                     }
   474                 }
   475                 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
   476             } else {
   477                 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
   478             }
   479         } else {
   480             assert(false);
   481         }
   482     }
   483 
   484     if (node->sym()->scope()->kind() != Scope::GLOBAL) {
   485         if (!__ allocate(node->sym()))
   486             return;
   487     }
   488 
   489     set(node->sym());
   490     __ pop();
   491 }
   492 
   493 void
   494 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   495 {
   496     control_->returns(Returns_Always);
   497 
   498     if (!node->expression()) {
   499         if (!fun_->returnType()->isVoid()) {
   500             cc_.reportError(node->pos(), Message_MissingReturnValue);
   501             return;
   502         }
   503 
   504         __ returnvoid();
   505         return;
   506     }
   507 
   508     if (fun_->returnType()->isVoid()) {
   509         cc_.reportError(node->pos(), Message_UsedVoidReturn);
   510         return;
   511     }
   512 
   513     PoolScope poolScope(zone_->pool());
   514     RootScope rootScope(zone_);
   515 
   516     HIR *hir = eval(node->expression());
   517     if (!hir)
   518         return;
   519 
   520     Local<Type> returnType(zone_, fun_->returnType());
   521     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   522         return;
   523 
   524     discharge(hir);
   525 
   526     if (hir->type()->isVoid())
   527         __ returnvoid();
   528     else
   529         __ return_();
   530 }
   531 
   532 void
   533 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   534 {
   535     HIR *left = eval(node->left());
   536     HIR *right = eval(node->right());
   537     if (!left || !right)
   538         return;
   539 
   540     hir_ = binary(node, node->token(), left, right);
   541 }
   542 
   543 bool
   544 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   545 {
   546     if (type->parameters()->length() == actual)
   547         return true;
   548 
   549     if (actual > type->parameters()->length()) {
   550         if (!type->isNative() || !type->isNativeVariadic())
   551             return false;
   552         return true;
   553     }
   554 
   555     if (!type->defaults())
   556         return false;
   557 
   558     // Missing arguments. See if there's a default argument for each missing
   559     // actual.
   560     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   561         if (!type->defaults()->at(i))
   562             return false;
   563     }
   564 
   565     return true;
   566 }
   567 
   568 void
   569 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   570 {
   571     Symbol *sym = proxy->sym();
   572 
   573     switch (sym->kind()) {
   574       case Symbol::kConstant:
   575       {
   576         ConstantSymbol *val = sym->toConstant();
   577         hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
   578         break;
   579       }
   580       
   581       // This is kind of screwy. Symbol::kFunction is like a constant we can't
   582       // evaluate yet. Maybe we should extract the GLOBAL case and say that
   583       // kFunction is only used for global functions (and use const vars for
   584       // local functions).
   585       case Symbol::kFunction:
   586       case Symbol::kVariable:
   587       {
   588         Scope *in = sym->scope();
   589         switch (in->kind()) {
   590           case Scope::GLOBAL:
   591             hir_ = new (pool_) HGlobal(proxy, sym);
   592             break;
   593 
   594           case Scope::FUNCTION:
   595           {
   596             VariableSymbol *var = sym->toVariable();
   597             assert(var->storage() == VariableSymbol::Arg);
   598             hir_ = new (pool_) HLocal(proxy, var);
   599             break;
   600           }
   601 
   602           default:
   603           {
   604             VariableSymbol *var = sym->toVariable();
   605             assert(in->kind() == Scope::BLOCK);
   606             assert(var->storage() == VariableSymbol::Local);
   607             hir_ = new (pool_) HLocal(proxy, var);
   608             break;
   609           }
   610         }
   611         break;
   612       }
   613 
   614       default:
   615         // :TODO:
   616         assert(false);
   617     }
   618 }
   619 
   620 void
   621 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   622 {
   623     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   624     hir_ = new (pool_) HInteger(lit, type, lit->value());
   625 }
   626 
   627 void
   628 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   629 {
   630     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   631     hir_ = new (pool_) HFloat(node, type, (float)node->value());
   632 }
   633 
   634 void
   635 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
   636 {
   637     Type *type = zone_->types()->getString();
   638     hir_ = new (pool_) HString(node, type, node->string());
   639 }
   640 
   641 void
   642 SemanticAnalysis::visitCallExpression(CallExpression *node)
   643 {
   644     HIR *callee = eval(node->callee());
   645     if (!callee)
   646         return;
   647 
   648     if (!callee->type()->isFunction()) {
   649         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   650         return;
   651     }
   652 
   653     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   654     
   655     if (!checkArgumentCount(fun, node->arguments()->length())) {
   656         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   657         return;
   658     }
   659 
   660     if (fun->isForward()) {
   661         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   662         return;
   663     }
   664 
   665     HIRList *args = new (pool_) HIRList;
   666     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   667         Expression *expression = node->arguments()->at(i);
   668         HIR *arg = eval(expression);
   669         if (!arg)
   670             return;
   671 
   672         Handle<Type> given = arg->type();
   673         
   674         bool mustComputeReference;
   675         if (i >= fun->parameters()->length()) {
   676             // Special handling for natives. Arguments past the formal must
   677             // always have references computed. However, arrays are already
   678             // references for natives.
   679             assert(fun->isNative() && fun->isNativeVariadic());
   680             mustComputeReference = !given->isReference() &&
   681                                    !given->isArray();
   682         } else {
   683             Local<Type> actual(zone_, fun->parameterAt(i));
   684 
   685             if (expression->isIndexExpression()) {
   686                 // Temporarily disabled.
   687                 assert(!actual->isArray());
   688                 if (actual->isReference()) {
   689                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   690                     return;
   691                 }
   692             }
   693 
   694             if (actual->isReference()) {
   695                 // If the actual is a reference, the coercion rules are much
   696                 // stricter; the contained types must be identical.
   697                 // :TODO: make this not an assert
   698                 assert(ReferenceType::cast(actual)->contained() == arg->type());
   699             } else {
   700                 // When we start overloading, coercion will have to happen later.
   701                 arg = coerce(arg, actual, Coerce_Arg);
   702                 if (!arg)
   703                     return;
   704             }
   705 
   706             mustComputeReference = actual->isReference() && !given->isReference();
   707         }
   708 
   709         if (mustComputeReference) {
   710             // Refs always use the LIFO stack if they can.
   711             arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
   712             requireLifoStack();
   713         }
   714 
   715         if (!args->append(arg))
   716             return;
   717     }
   718 
   719     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   720 }
   721 
   722 void
   723 SemanticAnalysis::visitAssignment(Assignment *node)
   724 {
   725     HLValue *lval = lvalue(node->lvalue());
   726     if (!lval)
   727         return;
   728 
   729     HIR *hir = eval(node->expression());
   730     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   731         return;
   732 
   733     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   734 }
   735 
   736 void
   737 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   738 {
   739     if (!loop_) {
   740         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   741         return;
   742     }
   743 
   744     loop_->setBreaks();
   745     __ j(OP_BREAK, loop_->break_());
   746 }
   747 
   748 void
   749 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   750 {
   751     if (!loop_) {
   752         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   753         return;
   754     }
   755 
   756     __ j(OP_CONTINUE, loop_->continue_());
   757 }
   758 
   759 void
   760 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   761 {
   762     HIR *left = eval(node->left());
   763     if (!left)
   764         return;
   765 
   766     HIR *right = eval(node->right());
   767     if (!right)
   768         return;
   769 
   770     // Hrm... yes, for now, let's coerce here.
   771     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   772     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   773         return;
   774     
   775     // Do not coerce here, there's no reason to yet.
   776     if (!left->type()->isArray()) {
   777         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   778         return;
   779     }
   780 
   781     hir_ = new (pool_) HIndex(node,
   782                               ArrayType::cast(left->type())->contained(),
   783                               left,
   784                               right);
   785 }
   786 
   787 void
   788 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   789 {
   790     HLValue *lval = lvalue(node->expression());
   791     if (!lval)
   792         return;
   793 
   794     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   795         assert(false);
   796         return;
   797     }
   798 
   799     HIR *rval;
   800     if (lval->type()->isInt32())
   801         rval = new (pool_) HInteger(node, lval->type(), 1);
   802     else
   803         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   804 
   805     if (node->postfix())
   806         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   807     else
   808         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   809 }
   810 
   811 Type *
   812 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   813 {
   814     Handle<Type> l = left->type();
   815     Handle<Type> r = right->type();
   816 
   817     if (token >= TOK_PLUS && token <= TOK_SLASH) {
   818         // We allow: [float|int32] + [float|int32]
   819         if (l->isFloat() && r->isInt32())
   820             return l;
   821         if (l->isInt32() && r->isFloat())
   822             return r;
   823         if (l->isInt32() && r->isInt32())
   824             return l;
   825     }
   826 
   827     // :TODO: remove
   828     assert(l == r);
   829 
   830     return left->type();
   831 }
   832 
   833 HIR *
   834 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   835                                  HIR *from,
   836                                  Handle<Type> argActual,
   837                                  CoercionKind kind)
   838 {
   839     Local<Type> argGiven(zone_, from->type());
   840 
   841     // Special case: if we receive a string literal, and this is a char array,
   842     // we allow a coercion.
   843     if (from->isString() &&
   844         argGiven->isString() &&
   845         argActual->isArray() &&
   846         ArrayType::cast(argActual)->isCharArray())
   847     {
   848         HString *hir = from->toString();
   849         Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   850 
   851         if (actual->isFixedLength()) {
   852             if (hir->string()->length() + 1 > actual->fixedLength()) {
   853                 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   854                 return NULL;
   855             }
   856         }
   857 
   858         // Transform the string literal into an array literal. We give it the
   859         // type of the left-hand side. The constness of the destination type
   860         // will determine whether HArray duplicates it or not.
   861         Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, actual));
   862         if (!map)
   863             return NULL;
   864 
   865         Local<Array> array(zone_);
   866         array = Array::NewString(zone_,
   867                                  map,
   868                                  hir->string()->chars(),
   869                                  hir->string()->length(),
   870                                  Heap::Tenure_Old);
   871         if (!array)
   872             return NULL;
   873 
   874         // Since we're creating a canonical copy of the char array, we have to
   875         // be careful that it doesn't get mutated. There are two cases where
   876         // we know it can't be mutated, and therefore don't need to specify
   877         // that it be cloned after pushing it onto the stack.
   878         //
   879         //  (1) The array type is const.
   880         //  (2) The array type is fixed-length, and the coercion is for
   881         //      assignment, meaning it will be immediately copied.
   882         //
   883         // We treat declaration separately from assignment, since for
   884         // declaration we can just immediately use the cloned version.
   885         bool shouldDuplicate = true;
   886         if (actual->isConst() ||
   887             (actual->isFixedLength() && kind == Coerce_Assign))
   888         {
   889             shouldDuplicate = false;
   890         }
   891 
   892         return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
   893     }
   894 
   895     if (!argGiven->isArray()) {
   896         cc_.reportError(pos, Message_ExpectedArray);
   897         return NULL;
   898     }
   899 
   900     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   901     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
   902 
   903     if (actual->levels() != given->levels()) {
   904         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
   905         return NULL;
   906     }
   907 
   908     unsigned level = 1;
   909     while (true) {
   910         if (actual->isFixedLength()) {
   911             if (!given->isFixedLength()) {
   912                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   913                 return NULL;
   914             }
   915 
   916             if (actual->isCharArray()) {
   917                 // String assignment can have a truncated |given|.
   918                 if (given->fixedLength() > actual->fixedLength()) {
   919                     cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   920                     return NULL;
   921                 }
   922             } else {
   923                 if (given->fixedLength() != actual->fixedLength()) {
   924                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   925                     return NULL;
   926                 }
   927             }
   928         } else if (given->isFixedLength()) {
   929             // We do not allow assignments in the form:
   930             //  [][] = [][Y]
   931             //
   932             // Otherwise, the following code could break the size guarantees
   933             // of the right-hand side:
   934             //
   935             //  new x[][5];
   936             //  new y[][];
   937             //  new z[3];
   938             //
   939             //
   940             //  y = x;
   941             //  y[0] = z;
   942             //
   943             // Now |x[0]| contains a 3-length array.
   944             if (level > 1) {
   945                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   946                 return NULL;
   947             }
   948         }
   949 
   950         if (!given->contained()->isArray() || !actual->contained()->isArray())
   951             break;
   952 
   953         given = ArrayType::cast(given->contained());
   954         actual = ArrayType::cast(actual->contained());
   955     }
   956 
   957     // These arrays must contain the same innermost type.
   958     if (given->contained() != actual->contained()) {
   959         cc_.reportError(pos, Message_TypeMismatch,
   960                         GetTypeName(actual->contained()),
   961                         GetTypeName(given->contained()));
   962         return false;
   963     }
   964 
   965     return from;
   966 }
   967 
   968 HIR *
   969 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
   970 {
   971     cc_.reportError(pos, Message_InvalidCoercion,
   972                     GetTypeName(from),
   973                     GetTypeName(to));
   974     return NULL;
   975 }
   976 
   977 HIR *
   978 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
   979 {
   980     Local<Type> from(zone_, hir->type());
   981 
   982     if (from->isInt32() && to->isFloat())
   983         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
   984     if (from->isInt32() && to->isBool())
   985         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
   986 
   987     if (to->isEnum() && *from != to)
   988         return typeFailure(hir->node()->pos(), from, to);
   989     
   990     if (to->isArray())
   991         return typeCheckArray(SourcePosition(), hir, to, kind);
   992     
   993     return hir;
   994 }
   995 
   996 void
   997 SemanticAnalysis::set(VariableSymbol *sym)
   998 {
   999     if (sym->scope()->kind() == Scope::GLOBAL) {
  1000         __ setglobal(sym);
  1001     } else {
  1002         assert(sym->storage() == VariableSymbol::Local);
  1003         __ setlocal(sym);
  1004     }
  1005 }
  1006 
  1007 HIR *
  1008 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
  1009 {
  1010     Local<Type> coercion(zone_, coercionType(token, left, right));
  1011     if (!coercion)
  1012         return NULL;
  1013     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
  1014         return NULL;
  1015     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
  1016         return NULL;
  1017     
  1018     switch (token) {
  1019      case TOK_PLUS:
  1020       case TOK_MINUS:
  1021       case TOK_STAR:
  1022       case TOK_SLASH:
  1023       case TOK_PERCENT:
  1024       case TOK_AMPERSAND:
  1025       case TOK_BITOR:
  1026       case TOK_BITXOR:
  1027       case TOK_SHR:
  1028       case TOK_USHR:
  1029       case TOK_SHL:
  1030         return new (pool_) HBinary(node, left->type(), token, left, right);
  1031 
  1032       case TOK_EQUALS:
  1033       case TOK_NOTEQUALS:
  1034       case TOK_LT:
  1035       case TOK_LE:
  1036       case TOK_GT:
  1037       case TOK_GE:
  1038       case TOK_AND:
  1039       case TOK_OR:
  1040       {
  1041         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1042         return new (pool_) HBinary(node, result, token, left, right);
  1043       }
  1044 
  1045       default:
  1046         assert(false);
  1047         return NULL;
  1048     }
  1049 }
  1050 
  1051 static inline TokenKind
  1052 ToCompare(Expression *expr)
  1053 {
  1054     if (expr->isBinaryExpression()) {
  1055         BinaryExpression *b = expr->toBinaryExpression();
  1056         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
  1057             return b->token();
  1058     } else if (expr->isUnaryExpression()) {
  1059         UnaryExpression *u = expr->toUnaryExpression();
  1060         if (u->token() == TOK_NOT)
  1061             return TOK_NOT;
  1062     }
  1063     return TOK_EOF;
  1064 }
  1065 
  1066 void
  1067 SemanticAnalysis::visitForTest(Expression *expr,
  1068                                Label *trueBranch,
  1069                                Label *falseBranch,
  1070                                Label *fallthrough)
  1071 {
  1072     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1073 
  1074     TokenKind token = ToCompare(expr);
  1075     if (token == TOK_EOF || token == TOK_NOT) {
  1076         HIR *hir;
  1077         if (token == TOK_EOF)
  1078             hir = eval(expr);
  1079         else
  1080             hir = eval(expr->toUnaryExpression()->expression());
  1081         if (!hir)
  1082             return;
  1083         if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1084             return;
  1085 
  1086         discharge(hir);
  1087 
  1088         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
  1089         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
  1090         
  1091         if (fallthrough == falseBranch)
  1092             __ j(op, trueBranch);
  1093         else
  1094             __ j(op, falseBranch);
  1095         return;
  1096     }
  1097 
  1098     BinaryExpression *bin = expr->toBinaryExpression();
  1099     if (token == TOK_AND || token == TOK_OR) {
  1100         assert(false);
  1101         //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
  1102         return;
  1103     }
  1104 
  1105     HIR *left = eval(bin->left());
  1106     HIR *right = eval(bin->right());
  1107     if (!left || !right)
  1108         return;
  1109 
  1110     HIR *hir = binary(bin, bin->token(), left, right);
  1111     if (!hir)
  1112         return;
  1113     if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1114         return;
  1115 
  1116     discharge(hir);
  1117     if (fallthrough == trueBranch)
  1118         __ j(OP_JF, falseBranch);
  1119     else
  1120         __ j(OP_JT, trueBranch);
  1121 }
  1122 
  1123 HLValue *
  1124 SemanticAnalysis::lvalue(Expression *expr)
  1125 {
  1126     HIR *hir = eval(expr);
  1127     if (!hir)
  1128         return NULL;
  1129     
  1130     if (!hir->isLValue()) {
  1131         cc_.reportError(expr->pos(), Message_ExpectedLValue);
  1132         return NULL;
  1133     }
  1134 
  1135     return static_cast<HLValue *>(hir);
  1136 }
  1137 
  1138 HIR *
  1139 SemanticAnalysis::eval(Expression *expr)
  1140 {
  1141     assert(!hir_);
  1142     expr->accept(this);
  1143 
  1144     HIR *hir = hir_;
  1145     hir_ = NULL;
  1146 
  1147     return hir;
  1148 }
  1149 
  1150 void
  1151 SemanticAnalysis::discharge(HIR *hir)
  1152 {
  1153     EmitHIR(zone_, emitter_, hir);
  1154 }