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