src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Thu Dec 20 00:59:38 2012 -0800 (2012-12-20)
changeset 222 0cde1379b29f
parent 221 0c588a96837c
child 230 fb3cd08bc7fb
permissions -rw-r--r--
Re-added support for reference arguments.
     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             if (actual->isReference()) {
   520                 // If the actual is a reference, the coercion rules are much
   521                 // stricter; the contained types must be identical.
   522                 // :TODO: make this not an assert
   523                 assert(ReferenceType::cast(actual)->contained() == arg->type());
   524             } else {
   525                 // When we start overloading, coercion will have to happen later.
   526                 arg = coerce(arg, actual, Coerce_Arg);
   527                 if (!arg)
   528                     return;
   529             }
   530 
   531             mustComputeReference = actual->isReference() && !given->isReference();
   532         }
   533 
   534         if (mustComputeReference)
   535             arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
   536 
   537         if (!args->append(arg))
   538             return;
   539     }
   540 
   541     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   542 }
   543 
   544 void
   545 SemanticAnalysis::visitAssignment(Assignment *node)
   546 {
   547     HLValue *lval = lvalue(node->lvalue());
   548     if (!lval)
   549         return;
   550 
   551     HIR *hir = eval(node->expression());
   552     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   553         return;
   554 
   555     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   556 }
   557 
   558 void
   559 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   560 {
   561     if (!loop_) {
   562         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   563         return;
   564     }
   565 
   566     // Note, if we re-introduce LIFO allocs, we need to unwind here.
   567     __ jump(loop_->break_());
   568 }
   569 
   570 void
   571 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   572 {
   573     if (!loop_) {
   574         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   575         return;
   576     }
   577 
   578     // Note, if we re-introduce LIFO allocs, we need to unwind here.
   579     __ jump(loop_->continue_());
   580 }
   581 
   582 void
   583 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   584 {
   585     HIR *left = eval(node->left());
   586     if (!left)
   587         return;
   588 
   589     HIR *right = eval(node->right());
   590     if (!right)
   591         return;
   592 
   593     // Hrm... yes, for now, let's coerce here.
   594     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   595     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   596         return;
   597     
   598     // Do not coerce here, there's no reason to yet.
   599     if (!left->type()->isArray()) {
   600         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   601         return;
   602     }
   603 
   604     hir_ = new (pool_) HIndex(node,
   605                               ArrayType::cast(left->type())->contained(),
   606                               left,
   607                               right);
   608 }
   609 
   610 void
   611 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   612 {
   613     HLValue *lval = lvalue(node->expression());
   614     if (!lval)
   615         return;
   616 
   617     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   618         assert(false);
   619         return;
   620     }
   621 
   622     HIR *rval;
   623     if (lval->type()->isInt32())
   624         rval = new (pool_) HInteger(node, lval->type(), 1);
   625     else
   626         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   627 
   628     if (node->postfix())
   629         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   630     else
   631         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   632 }
   633 
   634 Type *
   635 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   636 {
   637     Handle<Type> l = left->type();
   638     Handle<Type> r = right->type();
   639 
   640     if (token >= TOK_PLUS && token <= TOK_SLASH) {
   641         // We allow: [float|int32] + [float|int32]
   642         if (l->isFloat() && r->isInt32())
   643             return l;
   644         if (l->isInt32() && r->isFloat())
   645             return r;
   646         if (l->isInt32() && r->isInt32())
   647             return l;
   648     }
   649 
   650     // :TODO: remove
   651     assert(l == r);
   652 
   653     return left->type();
   654 }
   655 
   656 bool
   657 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   658                                  Handle<Type> argGiven,
   659                                  Handle<Type> argActual,
   660                                  CoercionKind kind)
   661 {
   662     if (!argGiven->isArray()) {
   663         cc_.reportError(pos, Message_ExpectedArray);
   664         return false;
   665     }
   666 
   667     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   668     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
   669 
   670     if (actual->levels() != given->levels()) {
   671         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
   672         return false;
   673     }
   674 
   675     unsigned level = 1;
   676     while (true) {
   677         if (actual->isFixedLength()) {
   678             if (kind == Coerce_Return || kind == Coerce_Assign) {
   679                 if (!given->isFixedLength()) {
   680                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   681                     return false;
   682                 }
   683 
   684                 if (actual->isCharArray()) {
   685                     // String assignment can have a truncated |given|.
   686                     if (given->fixedLength() > actual->fixedLength()) {
   687                         cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   688                         return false;
   689                     }
   690                 } else {
   691                     if (given->fixedLength() != actual->fixedLength()) {
   692                         cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   693                         return false;
   694                     }
   695                 }
   696             }
   697         } else if (given->isFixedLength()) {
   698             // We do not allow assignments in the form:
   699             //  [][] = [][Y]
   700             //
   701             // Otherwise, the following code could break the size guarantees
   702             // of the right-hand side:
   703             //
   704             //  new x[][5];
   705             //  new y[][];
   706             //  new z[3];
   707             //
   708             //
   709             //  y = x;
   710             //  y[0] = z;
   711             //
   712             // Now |x[0]| contains a 3-length array.
   713             if (level > 1) {
   714                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   715                 return false;
   716             }
   717         }
   718 
   719         if (!given->contained()->isArray() || !actual->contained()->isArray())
   720             break;
   721 
   722         given = ArrayType::cast(given->contained());
   723         actual = ArrayType::cast(actual->contained());
   724     }
   725 
   726     // These arrays must contain the same innermost type.
   727     if (given->contained() != actual->contained()) {
   728         cc_.reportError(pos, Message_TypeMismatch,
   729                         GetTypeName(actual->contained()),
   730                         GetTypeName(given->contained()));
   731         return false;
   732     }
   733 
   734     return true;
   735 }
   736 
   737 HIR *
   738 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
   739 {
   740     Handle<Type> from = hir->type();
   741 
   742     if (from->isInt32() && to->isFloat())
   743         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
   744     if (from->isInt32() && to->isBool())
   745         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
   746     
   747     if (to->isArray()) {
   748         if (!typeCheckArray(SourcePosition(), from, to, kind))
   749             return NULL;
   750         return hir;
   751     }
   752     
   753     return hir;
   754 }
   755 
   756 void
   757 SemanticAnalysis::set(VariableSymbol *sym)
   758 {
   759     if (sym->scope()->kind() == Scope::GLOBAL) {
   760         __ setglobal(sym);
   761     } else {
   762         assert(sym->storage() == VariableSymbol::Local);
   763         __ setlocal(sym);
   764     }
   765 }
   766 
   767 HIR *
   768 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
   769 {
   770     Local<Type> coercion(zone_, coercionType(token, left, right));
   771     if (!coercion)
   772         return NULL;
   773     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
   774         return NULL;
   775     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
   776         return NULL;
   777     
   778     switch (token) {
   779      case TOK_PLUS:
   780       case TOK_MINUS:
   781       case TOK_STAR:
   782       case TOK_SLASH:
   783       case TOK_PERCENT:
   784       case TOK_AMPERSAND:
   785       case TOK_BITOR:
   786       case TOK_BITXOR:
   787       case TOK_SHR:
   788       case TOK_USHR:
   789       case TOK_SHL:
   790         return new (pool_) HBinary(node, left->type(), token, left, right);
   791 
   792       case TOK_EQUALS:
   793       case TOK_NOTEQUALS:
   794       case TOK_LT:
   795       case TOK_LE:
   796       case TOK_GT:
   797       case TOK_GE:
   798       case TOK_AND:
   799       case TOK_OR:
   800       {
   801         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   802         return new (pool_) HBinary(node, result, token, left, right);
   803       }
   804 
   805       default:
   806         assert(false);
   807         return NULL;
   808     }
   809 }
   810 
   811 static inline TokenKind
   812 ToCompare(Expression *expr)
   813 {
   814     if (expr->isBinaryExpression()) {
   815         BinaryExpression *b = expr->toBinaryExpression();
   816         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
   817             return b->token();
   818     } else if (expr->isUnaryExpression()) {
   819         UnaryExpression *u = expr->toUnaryExpression();
   820         if (u->token() == TOK_NOT)
   821             return TOK_NOT;
   822     }
   823     return TOK_EOF;
   824 }
   825 
   826 void
   827 SemanticAnalysis::visitForTest(Expression *expr,
   828                                Label *trueBranch,
   829                                Label *falseBranch,
   830                                Label *fallthrough)
   831 {
   832     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   833 
   834     TokenKind token = ToCompare(expr);
   835     if (token == TOK_EOF || token == TOK_NOT) {
   836         HIR *hir;
   837         if (token == TOK_EOF)
   838             hir = eval(expr);
   839         else
   840             hir = eval(expr->toUnaryExpression()->expression());
   841         if (!hir)
   842             return;
   843         if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
   844             return;
   845 
   846         discharge(hir);
   847 
   848         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
   849         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
   850         
   851         if (fallthrough == falseBranch)
   852             __ j(op, trueBranch);
   853         else
   854             __ j(op, falseBranch);
   855         return;
   856     }
   857 
   858     BinaryExpression *bin = expr->toBinaryExpression();
   859     if (token == TOK_AND || token == TOK_OR) {
   860         assert(false);
   861         //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
   862         return;
   863     }
   864 
   865     HIR *left = eval(bin->left());
   866     HIR *right = eval(bin->right());
   867     if (!left || !right)
   868         return;
   869 
   870     HIR *hir = binary(bin, bin->token(), left, right);
   871     if (!hir)
   872         return;
   873     if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
   874         return;
   875 
   876     discharge(hir);
   877     if (fallthrough == trueBranch)
   878         __ j(OP_JF, falseBranch);
   879     else
   880         __ j(OP_JT, trueBranch);
   881 }
   882 
   883 HLValue *
   884 SemanticAnalysis::lvalue(Expression *expr)
   885 {
   886     HIR *hir = eval(expr);
   887     if (!hir)
   888         return NULL;
   889     
   890     if (!hir->isLValue()) {
   891         cc_.reportError(expr->pos(), Message_ExpectedLValue);
   892         return NULL;
   893     }
   894 
   895     return static_cast<HLValue *>(hir);
   896 }
   897 
   898 HIR *
   899 SemanticAnalysis::eval(Expression *expr)
   900 {
   901     assert(!hir_);
   902     expr->accept(this);
   903 
   904     HIR *hir = hir_;
   905     hir_ = NULL;
   906 
   907     return hir;
   908 }
   909 
   910 void
   911 SemanticAnalysis::discharge(HIR *hir)
   912 {
   913     EmitHIR(zone_, emitter_, hir);
   914 }