src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Mon Nov 19 02:12:13 2012 -0800 (2012-11-19)
changeset 221 0c588a96837c
parent 220 5df4a112967d
child 222 0cde1379b29f
permissions -rw-r--r--
Re-add line and column information to bytecode.
     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 {
    84 
    85 }
    86 
    87 void
    88 SemanticAnalysis::analyze()
    89 {
    90     scope_ = unit_->globalScope();
    91 
    92     module_ = Module::New(zone_);
    93 
    94     for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
    95         Statement *stmt = unit_->tree()->statements()->at(i);
    96         stmt->accept(this);
    97     }
    98 
    99     Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
   100     if (!globals)
   101         return;
   102     module_->setGlobals(globals);
   103 
   104     Local<Code> code(zone_, __ finish());
   105     if (!code)
   106         return;
   107     code->setModule(module_);
   108     module_->setCode(code);
   109 
   110 #ifndef NDEBUG
   111 //    Disassemble(code, stdout);
   112 #endif
   113 
   114     unit_->module_ = module_;
   115 }
   116 
   117 void
   118 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
   119 {
   120     FunctionSymbol *sym = stmt->sym();
   121     Local<FunctionType> type(zone_, sym->type());
   122 
   123     assert(scope_->kind() == Scope::GLOBAL);
   124 
   125     if (stmt->token() == TOK_NATIVE) {
   126         // Define the native now.
   127         size_t index;
   128         if (!zone_->nativeTable()->add(stmt->name(), &index))
   129             return;
   130 
   131         Local<Native> native(zone_, Native::New(zone_, type, index));
   132         if (!native)
   133             return;
   134 
   135         __ object(native);
   136         __ setglobal(sym);
   137         __ pop();
   138     }
   139 
   140     // If the function is a forward or native, we don't have to do anything.
   141     if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
   142         return;
   143 
   144     SemanticAnalysis child(this, type);
   145     Local<Function> funobj(zone_, child.compile(stmt));
   146     if (!funobj)
   147         return;
   148 
   149     __ object(funobj);
   150     __ setglobal(sym);
   151     if (stmt->token() == TOK_PUBLIC)
   152         __ public_();
   153     else
   154         __ pop();
   155 }
   156 
   157 Function *
   158 SemanticAnalysis::compile(FunctionStatement *stmt)
   159 {
   160     __ setFirstLine(stmt->pos().line);
   161 
   162     AutoEnterScope argScope(&scope_, stmt->argScope());
   163 
   164     for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
   165         Parameter *param = stmt->signature().parameters()->at(i);
   166         param->sym()->allocate(VariableSymbol::Arg, i);
   167     }
   168 
   169     AutoEnterScope varScope(&scope_, stmt->varScope());
   170 
   171     stmt->body()->accept(this);
   172 
   173     Local<Code> code(zone_, __ finish());
   174     if (!code)
   175         return NULL;
   176     code->setModule(module_);
   177 
   178     Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
   179     if (!fun)
   180         return NULL;
   181 
   182 #ifndef NDEBUG
   183 //    Disassemble(code, stdout);
   184 #endif
   185 
   186     return fun;
   187 }
   188 
   189 void 
   190 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
   191 {
   192     AutoEnterScope scope(&scope_, node->scope());
   193 
   194     for (size_t i = 0; i < node->statements()->length(); i++) {
   195         Statement *stmt = node->statements()->at(i);
   196         __ note_position(stmt->pos());
   197         stmt->accept(this);
   198         assert(__ stackDepth() == 0);
   199     }
   200 }
   201 
   202 void
   203 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
   204 {
   205     // While building HIR, we enter new pool and root scopes, since HIR
   206     // creation is purely temporary.
   207     PoolScope poolScope(zone_->pool());
   208     RootScope rootScope(zone_);
   209 
   210     HIR *hir = eval(node->expression());
   211     if (!hir)
   212         return;
   213 
   214     discharge(hir);
   215     if (!hir->type()->isVoid())
   216         __ pop();
   217 }
   218 
   219 void
   220 SemanticAnalysis::visitIfStatement(IfStatement *node)
   221 {
   222     Label join;
   223 
   224     if (!node->ifFalse()) {
   225         Label success;
   226 
   227         visitForTest(node->condition(), &success, &join, &success);
   228         __ bind(&success);
   229         node->ifTrue()->accept(this);
   230     } else {
   231         Label success, next;
   232 
   233         visitForTest(node->condition(), &success, &next, &success);
   234         __ bind(&success);
   235         node->ifTrue()->accept(this);
   236         __ jump(&join);
   237         __ bind(&next);
   238         node->ifFalse()->accept(this);
   239     }
   240 
   241     __ bind(&join);
   242 }
   243 
   244 void
   245 SemanticAnalysis::visitForStatement(ForStatement *node)
   246 {
   247     AutoEnterScope scope(&scope_, node->scope());
   248     PoolScope poolScope(zone_->pool());
   249     RootScope rootScope(zone_);
   250 
   251     Label join, update;
   252     LoopScope loop(scope_, &join, &update, &loop_);
   253 
   254     if (node->initialization())
   255         node->initialization()->accept(this);
   256 
   257     Label header, test;
   258     if (node->condition())
   259         __ jump(&test);
   260 
   261     __ bind(&header);
   262     node->body()->accept(this);
   263 
   264     __ bind(&update);
   265     if (node->update())
   266         node->update()->accept(this);
   267 
   268     if (node->condition()) {
   269         __ bind(&test);
   270         visitForTest(node->condition(), &header, &join, &join);
   271     } else {
   272         __ jump(&header);
   273     }
   274 
   275     __ bind(&join);
   276 
   277     assert(__ stackDepth() == 0);
   278 }
   279 
   280 void
   281 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
   282 {
   283     PoolScope poolScope(zone_->pool());
   284     RootScope rootScope(zone_);
   285 
   286     Label header, join;
   287 
   288     __ bind(&header);
   289 
   290     LoopScope loop(scope_, &join, &header, &loop_);
   291     if (node->token() == TOK_WHILE) {
   292         Label body;
   293         visitForTest(node->condition(), &body, &join, &body);
   294         node->body()->accept(this);
   295         __ jump(&header);
   296     } else {
   297         node->body()->accept(this);
   298         visitForTest(node->condition(), &header, &join, &join);
   299     }
   300 
   301     __ bind(&join);
   302 
   303     assert(__ stackDepth() == 0);
   304 }
   305 
   306 static inline Heap::Tenure
   307 InferTenure(Symbol *sym)
   308 {
   309     if (sym->scope()->kind() == Scope::GLOBAL)
   310         return Heap::Tenure_Old;
   311     // :TODO: need to use LIFO!
   312     return Heap::Tenure_Default;
   313 }
   314 
   315 void
   316 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   317 {
   318     PoolScope poolScope(zone_->pool());
   319     RootScope rootScope(zone_);
   320 
   321     if (node->initialization()) {
   322         HIR *hir = NULL;
   323 
   324         if ((hir = eval(node->initialization())) == NULL)
   325             return;
   326         if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
   327             return;
   328 
   329         discharge(hir);
   330     } else {
   331         if (node->sym()->type()->isInt32() ||
   332             node->sym()->type()->isEnum() ||
   333             node->sym()->type()->isChar() ||
   334             node->sym()->type()->isBool())
   335         {
   336             __ int_(0);
   337         } else if (node->sym()->type()->isFloat()) {
   338             __ float_(0);
   339         } else if (node->sym()->type()->isArray()) {
   340             Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
   341             Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
   342             if (!map)
   343                 return;
   344 
   345             if (type->isFixedLength()) {
   346                 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
   347             } else if (node->dims()) {
   348                 assert(false);
   349                 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
   350             } else {
   351                 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
   352             }
   353         }
   354     }
   355 
   356     if (!__ allocate(node->sym()))
   357         return;
   358 
   359     set(node->sym());
   360     __ pop();
   361 }
   362 
   363 void
   364 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   365 {
   366     if (!node->expression()) {
   367         if (!fun_->returnType()->isVoid()) {
   368             cc_.reportError(node->pos(), Message_UsedVoidReturn);
   369             return;
   370         }
   371 
   372         __ returnvoid();
   373         return;
   374     }
   375 
   376     PoolScope poolScope(zone_->pool());
   377     RootScope rootScope(zone_);
   378 
   379     HIR *hir = eval(node->expression());
   380     if (!hir)
   381         return;
   382 
   383     Local<Type> returnType(zone_, fun_->returnType());
   384     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   385         return;
   386 
   387     discharge(hir);
   388     __ return_();
   389 }
   390 
   391 void
   392 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   393 {
   394     HIR *left = eval(node->left());
   395     HIR *right = eval(node->right());
   396     if (!left || !right)
   397         return;
   398 
   399     hir_ = binary(node, node->token(), left, right);
   400 }
   401 
   402 bool
   403 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   404 {
   405     if (type->parameters()->length() == actual)
   406         return true;
   407 
   408     if (actual > type->parameters()->length()) {
   409         if (!type->isNative() || !type->isNativeVariadic())
   410             return false;
   411         return true;
   412     }
   413 
   414     if (!type->defaults())
   415         return false;
   416 
   417     // Missing arguments. See if there's a default argument for each missing
   418     // actual.
   419     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   420         if (!type->defaults()->at(i))
   421             return false;
   422     }
   423 
   424     return true;
   425 }
   426 
   427 void
   428 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   429 {
   430     Symbol *sym = proxy->sym();
   431     VariableSymbol *var = sym->asVariable();
   432 
   433     Scope *in = sym->scope();
   434     switch (in->kind()) {
   435       case Scope::GLOBAL:
   436         hir_ = new (pool_) HGlobal(proxy, sym);
   437         return;
   438 
   439       case Scope::FUNCTION:
   440         assert(var->storage() == VariableSymbol::Arg);
   441         hir_ = new (pool_) HLocal(proxy, var);
   442         return;
   443 
   444       default:
   445         assert(in->kind() == Scope::BLOCK);
   446         assert(var->storage() == VariableSymbol::Local);
   447         hir_ = new (pool_) HLocal(proxy, var);
   448         return;
   449     }
   450 }
   451 
   452 void
   453 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   454 {
   455     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   456     hir_ = new (pool_) HInteger(lit, type, lit->value());
   457 }
   458 
   459 void
   460 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   461 {
   462     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   463     hir_ = new (pool_) HFloat(node, type, (float)node->value());
   464 }
   465 
   466 void
   467 SemanticAnalysis::visitCallExpression(CallExpression *node)
   468 {
   469     HIR *callee = eval(node->callee());
   470     if (!callee)
   471         return;
   472 
   473     if (!callee->type()->isFunction()) {
   474         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   475         return;
   476     }
   477 
   478     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   479     
   480     if (!checkArgumentCount(fun, node->arguments()->length())) {
   481         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   482         return;
   483     }
   484 
   485     if (fun->isForward()) {
   486         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   487         return;
   488     }
   489 
   490     HIRList *args = new (pool_) HIRList;
   491     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   492         Expression *expression = node->arguments()->at(i);
   493         HIR *arg = eval(expression);
   494         if (!arg)
   495             return;
   496 
   497         Handle<Type> given = arg->type();
   498         
   499         bool mustComputeReference;
   500         if (i >= fun->parameters()->length()) {
   501             // Special handling for natives. Arguments past the formal must
   502             // always have references computed. However, arrays are already
   503             // references for natives.
   504             assert(fun->isNative() && fun->isNativeVariadic());
   505             mustComputeReference = !given->isReference() &&
   506                                    !given->isArray();
   507         } else {
   508             Local<Type> actual(zone_, fun->parameterAt(i));
   509 
   510             if (expression->isIndexExpression()) {
   511                 // Temporarily disabled.
   512                 assert(!actual->isArray());
   513                 if (actual->isReference()) {
   514                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   515                     return;
   516                 }
   517             }
   518 
   519             // When we start overloading, coercion will have to happen later.
   520             arg = coerce(arg, actual, Coerce_Arg);
   521             if (!arg)
   522                 return;
   523 
   524             mustComputeReference = actual->isReference() && !given->isReference();
   525         }
   526 
   527         // :TODO: handle mustComputeReference
   528         assert(!mustComputeReference);
   529 
   530         if (!args->append(arg))
   531             return;
   532     }
   533 
   534     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   535 }
   536 
   537 void
   538 SemanticAnalysis::visitAssignment(Assignment *node)
   539 {
   540     HLValue *lval = lvalue(node->lvalue());
   541     if (!lval)
   542         return;
   543 
   544     HIR *hir = eval(node->expression());
   545     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   546         return;
   547 
   548     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   549 }
   550 
   551 void
   552 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   553 {
   554     if (!loop_) {
   555         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   556         return;
   557     }
   558 
   559     // Note, if we re-introduce LIFO allocs, we need to unwind here.
   560     __ jump(loop_->break_());
   561 }
   562 
   563 void
   564 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   565 {
   566     if (!loop_) {
   567         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   568         return;
   569     }
   570 
   571     // Note, if we re-introduce LIFO allocs, we need to unwind here.
   572     __ jump(loop_->continue_());
   573 }
   574 
   575 void
   576 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   577 {
   578     HIR *left = eval(node->left());
   579     if (!left)
   580         return;
   581 
   582     HIR *right = eval(node->right());
   583     if (!right)
   584         return;
   585 
   586     // Hrm... yes, for now, let's coerce here.
   587     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   588     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   589         return;
   590     
   591     // Do not coerce here, there's no reason to yet.
   592     if (!left->type()->isArray()) {
   593         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   594         return;
   595     }
   596 
   597     hir_ = new (pool_) HIndex(node,
   598                               ArrayType::cast(left->type())->contained(),
   599                               left,
   600                               right);
   601 }
   602 
   603 void
   604 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   605 {
   606     HLValue *lval = lvalue(node->expression());
   607     if (!lval)
   608         return;
   609 
   610     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   611         assert(false);
   612         return;
   613     }
   614 
   615     HIR *rval;
   616     if (lval->type()->isInt32())
   617         rval = new (pool_) HInteger(node, lval->type(), 1);
   618     else
   619         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   620 
   621     if (node->postfix())
   622         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   623     else
   624         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   625 }
   626 
   627 Type *
   628 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   629 {
   630     Handle<Type> l = left->type();
   631     Handle<Type> r = right->type();
   632 
   633     if (token >= TOK_PLUS && token <= TOK_SLASH) {
   634         // We allow: [float|int32] + [float|int32]
   635         if (l->isFloat() && r->isInt32())
   636             return l;
   637         if (l->isInt32() && r->isFloat())
   638             return r;
   639         if (l->isInt32() && r->isInt32())
   640             return l;
   641     }
   642 
   643     assert(l == r);
   644 
   645     return left->type();
   646 }
   647 
   648 bool
   649 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   650                                  Handle<Type> argGiven,
   651                                  Handle<Type> argActual,
   652                                  CoercionKind kind)
   653 {
   654     if (!argGiven->isArray()) {
   655         cc_.reportError(pos, Message_ExpectedArray);
   656         return false;
   657     }
   658 
   659     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   660     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
   661 
   662     if (actual->levels() != given->levels()) {
   663         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
   664         return false;
   665     }
   666 
   667     unsigned level = 1;
   668     while (true) {
   669         if (actual->isFixedLength()) {
   670             if (kind == Coerce_Return || kind == Coerce_Assign) {
   671                 if (!given->isFixedLength()) {
   672                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   673                     return false;
   674                 }
   675 
   676                 if (actual->isCharArray()) {
   677                     // String assignment can have a truncated |given|.
   678                     if (given->fixedLength() > actual->fixedLength()) {
   679                         cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   680                         return false;
   681                     }
   682                 } else {
   683                     if (given->fixedLength() != actual->fixedLength()) {
   684                         cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   685                         return false;
   686                     }
   687                 }
   688             }
   689         } else if (given->isFixedLength()) {
   690             // We do not allow assignments in the form:
   691             //  [][] = [][Y]
   692             //
   693             // Otherwise, the following code could break the size guarantees
   694             // of the right-hand side:
   695             //
   696             //  new x[][5];
   697             //  new y[][];
   698             //  new z[3];
   699             //
   700             //
   701             //  y = x;
   702             //  y[0] = z;
   703             //
   704             // Now |x[0]| contains a 3-length array.
   705             if (level > 1) {
   706                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   707                 return false;
   708             }
   709         }
   710 
   711         if (!given->contained()->isArray() || !actual->contained()->isArray())
   712             break;
   713 
   714         given = ArrayType::cast(given->contained());
   715         actual = ArrayType::cast(actual->contained());
   716     }
   717 
   718     // These arrays must contain the same innermost type.
   719     if (given->contained() != actual->contained()) {
   720         cc_.reportError(pos, Message_TypeMismatch,
   721                         GetTypeName(actual->contained()),
   722                         GetTypeName(given->contained()));
   723         return false;
   724     }
   725 
   726     return true;
   727 }
   728 
   729 HIR *
   730 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
   731 {
   732     Handle<Type> from = hir->type();
   733 
   734     if (from->isInt32() && to->isFloat())
   735         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
   736     if (from->isInt32() && to->isBool())
   737         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
   738     
   739     if (to->isArray()) {
   740         if (!typeCheckArray(SourcePosition(), from, to, kind))
   741             return NULL;
   742         return hir;
   743     }
   744 
   745     assert(from == to);
   746     
   747     return hir;
   748 }
   749 
   750 void
   751 SemanticAnalysis::set(VariableSymbol *sym)
   752 {
   753     if (sym->scope()->kind() == Scope::GLOBAL) {
   754         __ setglobal(sym);
   755     } else {
   756         assert(sym->storage() == VariableSymbol::Local);
   757         __ setlocal(sym);
   758     }
   759 }
   760 
   761 HIR *
   762 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
   763 {
   764     Local<Type> coercion(zone_, coercionType(token, left, right));
   765     if (!coercion)
   766         return NULL;
   767     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
   768         return NULL;
   769     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
   770         return NULL;
   771     
   772     switch (token) {
   773      case TOK_PLUS:
   774       case TOK_MINUS:
   775       case TOK_STAR:
   776       case TOK_SLASH:
   777       case TOK_PERCENT:
   778       case TOK_AMPERSAND:
   779       case TOK_BITOR:
   780       case TOK_BITXOR:
   781       case TOK_SHR:
   782       case TOK_USHR:
   783       case TOK_SHL:
   784         return new (pool_) HBinary(node, left->type(), token, left, right);
   785 
   786       case TOK_EQUALS:
   787       case TOK_NOTEQUALS:
   788       case TOK_LT:
   789       case TOK_LE:
   790       case TOK_GT:
   791       case TOK_GE:
   792       case TOK_AND:
   793       case TOK_OR:
   794       {
   795         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   796         return new (pool_) HBinary(node, result, token, left, right);
   797       }
   798 
   799       default:
   800         assert(false);
   801         return NULL;
   802     }
   803 }
   804 
   805 static inline TokenKind
   806 ToCompare(Expression *expr)
   807 {
   808     if (expr->isBinaryExpression()) {
   809         BinaryExpression *b = expr->toBinaryExpression();
   810         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
   811             return b->token();
   812     } else if (expr->isUnaryExpression()) {
   813         UnaryExpression *u = expr->toUnaryExpression();
   814         if (u->token() == TOK_NOT)
   815             return TOK_NOT;
   816     }
   817     return TOK_EOF;
   818 }
   819 
   820 void
   821 SemanticAnalysis::visitForTest(Expression *expr,
   822                                Label *trueBranch,
   823                                Label *falseBranch,
   824                                Label *fallthrough)
   825 {
   826     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   827 
   828     TokenKind token = ToCompare(expr);
   829     if (token == TOK_EOF || token == TOK_NOT) {
   830         HIR *hir;
   831         if (token == TOK_EOF)
   832             hir = eval(expr);
   833         else
   834             hir = eval(expr->toUnaryExpression()->expression());
   835         if (!hir)
   836             return;
   837         if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
   838             return;
   839 
   840         discharge(hir);
   841 
   842         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
   843         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
   844         
   845         if (fallthrough == falseBranch)
   846             __ j(op, trueBranch);
   847         else
   848             __ j(op, falseBranch);
   849         return;
   850     }
   851 
   852     BinaryExpression *bin = expr->toBinaryExpression();
   853     if (token == TOK_AND || token == TOK_OR) {
   854         assert(false);
   855         //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
   856         return;
   857     }
   858 
   859     HIR *left = eval(bin->left());
   860     HIR *right = eval(bin->right());
   861     if (!left || !right)
   862         return;
   863 
   864     HIR *hir = binary(bin, bin->token(), left, right);
   865     if (!hir)
   866         return;
   867     if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
   868         return;
   869 
   870     discharge(hir);
   871     if (fallthrough == trueBranch)
   872         __ j(OP_JF, falseBranch);
   873     else
   874         __ j(OP_JT, trueBranch);
   875 }
   876 
   877 HLValue *
   878 SemanticAnalysis::lvalue(Expression *expr)
   879 {
   880     HIR *hir = eval(expr);
   881     if (!hir)
   882         return NULL;
   883     
   884     if (!hir->isLValue()) {
   885         cc_.reportError(expr->pos(), Message_ExpectedLValue);
   886         return NULL;
   887     }
   888 
   889     return static_cast<HLValue *>(hir);
   890 }
   891 
   892 HIR *
   893 SemanticAnalysis::eval(Expression *expr)
   894 {
   895     assert(!hir_);
   896     expr->accept(this);
   897 
   898     HIR *hir = hir_;
   899     hir_ = NULL;
   900 
   901     return hir;
   902 }
   903 
   904 void
   905 SemanticAnalysis::discharge(HIR *hir)
   906 {
   907     EmitHIR(zone_, emitter_, hir);
   908 }