src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Sat Dec 22 23:18:57 2012 -0800 (2012-12-22)
changeset 233 bbb498ccb4ac
parent 232 2b8512340180
child 234 26e3035cdffc
permissions -rw-r--r--
Re-add enum support.
     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     if (node->initialization()) {
   433         HIR *hir = NULL;
   434 
   435         if ((hir = eval(node->initialization())) == NULL)
   436             return;
   437         if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
   438             return;
   439 
   440         discharge(hir);
   441     } else {
   442         if (node->sym()->type()->isInt32() ||
   443             node->sym()->type()->isEnum() ||
   444             node->sym()->type()->isChar() ||
   445             node->sym()->type()->isBool())
   446         {
   447             __ int_(0);
   448         } else if (node->sym()->type()->isFloat()) {
   449             __ float_(0);
   450         } else if (node->sym()->type()->isArray()) {
   451             Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
   452             Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
   453             if (!map)
   454                 return;
   455 
   456             if (type->isFixedLength()) {
   457                 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
   458             } else if (node->dims()) {
   459                 assert(false);
   460                 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
   461             } else {
   462                 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
   463             }
   464         }
   465     }
   466 
   467     if (!__ allocate(node->sym()))
   468         return;
   469 
   470     set(node->sym());
   471     __ pop();
   472 }
   473 
   474 void
   475 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   476 {
   477     control_->returns(Returns_Always);
   478 
   479     if (!node->expression()) {
   480         if (!fun_->returnType()->isVoid()) {
   481             cc_.reportError(node->pos(), Message_MissingReturnValue);
   482             return;
   483         }
   484 
   485         __ returnvoid();
   486         return;
   487     }
   488 
   489     if (fun_->returnType()->isVoid()) {
   490         cc_.reportError(node->pos(), Message_UsedVoidReturn);
   491         return;
   492     }
   493 
   494     PoolScope poolScope(zone_->pool());
   495     RootScope rootScope(zone_);
   496 
   497     HIR *hir = eval(node->expression());
   498     if (!hir)
   499         return;
   500 
   501     Local<Type> returnType(zone_, fun_->returnType());
   502     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   503         return;
   504 
   505     discharge(hir);
   506 
   507     if (hir->type()->isVoid())
   508         __ returnvoid();
   509     else
   510         __ return_();
   511 }
   512 
   513 void
   514 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   515 {
   516     HIR *left = eval(node->left());
   517     HIR *right = eval(node->right());
   518     if (!left || !right)
   519         return;
   520 
   521     hir_ = binary(node, node->token(), left, right);
   522 }
   523 
   524 bool
   525 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   526 {
   527     if (type->parameters()->length() == actual)
   528         return true;
   529 
   530     if (actual > type->parameters()->length()) {
   531         if (!type->isNative() || !type->isNativeVariadic())
   532             return false;
   533         return true;
   534     }
   535 
   536     if (!type->defaults())
   537         return false;
   538 
   539     // Missing arguments. See if there's a default argument for each missing
   540     // actual.
   541     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   542         if (!type->defaults()->at(i))
   543             return false;
   544     }
   545 
   546     return true;
   547 }
   548 
   549 void
   550 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   551 {
   552     Symbol *sym = proxy->sym();
   553 
   554     switch (sym->kind()) {
   555       case Symbol::kConstant:
   556       {
   557         ConstantSymbol *val = sym->toConstant();
   558         hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
   559         break;
   560       }
   561       
   562       // This is kind of screwy. Symbol::kFunction is like a constant we can't
   563       // evaluate yet. Maybe we should extract the GLOBAL case and say that
   564       // kFunction is only used for global functions (and use const vars for
   565       // local functions).
   566       case Symbol::kFunction:
   567       case Symbol::kVariable:
   568       {
   569         Scope *in = sym->scope();
   570         switch (in->kind()) {
   571           case Scope::GLOBAL:
   572             hir_ = new (pool_) HGlobal(proxy, sym);
   573             break;
   574 
   575           case Scope::FUNCTION:
   576           {
   577             VariableSymbol *var = sym->toVariable();
   578             assert(var->storage() == VariableSymbol::Arg);
   579             hir_ = new (pool_) HLocal(proxy, var);
   580             break;
   581           }
   582 
   583           default:
   584           {
   585             VariableSymbol *var = sym->toVariable();
   586             assert(in->kind() == Scope::BLOCK);
   587             assert(var->storage() == VariableSymbol::Local);
   588             hir_ = new (pool_) HLocal(proxy, var);
   589             break;
   590           }
   591         }
   592         break;
   593       }
   594 
   595       default:
   596         // :TODO:
   597         assert(false);
   598     }
   599 }
   600 
   601 void
   602 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   603 {
   604     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   605     hir_ = new (pool_) HInteger(lit, type, lit->value());
   606 }
   607 
   608 void
   609 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   610 {
   611     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   612     hir_ = new (pool_) HFloat(node, type, (float)node->value());
   613 }
   614 
   615 void
   616 SemanticAnalysis::visitCallExpression(CallExpression *node)
   617 {
   618     HIR *callee = eval(node->callee());
   619     if (!callee)
   620         return;
   621 
   622     if (!callee->type()->isFunction()) {
   623         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   624         return;
   625     }
   626 
   627     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   628     
   629     if (!checkArgumentCount(fun, node->arguments()->length())) {
   630         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   631         return;
   632     }
   633 
   634     if (fun->isForward()) {
   635         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   636         return;
   637     }
   638 
   639     HIRList *args = new (pool_) HIRList;
   640     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   641         Expression *expression = node->arguments()->at(i);
   642         HIR *arg = eval(expression);
   643         if (!arg)
   644             return;
   645 
   646         Handle<Type> given = arg->type();
   647         
   648         bool mustComputeReference;
   649         if (i >= fun->parameters()->length()) {
   650             // Special handling for natives. Arguments past the formal must
   651             // always have references computed. However, arrays are already
   652             // references for natives.
   653             assert(fun->isNative() && fun->isNativeVariadic());
   654             mustComputeReference = !given->isReference() &&
   655                                    !given->isArray();
   656         } else {
   657             Local<Type> actual(zone_, fun->parameterAt(i));
   658 
   659             if (expression->isIndexExpression()) {
   660                 // Temporarily disabled.
   661                 assert(!actual->isArray());
   662                 if (actual->isReference()) {
   663                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   664                     return;
   665                 }
   666             }
   667 
   668             if (actual->isReference()) {
   669                 // If the actual is a reference, the coercion rules are much
   670                 // stricter; the contained types must be identical.
   671                 // :TODO: make this not an assert
   672                 assert(ReferenceType::cast(actual)->contained() == arg->type());
   673             } else {
   674                 // When we start overloading, coercion will have to happen later.
   675                 arg = coerce(arg, actual, Coerce_Arg);
   676                 if (!arg)
   677                     return;
   678             }
   679 
   680             mustComputeReference = actual->isReference() && !given->isReference();
   681         }
   682 
   683         if (mustComputeReference) {
   684             // Refs always use the LIFO stack if they can.
   685             arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
   686             requireLifoStack();
   687         }
   688 
   689         if (!args->append(arg))
   690             return;
   691     }
   692 
   693     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   694 }
   695 
   696 void
   697 SemanticAnalysis::visitAssignment(Assignment *node)
   698 {
   699     HLValue *lval = lvalue(node->lvalue());
   700     if (!lval)
   701         return;
   702 
   703     HIR *hir = eval(node->expression());
   704     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   705         return;
   706 
   707     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   708 }
   709 
   710 void
   711 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   712 {
   713     if (!loop_) {
   714         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   715         return;
   716     }
   717 
   718     loop_->setBreaks();
   719     __ j(OP_BREAK, loop_->break_());
   720 }
   721 
   722 void
   723 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   724 {
   725     if (!loop_) {
   726         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   727         return;
   728     }
   729 
   730     __ j(OP_CONTINUE, loop_->continue_());
   731 }
   732 
   733 void
   734 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   735 {
   736     HIR *left = eval(node->left());
   737     if (!left)
   738         return;
   739 
   740     HIR *right = eval(node->right());
   741     if (!right)
   742         return;
   743 
   744     // Hrm... yes, for now, let's coerce here.
   745     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   746     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   747         return;
   748     
   749     // Do not coerce here, there's no reason to yet.
   750     if (!left->type()->isArray()) {
   751         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   752         return;
   753     }
   754 
   755     hir_ = new (pool_) HIndex(node,
   756                               ArrayType::cast(left->type())->contained(),
   757                               left,
   758                               right);
   759 }
   760 
   761 void
   762 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   763 {
   764     HLValue *lval = lvalue(node->expression());
   765     if (!lval)
   766         return;
   767 
   768     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   769         assert(false);
   770         return;
   771     }
   772 
   773     HIR *rval;
   774     if (lval->type()->isInt32())
   775         rval = new (pool_) HInteger(node, lval->type(), 1);
   776     else
   777         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   778 
   779     if (node->postfix())
   780         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   781     else
   782         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   783 }
   784 
   785 Type *
   786 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   787 {
   788     Handle<Type> l = left->type();
   789     Handle<Type> r = right->type();
   790 
   791     if (token >= TOK_PLUS && token <= TOK_SLASH) {
   792         // We allow: [float|int32] + [float|int32]
   793         if (l->isFloat() && r->isInt32())
   794             return l;
   795         if (l->isInt32() && r->isFloat())
   796             return r;
   797         if (l->isInt32() && r->isInt32())
   798             return l;
   799     }
   800 
   801     // :TODO: remove
   802     assert(l == r);
   803 
   804     return left->type();
   805 }
   806 
   807 bool
   808 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   809                                  Handle<Type> argGiven,
   810                                  Handle<Type> argActual,
   811                                  CoercionKind kind)
   812 {
   813     if (!argGiven->isArray()) {
   814         cc_.reportError(pos, Message_ExpectedArray);
   815         return false;
   816     }
   817 
   818     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   819     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
   820 
   821     if (actual->levels() != given->levels()) {
   822         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
   823         return false;
   824     }
   825 
   826     unsigned level = 1;
   827     while (true) {
   828         if (actual->isFixedLength()) {
   829             if (kind == Coerce_Return || kind == Coerce_Assign) {
   830                 if (!given->isFixedLength()) {
   831                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   832                     return false;
   833                 }
   834 
   835                 if (actual->isCharArray()) {
   836                     // String assignment can have a truncated |given|.
   837                     if (given->fixedLength() > actual->fixedLength()) {
   838                         cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   839                         return false;
   840                     }
   841                 } else {
   842                     if (given->fixedLength() != actual->fixedLength()) {
   843                         cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   844                         return false;
   845                     }
   846                 }
   847             }
   848         } else if (given->isFixedLength()) {
   849             // We do not allow assignments in the form:
   850             //  [][] = [][Y]
   851             //
   852             // Otherwise, the following code could break the size guarantees
   853             // of the right-hand side:
   854             //
   855             //  new x[][5];
   856             //  new y[][];
   857             //  new z[3];
   858             //
   859             //
   860             //  y = x;
   861             //  y[0] = z;
   862             //
   863             // Now |x[0]| contains a 3-length array.
   864             if (level > 1) {
   865                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   866                 return false;
   867             }
   868         }
   869 
   870         if (!given->contained()->isArray() || !actual->contained()->isArray())
   871             break;
   872 
   873         given = ArrayType::cast(given->contained());
   874         actual = ArrayType::cast(actual->contained());
   875     }
   876 
   877     // These arrays must contain the same innermost type.
   878     if (given->contained() != actual->contained()) {
   879         cc_.reportError(pos, Message_TypeMismatch,
   880                         GetTypeName(actual->contained()),
   881                         GetTypeName(given->contained()));
   882         return false;
   883     }
   884 
   885     return true;
   886 }
   887 
   888 HIR *
   889 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
   890 {
   891     cc_.reportError(pos, Message_InvalidCoercion,
   892                     GetTypeName(from),
   893                     GetTypeName(to));
   894     return NULL;
   895 }
   896 
   897 HIR *
   898 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
   899 {
   900     Handle<Type> from = hir->type();
   901 
   902     if (from->isInt32() && to->isFloat())
   903         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
   904     if (from->isInt32() && to->isBool())
   905         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
   906 
   907     if (to->isEnum() && from != to)
   908         return typeFailure(hir->node()->pos(), from, to);
   909     
   910     if (to->isArray()) {
   911         if (!typeCheckArray(SourcePosition(), from, to, kind))
   912             return NULL;
   913         return hir;
   914     }
   915     
   916     return hir;
   917 }
   918 
   919 void
   920 SemanticAnalysis::set(VariableSymbol *sym)
   921 {
   922     if (sym->scope()->kind() == Scope::GLOBAL) {
   923         __ setglobal(sym);
   924     } else {
   925         assert(sym->storage() == VariableSymbol::Local);
   926         __ setlocal(sym);
   927     }
   928 }
   929 
   930 HIR *
   931 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
   932 {
   933     Local<Type> coercion(zone_, coercionType(token, left, right));
   934     if (!coercion)
   935         return NULL;
   936     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
   937         return NULL;
   938     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
   939         return NULL;
   940     
   941     switch (token) {
   942      case TOK_PLUS:
   943       case TOK_MINUS:
   944       case TOK_STAR:
   945       case TOK_SLASH:
   946       case TOK_PERCENT:
   947       case TOK_AMPERSAND:
   948       case TOK_BITOR:
   949       case TOK_BITXOR:
   950       case TOK_SHR:
   951       case TOK_USHR:
   952       case TOK_SHL:
   953         return new (pool_) HBinary(node, left->type(), token, left, right);
   954 
   955       case TOK_EQUALS:
   956       case TOK_NOTEQUALS:
   957       case TOK_LT:
   958       case TOK_LE:
   959       case TOK_GT:
   960       case TOK_GE:
   961       case TOK_AND:
   962       case TOK_OR:
   963       {
   964         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   965         return new (pool_) HBinary(node, result, token, left, right);
   966       }
   967 
   968       default:
   969         assert(false);
   970         return NULL;
   971     }
   972 }
   973 
   974 static inline TokenKind
   975 ToCompare(Expression *expr)
   976 {
   977     if (expr->isBinaryExpression()) {
   978         BinaryExpression *b = expr->toBinaryExpression();
   979         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
   980             return b->token();
   981     } else if (expr->isUnaryExpression()) {
   982         UnaryExpression *u = expr->toUnaryExpression();
   983         if (u->token() == TOK_NOT)
   984             return TOK_NOT;
   985     }
   986     return TOK_EOF;
   987 }
   988 
   989 void
   990 SemanticAnalysis::visitForTest(Expression *expr,
   991                                Label *trueBranch,
   992                                Label *falseBranch,
   993                                Label *fallthrough)
   994 {
   995     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   996 
   997     TokenKind token = ToCompare(expr);
   998     if (token == TOK_EOF || token == TOK_NOT) {
   999         HIR *hir;
  1000         if (token == TOK_EOF)
  1001             hir = eval(expr);
  1002         else
  1003             hir = eval(expr->toUnaryExpression()->expression());
  1004         if (!hir)
  1005             return;
  1006         if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
  1007             return;
  1008 
  1009         discharge(hir);
  1010 
  1011         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
  1012         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
  1013         
  1014         if (fallthrough == falseBranch)
  1015             __ j(op, trueBranch);
  1016         else
  1017             __ j(op, falseBranch);
  1018         return;
  1019     }
  1020 
  1021     BinaryExpression *bin = expr->toBinaryExpression();
  1022     if (token == TOK_AND || token == TOK_OR) {
  1023         assert(false);
  1024         //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
  1025         return;
  1026     }
  1027 
  1028     HIR *left = eval(bin->left());
  1029     HIR *right = eval(bin->right());
  1030     if (!left || !right)
  1031         return;
  1032 
  1033     HIR *hir = binary(bin, bin->token(), left, right);
  1034     if (!hir)
  1035         return;
  1036     if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
  1037         return;
  1038 
  1039     discharge(hir);
  1040     if (fallthrough == trueBranch)
  1041         __ j(OP_JF, falseBranch);
  1042     else
  1043         __ j(OP_JT, trueBranch);
  1044 }
  1045 
  1046 HLValue *
  1047 SemanticAnalysis::lvalue(Expression *expr)
  1048 {
  1049     HIR *hir = eval(expr);
  1050     if (!hir)
  1051         return NULL;
  1052     
  1053     if (!hir->isLValue()) {
  1054         cc_.reportError(expr->pos(), Message_ExpectedLValue);
  1055         return NULL;
  1056     }
  1057 
  1058     return static_cast<HLValue *>(hir);
  1059 }
  1060 
  1061 HIR *
  1062 SemanticAnalysis::eval(Expression *expr)
  1063 {
  1064     assert(!hir_);
  1065     expr->accept(this);
  1066 
  1067     HIR *hir = hir_;
  1068     hir_ = NULL;
  1069 
  1070     return hir;
  1071 }
  1072 
  1073 void
  1074 SemanticAnalysis::discharge(HIR *hir)
  1075 {
  1076     EmitHIR(zone_, emitter_, hir);
  1077 }