src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Sat Jan 12 16:13:46 2013 -0800 (2013-01-12)
changeset 258 241d082d6d89
parent 256 3c184218462d
child 259 99ab8b19f0b9
permissions -rw-r--r--
Implement |from x import *| syntax for modules.
     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     loop_(NULL)
    68 {
    69 }
    70 
    71 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
    72   : zone_(parent->zone_),
    73     pool_(parent->pool_),
    74     cc_(parent->cc_),
    75     unit_(parent->unit_),
    76     hir_(NULL),
    77     scope_(parent->scope_),
    78     emitter_(pool_),
    79     fun_(fun),
    80     loop_(NULL),
    81     control_(NULL)
    82 {
    83 
    84 }
    85 
    86 void
    87 SemanticAnalysis::analyze()
    88 {
    89     scope_ = unit_->globalScope();
    90 
    91     for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
    92         Statement *stmt = unit_->tree()->statements()->at(i);
    93         stmt->accept(this);
    94     }
    95 
    96     Local<Code> code(zone_, __ finish());
    97     if (!code)
    98         return;
    99     code->setModule(unit_->module());
   100     unit_->module()->setCode(code);
   101 
   102 #ifndef NDEBUG
   103 //    Disassemble(code, stdout);
   104 #endif
   105 }
   106 
   107 void
   108 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
   109 {
   110     FunctionSymbol *sym = stmt->sym();
   111     Local<FunctionType> type(zone_, sym->type());
   112 
   113     assert(scope_->kind() == Scope::GLOBAL);
   114 
   115     if (stmt->token() == TOK_NATIVE) {
   116         // Define the native now.
   117         size_t index;
   118         if (!zone_->nativeTable()->add(stmt->name(), &index))
   119             return;
   120 
   121         Local<Native> native(zone_, Native::New(zone_, type, index));
   122         if (!native)
   123             return;
   124 
   125         __ object(native);
   126         __ setglobal(sym);
   127         __ pop();
   128     }
   129 
   130     // If the function is a forward or native, we don't have to do anything.
   131     if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
   132         return;
   133 
   134     SemanticAnalysis child(this, type);
   135     Local<Function> funobj(zone_, child.compile(stmt));
   136     if (!funobj)
   137         return;
   138 
   139     __ object(funobj);
   140     __ setglobal(sym);
   141     if (stmt->token() == TOK_PUBLIC)
   142         __ public_();
   143     else
   144         __ pop();
   145 }
   146 
   147 Function *
   148 SemanticAnalysis::compile(FunctionStatement *stmt)
   149 {
   150     __ setFirstLine(stmt->pos().line);
   151 
   152     AutoEnterScope argScope(&scope_, stmt->argScope());
   153 
   154     for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
   155         Parameter *param = stmt->signature().parameters()->at(i);
   156         param->sym()->allocate(VariableSymbol::Arg, i);
   157     }
   158 
   159     AutoEnterScope varScope(&scope_, stmt->varScope());
   160     ControlStatus status = visitForControl(stmt->body());
   161 
   162     if (!fun_->returnType()->isVoid()) {
   163         // If the function is not void, report if not all paths return a value.
   164         // All other incorrect return cases have been caught already.
   165         if (status.returns() == Returns_Sometimes) {
   166             cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
   167             return NULL;
   168         }
   169 
   170         if (status.returns() == Returns_Never) {
   171             cc_.reportError(stmt->pos(), Message_MissingReturnValue);
   172             return NULL;
   173         }
   174     }
   175 
   176     Local<Code> code(zone_, __ finish());
   177     if (!code)
   178         return NULL;
   179     code->setModule(unit_->module());
   180 
   181     Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
   182     if (!fun)
   183         return NULL;
   184 
   185 #ifndef NDEBUG
   186 //    Disassemble(code, stdout);
   187 #endif
   188 
   189     return fun;
   190 }
   191 
   192 void 
   193 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
   194 {
   195     AutoEnterScope scope(&scope_, node->scope());
   196 
   197     for (size_t i = 0; i < node->statements()->length(); i++) {
   198         Statement *stmt = node->statements()->at(i);
   199         __ note_position(stmt->pos());
   200         stmt->accept(this);
   201         assert(__ stackDepth() == 0);
   202     }
   203 }
   204 
   205 void
   206 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
   207 {
   208 }
   209 
   210 void
   211 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
   212 {
   213     // While building HIR, we enter new pool and root scopes, since HIR
   214     // creation is purely temporary.
   215     PoolScope poolScope(zone_->pool());
   216     RootScope rootScope(zone_);
   217 
   218     HIR *hir = eval(node->expression());
   219     if (!hir)
   220         return;
   221 
   222     discharge(hir);
   223     if (!hir->type()->isVoid())
   224         __ pop();
   225 }
   226 
   227 void
   228 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
   229 {
   230     // If both sides terminate in a return, we consider this a return as well.
   231     if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
   232         terminate(Returns_Always);
   233         return;
   234     }
   235 
   236     ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
   237                           ? Returns_Never
   238                           : Returns_Sometimes;
   239 
   240     if (left.terminates() && right.terminates())
   241         terminate(status);
   242     else
   243         returns(status);
   244 }
   245 
   246 SemanticAnalysis::ControlStatus
   247 SemanticAnalysis::visitForControl(Statement *statement)
   248 {
   249     ControlScope scope(&control_);
   250     statement->accept(this);
   251     return scope.status();
   252 }
   253 
   254 void
   255 SemanticAnalysis::visitIfStatement(IfStatement *node)
   256 {
   257     Label join;
   258 
   259     ControlStatus trueBranch;
   260     ControlStatus falseBranch(false, Returns_Never);
   261 
   262     if (!node->ifFalse()) {
   263         Label success;
   264 
   265         visitForTest(node->condition(), &success, &join, &success);
   266         __ bind(&success);
   267         trueBranch = visitForControl(node->ifTrue());
   268     } else {
   269         Label success, next;
   270 
   271         visitForTest(node->condition(), &success, &next, &success);
   272         __ bind(&success);
   273         trueBranch = visitForControl(node->ifTrue());
   274         __ jump(&join);
   275         __ bind(&next);
   276         falseBranch = visitForControl(node->ifFalse());
   277     }
   278 
   279     __ bind(&join);
   280 
   281     control_->merge(trueBranch, falseBranch);
   282 }
   283 
   284 void
   285 SemanticAnalysis::requireLifoStack()
   286 {
   287     if (!loop_)
   288         return;
   289 
   290     loop_->setUsesLifoStack();
   291 }
   292 
   293 SemanticAnalysis::ControlStatus
   294 SemanticAnalysis::visitLoopBody(Statement *stmt)
   295 {
   296     // We always mark off a loop body, so on each edge, we can balance the
   297     // LIFO stack. Right now, we don't have the ability to budget the LIFO
   298     // stack ahead of time. If we turn out to never need the LIFO stack, we
   299     // mark it as unnecessary. (The interpreter can't really make use of this,
   300     // but the JIT can).
   301     //
   302     // Note that balancing the LIFO stack isn't even necessary, so this
   303     // feature may be removed. All this mechanism does is mitigate the
   304     // possibility that a long-running loop will overflow the LIFO region
   305     // and therefore start requiring nursery allocations.
   306     int pos = __ enterloop();
   307     ControlStatus status = visitForControl(stmt);
   308     __ leaveloop();
   309 
   310     if (loop_->usesLifoStack())
   311         __ setLoopUsesLifoStack(pos);
   312 
   313     return status;
   314 }
   315 
   316 void
   317 SemanticAnalysis::visitForStatement(ForStatement *node)
   318 {
   319     AutoEnterScope scope(&scope_, node->scope());
   320     PoolScope poolScope(zone_->pool());
   321     RootScope rootScope(zone_);
   322 
   323     Label join, update;
   324     LoopScope loop(scope_, &join, &update, &loop_);
   325 
   326     if (node->initialization())
   327         node->initialization()->accept(this);
   328 
   329     Label header, test;
   330     if (node->condition())
   331         __ jump(&test);
   332 
   333     __ bind(&header);
   334     ControlStatus status = visitLoopBody(node->body());
   335 
   336     __ bind(&update);
   337     if (node->update())
   338         node->update()->accept(this);
   339 
   340     if (node->condition()) {
   341         __ bind(&test);
   342         visitForTest(node->condition(), &header, &join, &join);
   343     } else {
   344         __ jump(&header);
   345     }
   346 
   347     __ bind(&join);
   348     
   349     // If there was a condition, we treat this like a while loop. Otherwise,
   350     // the join point is only reachable if the loop contains a break. The
   351     // termination status doesn't tell us anything yet.
   352     if (node->condition() || loop.breaks())
   353         control_->merge(status, ControlStatus(false, Returns_Never));
   354     else
   355         control_->terminate(status.returns());
   356 
   357     assert(__ stackDepth() == 0);
   358 }
   359 
   360 void
   361 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
   362 {
   363     PoolScope poolScope(zone_->pool());
   364     RootScope rootScope(zone_);
   365 
   366     Label header, join;
   367 
   368     __ bind(&header);
   369 
   370     ControlStatus status;
   371 
   372     LoopScope loop(scope_, &join, &header, &loop_);
   373     if (node->token() == TOK_WHILE) {
   374         Label body;
   375         visitForTest(node->condition(), &body, &join, &body);
   376         status = visitLoopBody(node->body());
   377         __ jump(&header);
   378     } else {
   379         status = visitLoopBody(node->body());
   380         visitForTest(node->condition(), &header, &join, &join);
   381     }
   382 
   383     __ bind(&join);
   384 
   385     // Detect loops that will always have a fork in the contro-flow graph.
   386     // This will be a |while| loop, or a |do-while| loop whose body does
   387     // not terminate. For now, we treat these as an |if| regardless of the
   388     // direction the branch can take. That means the control-flow is always
   389     // conditional.
   390     if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
   391         control_->merge(status, ControlStatus(false, Returns_Never));
   392     } else {
   393         // At this point, we've got a do-while loop with a |return| or
   394         // |continue|, meaning that the rest of the block is unreachable.
   395         control_->terminate(status.returns());
   396     }
   397 
   398     assert(__ stackDepth() == 0);
   399 }
   400 
   401 static inline Heap::Tenure
   402 InferTenure(Symbol *sym)
   403 {
   404     if (sym->scope()->kind() == Scope::GLOBAL)
   405         return Heap::Tenure_Old;
   406 
   407     // SP2's array semantics allow any array kind to escape, so we must use
   408     // the normal heap. (Hopefully escape analysis can ease this pain later).
   409     if (sym->type()->isArray())
   410         return Heap::Tenure_Default;
   411 
   412     return Heap::Tenure_Default;
   413 }
   414 
   415 void
   416 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   417 {
   418     PoolScope poolScope(zone_->pool());
   419     RootScope rootScope(zone_);
   420 
   421     Local<Type> type(zone_, node->sym()->type());
   422 
   423     if (node->sym()->type()->isVoid()) {
   424         cc_.reportError(node->type()->pos(), Message_CannotDeclareVoid);
   425         return;
   426     }
   427 
   428     if (node->initialization()) {
   429         HIR *hir = NULL;
   430 
   431         if ((hir = eval(node->initialization())) == NULL)
   432             return;
   433         if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
   434             return;
   435 
   436         discharge(hir);
   437     } else {
   438         if (type->isInt32() || type->isEnum() ||
   439             type->isChar() || type->isBool())
   440         {
   441             __ int_(0);
   442         } else if (type->isFloat()) {
   443             __ float_(0);
   444         } else if (type->isArray()) {
   445             Local<ArrayType> atype(zone_, ArrayType::cast(type));
   446             Local<ArrayMap> map(zone_, atype->newMap());
   447             if (!map)
   448                 return;
   449 
   450             if (atype->isFixedLength()) {
   451                 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
   452             } else if (node->dims()->at(0)) {
   453                 // This may not be true if we allow typedefing, so :TODO:
   454                 // figure out proper semantics.
   455                 assert(node->dims()->length() == atype->levels());
   456 
   457                 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   458                 for (size_t i = 0; i < node->dims()->length(); i++) {
   459                     Expression *expr = node->dims()->at(i);
   460                     if (expr) {
   461                         HIR *hir = eval(expr);
   462                         if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
   463                             return;
   464                         discharge(hir);
   465                     } else {
   466                         __ int_(0);
   467                     }
   468                 }
   469                 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
   470             } else {
   471                 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
   472             }
   473         } else {
   474             assert(false);
   475         }
   476     }
   477 
   478     if (node->sym()->scope()->kind() != Scope::GLOBAL) {
   479         if (!__ allocate(node->sym()))
   480             return;
   481     }
   482 
   483     set(node->sym());
   484     __ pop();
   485 }
   486 
   487 void
   488 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   489 {
   490     control_->returns(Returns_Always);
   491 
   492     if (!node->expression()) {
   493         if (!fun_->returnType()->isVoid()) {
   494             cc_.reportError(node->pos(), Message_MissingReturnValue);
   495             return;
   496         }
   497 
   498         __ returnvoid();
   499         return;
   500     }
   501 
   502     if (fun_->returnType()->isVoid()) {
   503         cc_.reportError(node->pos(), Message_UsedVoidReturn);
   504         return;
   505     }
   506 
   507     PoolScope poolScope(zone_->pool());
   508     RootScope rootScope(zone_);
   509 
   510     HIR *hir = eval(node->expression());
   511     if (!hir)
   512         return;
   513 
   514     Local<Type> returnType(zone_, fun_->returnType());
   515     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   516         return;
   517 
   518     discharge(hir);
   519 
   520     if (hir->type()->isVoid())
   521         __ returnvoid();
   522     else
   523         __ return_();
   524 }
   525 
   526 void
   527 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   528 {
   529     HIR *left = eval(node->left());
   530     HIR *right = eval(node->right());
   531     if (!left || !right)
   532         return;
   533 
   534     hir_ = binary(node, node->token(), left, right);
   535 }
   536 
   537 bool
   538 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   539 {
   540     if (type->parameters()->length() == actual)
   541         return true;
   542 
   543     if (actual > type->parameters()->length()) {
   544         if (!type->isNative() || !type->isNativeVariadic())
   545             return false;
   546         return true;
   547     }
   548 
   549     if (!type->defaults())
   550         return false;
   551 
   552     // Missing arguments. See if there's a default argument for each missing
   553     // actual.
   554     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   555         if (!type->defaults()->at(i))
   556             return false;
   557     }
   558 
   559     return true;
   560 }
   561 
   562 static unsigned
   563 BindImplicitName(Module *from, ImplicitSymbol *sym)
   564 {
   565     if (sym->bound())
   566         return sym->fieldIndex();
   567 
   568     Module *module = Module::cast(from->getImportAt(sym->index()));
   569     StructMap *map = module->globals()->map();
   570 
   571     unsigned fieldIndex;
   572     Descriptor *desc = map->type()->lookupField(sym->name(), &fieldIndex);
   573     assert(desc && desc->type() == sym->type());
   574 
   575     sym->bind(fieldIndex);
   576     return fieldIndex;
   577 }
   578 
   579 void
   580 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   581 {
   582     Symbol *sym = proxy->sym();
   583 
   584     switch (sym->kind()) {
   585       case Symbol::kImport:
   586       {
   587         ImportSymbol *import = sym->toImport();
   588         hir_ = new (pool_) HImport(proxy, sym->type(), import->index());
   589         break;
   590       }
   591 
   592       case Symbol::kImplicit:
   593       {
   594         ImplicitSymbol *import = sym->toImplicit();
   595         unsigned fieldIndex = BindImplicitName(unit_->module(), import);
   596 
   597         hir_ = new (pool_) HImport(proxy, zone_->types()->getImportable(), import->index());
   598         hir_ = new (pool_) HField(proxy, hir_, sym->type(), fieldIndex);
   599         break;
   600       }
   601 
   602       case Symbol::kConstant:
   603       {
   604         ConstantSymbol *val = sym->toConstant();
   605         hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
   606         break;
   607       }
   608       
   609       // This is kind of screwy. Symbol::kFunction is like a constant we can't
   610       // evaluate yet. Maybe we should extract the GLOBAL case and say that
   611       // kFunction is only used for global functions (and use const vars for
   612       // local functions).
   613       case Symbol::kFunction:
   614       case Symbol::kVariable:
   615       {
   616         Scope *in = sym->scope();
   617         switch (in->kind()) {
   618           case Scope::GLOBAL:
   619             hir_ = new (pool_) HGlobal(proxy, sym);
   620             break;
   621 
   622           case Scope::FUNCTION:
   623           {
   624             VariableSymbol *var = sym->toVariable();
   625             assert(var->storage() == VariableSymbol::Arg);
   626             hir_ = new (pool_) HLocal(proxy, var);
   627             break;
   628           }
   629 
   630           default:
   631           {
   632             VariableSymbol *var = sym->toVariable();
   633             assert(in->kind() == Scope::BLOCK);
   634             assert(var->storage() == VariableSymbol::Local);
   635             hir_ = new (pool_) HLocal(proxy, var);
   636             break;
   637           }
   638         }
   639         break;
   640       }
   641 
   642       default:
   643         // :TODO:
   644         assert(false);
   645     }
   646 }
   647 
   648 void
   649 SemanticAnalysis::visitBooleanLiteral(BooleanLiteral *node)
   650 {
   651     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   652     hir_ = new (pool_) HBoolean(node, type, node->token() == TOK_TRUE);
   653 }
   654 
   655 void
   656 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   657 {
   658     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   659     hir_ = new (pool_) HInteger(lit, type, lit->value());
   660 }
   661 
   662 void
   663 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   664 {
   665     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   666     hir_ = new (pool_) HFloat(node, type, (float)node->value());
   667 }
   668 
   669 void
   670 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
   671 {
   672     Type *type = zone_->types()->getString();
   673     hir_ = new (pool_) HString(node, type, node->string());
   674 }
   675 
   676 void
   677 SemanticAnalysis::visitCallExpression(CallExpression *node)
   678 {
   679     HIR *callee = eval(node->callee());
   680     if (!callee)
   681         return;
   682 
   683     if (!callee->type()->isFunction()) {
   684         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   685         return;
   686     }
   687 
   688     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   689     
   690     if (!checkArgumentCount(fun, node->arguments()->length())) {
   691         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   692         return;
   693     }
   694 
   695     if (fun->isForward()) {
   696         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   697         return;
   698     }
   699 
   700     HIRList *args = new (pool_) HIRList;
   701     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   702         Expression *expression = node->arguments()->at(i);
   703         HIR *arg = eval(expression);
   704         if (!arg)
   705             return;
   706 
   707         Handle<Type> given = arg->type();
   708         
   709         bool mustComputeReference;
   710         if (i >= fun->parameters()->length()) {
   711             // Special handling for natives. Arguments past the formal must
   712             // always have references computed. However, arrays are already
   713             // references for natives.
   714             assert(fun->isNative() && fun->isNativeVariadic());
   715             mustComputeReference = !given->isReference() &&
   716                                    !given->isArray();
   717         } else {
   718             Local<Type> actual(zone_, fun->parameterAt(i));
   719 
   720 
   721             if (expression->isIndexExpression() && arg->isIndex()) {
   722                 // If the expression is the form x[y], and this produced a
   723                 // normal array indexing operation, then we apply some 
   724                 // special rules.
   725 
   726                 if (actual->isReference()) {
   727                     // Disabled, since this doesn't have easily definable or
   728                     // sensible semantics with SP2 arrays, but we don't want
   729                     // to silently break SP1 semantics.
   730                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   731                     return;
   732                 }
   733 
   734                 // As a special rule to account for SP1 semantics, we allow x[y]
   735                 // to automatically compute a sliced, read-only array view if
   736                 // the desired type is an array of one more dimension than x[y]
   737                 // would return.
   738                 //
   739                 // As an additional restriction, this is only allowed for
   740                 // one-level char arrays, to minimize potential issues until
   741                 // we determine whether more compatibility is needed.
   742                 //
   743                 // Internally, for sanity, the dependent array operation does
   744                 // not necessarily create a dependent array. For extensible
   745                 // arrays, we instead create a duplicate arrary of just the
   746                 // sliced portion, rather than deal with the complexity of the
   747                 // source array being resized.
   748                 //
   749                 // Note that we don't really know whether a dependent array
   750                 // will be dependent at compile-time, so the dependent type's
   751                 // just inherits from the source.
   752                 if (actual->isArray()) {
   753                     HIndex *index = arg->toIndex();
   754                     Local<ArrayType> basetype(zone_, ArrayType::cast(index->base()->type()));
   755                     Local<ArrayType> atype(zone_, ArrayType::cast(actual));
   756 
   757                     if (atype->isCharArray() && basetype->isCharArray()) {
   758                         // There is no possible way this will type check, so
   759                         // it's safe to just try something completely
   760                         // different.
   761                         Local<Type> slicetype(zone_);
   762                         if (basetype->isFixedLength()) {
   763                             // If the base type is fixed length, we need to
   764                             // compute a new dynamic array type based on the
   765                             // fixed array's contents and qualifiers.
   766                             Local<Type> contained(zone_, basetype->contained());
   767                             slicetype = zone_->types()->newArray(contained, ArrayType::DYNAMIC_ARRAY_SIZE);
   768                             if (!slicetype)
   769                                 return;
   770                             slicetype = zone_->types()->qualify(slicetype, basetype->quals());
   771                             if (!slicetype)
   772                                 return;
   773                         } else {
   774                             slicetype = basetype;
   775                         }
   776                         arg = new (pool_) HNewDependentArray(expression, slicetype, index->base(), index->index());
   777                         given = arg->type();
   778                     }
   779                 }
   780             }
   781 
   782             if (actual->isReference()) {
   783                 // If the actual is a reference, the coercion rules are much
   784                 // stricter; the contained types must be identical.
   785                 // :TODO: make this not an assert
   786                 assert(ReferenceType::cast(actual)->contained() == arg->type());
   787             } else {
   788                 // When we start overloading, coercion will have to happen later.
   789                 arg = coerce(arg, actual, Coerce_Arg);
   790                 if (!arg)
   791                     return;
   792             }
   793 
   794             mustComputeReference = actual->isReference() && !given->isReference();
   795         }
   796 
   797         if (mustComputeReference) {
   798             // Refs always use the LIFO stack if they can.
   799             arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
   800             requireLifoStack();
   801         }
   802 
   803         if (!args->append(arg))
   804             return;
   805     }
   806 
   807     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   808 }
   809 
   810 void
   811 SemanticAnalysis::visitAssignment(Assignment *node)
   812 {
   813     HLValue *lval = lvalue(node->lvalue());
   814     if (!lval)
   815         return;
   816 
   817     if (lval->type()->quals() & TypeQual_Const) {
   818         cc_.reportError(node->pos(), Message_CannotModifyConst);
   819         return;
   820     }
   821 
   822     HIR *hir = eval(node->expression());
   823     if (!hir)
   824         return;
   825     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   826         return;
   827 
   828     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   829 }
   830 
   831 void
   832 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   833 {
   834     if (!loop_) {
   835         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   836         return;
   837     }
   838 
   839     loop_->setBreaks();
   840     __ j(OP_BREAK, loop_->break_());
   841 }
   842 
   843 void
   844 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   845 {
   846     if (!loop_) {
   847         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   848         return;
   849     }
   850 
   851     __ j(OP_CONTINUE, loop_->continue_());
   852 }
   853 
   854 void
   855 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   856 {
   857     HIR *left = eval(node->left());
   858     if (!left)
   859         return;
   860 
   861     HIR *right = eval(node->right());
   862     if (!right)
   863         return;
   864 
   865     // Hrm... yes, for now, let's coerce here.
   866     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   867     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   868         return;
   869     
   870     // Do not coerce here, there's no reason to yet.
   871     if (!left->type()->isArray()) {
   872         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   873         return;
   874     }
   875 
   876     hir_ = new (pool_) HIndex(node,
   877                               ArrayType::cast(left->type())->contained(),
   878                               left,
   879                               right);
   880 }
   881 
   882 void
   883 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   884 {
   885     HLValue *lval = lvalue(node->expression());
   886     if (!lval)
   887         return;
   888 
   889     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   890         assert(false);
   891         return;
   892     }
   893 
   894     HIR *rval;
   895     if (lval->type()->isInt32())
   896         rval = new (pool_) HInteger(node, lval->type(), 1);
   897     else
   898         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   899 
   900     if (node->postfix())
   901         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   902     else
   903         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   904 }
   905 
   906 Type *
   907 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   908 {
   909     Local<Type> l(zone_, left->type());
   910     Local<Type> r(zone_, right->type());
   911 
   912     if (l->isPod())
   913         l = l->unqualified();
   914     if (r->isPod())
   915         r = r->unqualified();
   916 
   917     if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
   918         (token >= TOK_EQUALS && token <= TOK_GE))
   919     {
   920         // We allow: [float|int32] + [float|int32]
   921         if (l->isFloat() && r->isInt32())
   922             return l;
   923         if (l->isInt32() && r->isFloat())
   924             return r;
   925         if (l->isInt32() && r->isInt32())
   926             return l;
   927 
   928         if (l->isChar() && r->isInt32())
   929              return r;
   930         if (l->isInt32() && r->isChar())
   931             return l;
   932     }
   933 
   934     // :TODO: remove
   935     assert(*l == *r);
   936 
   937     return left->type();
   938 }
   939 
   940 HIR *
   941 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   942                                  HIR *from,
   943                                  Handle<ArrayType> argActual,
   944                                  CoercionKind kind)
   945 {
   946     Local<Type> argGiven(zone_, from->type());
   947 
   948     // Special case: if we receive a string literal, and this is a char array,
   949     // we allow a coercion.
   950     if (from->isString() &&
   951         argGiven->isString() &&
   952         argActual->isArray() &&
   953         ArrayType::cast(argActual)->isCharArray())
   954     {
   955         HString *hir = from->toString();
   956         Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   957 
   958         if (actual->isFixedLength()) {
   959             if (hir->string()->length() + 1 > actual->fixedLength()) {
   960                 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   961                 return NULL;
   962             }
   963         }
   964 
   965         // Transform the string literal into an array literal. We give it the
   966         // type of the left-hand side. The constness of the destination type
   967         // will determine whether HArray duplicates it or not.
   968         Local<ArrayMap> map(zone_, actual->newMap());
   969         if (!map)
   970             return NULL;
   971 
   972         Local<Array> array(zone_);
   973         array = Array::NewString(zone_,
   974                                  map,
   975                                  hir->string()->chars(),
   976                                  hir->string()->length(),
   977                                  Heap::Tenure_Old);
   978         if (!array)
   979             return NULL;
   980 
   981         // Since we're creating a canonical copy of the char array, we have to
   982         // be careful that it doesn't get mutated. There are two cases where
   983         // we know it can't be mutated, and therefore don't need to specify
   984         // that it be cloned after pushing it onto the stack.
   985         //
   986         //  (1) The array type is const.
   987         //  (2) The array type is fixed-length, and the coercion is for
   988         //      assignment, meaning it will be immediately copied.
   989         //
   990         // We treat declaration separately from assignment, since for
   991         // declaration we can just immediately use the cloned version.
   992         bool shouldDuplicate = true;
   993         if ((actual->quals() & TypeQual_Const) ||
   994             (actual->isFixedLength() && kind == Coerce_Assign))
   995         {
   996             shouldDuplicate = false;
   997         }
   998 
   999         return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
  1000     }
  1001 
  1002     if (!argGiven->isArray()) {
  1003         cc_.reportError(pos, Message_ExpectedArray);
  1004         return NULL;
  1005     }
  1006 
  1007     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
  1008     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
  1009 
  1010     if (actual->levels() != given->levels()) {
  1011         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
  1012         return NULL;
  1013     }
  1014 
  1015     unsigned level = 1;
  1016     while (true) {
  1017         if (actual->isFixedLength()) {
  1018             if (!given->isFixedLength()) {
  1019                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1020                 return NULL;
  1021             }
  1022 
  1023             if (actual->isCharArray()) {
  1024                 // String assignment can have a truncated |given|.
  1025                 if (given->fixedLength() > actual->fixedLength()) {
  1026                     cc_.reportError(pos, Message_ArrayAssignmentTooBig);
  1027                     return NULL;
  1028                 }
  1029             } else {
  1030                 if (given->fixedLength() != actual->fixedLength()) {
  1031                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1032                     return NULL;
  1033                 }
  1034             }
  1035         } else if (given->isFixedLength()) {
  1036             // We do not allow assignments in the form:
  1037             //  [][] = [][Y]
  1038             //
  1039             // Otherwise, the following code could break the size guarantees
  1040             // of the right-hand side:
  1041             //
  1042             //  new x[][5];
  1043             //  new y[][];
  1044             //  new z[3];
  1045             //
  1046             //
  1047             //  y = x;
  1048             //  y[0] = z;
  1049             //
  1050             // Now |x[0]| contains a 3-length array.
  1051             if (level > 1) {
  1052                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1053                 return NULL;
  1054             }
  1055         }
  1056 
  1057         if (!given->contained()->isArray() || !actual->contained()->isArray())
  1058             break;
  1059 
  1060         given = ArrayType::cast(given->contained());
  1061         actual = ArrayType::cast(actual->contained());
  1062     }
  1063 
  1064     bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
  1065     bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
  1066 
  1067     // These arrays must contain the same innermost type.
  1068     if (given->contained()->unqualified() != actual->contained()->unqualified() ||
  1069         (givenConst && !actualConst))
  1070     {
  1071         char aname[255];
  1072         char gname[255];
  1073         cc_.reportError(pos, Message_TypeMismatch,
  1074                         GetTypeName(argActual, aname, sizeof(aname)),
  1075                         GetTypeName(argGiven, gname, sizeof(gname)));
  1076         return NULL;
  1077     }
  1078 
  1079     return from;
  1080 }
  1081 
  1082 HIR *
  1083 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
  1084 {
  1085     char fname[255];
  1086     char tname[255];
  1087     cc_.reportError(pos, Message_InvalidCoercion,
  1088                     GetTypeName(from, fname, sizeof(fname)),
  1089                     GetTypeName(to, tname, sizeof(tname)));
  1090     return NULL;
  1091 }
  1092 
  1093 HIR *
  1094 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
  1095 {
  1096     Local<Type> from(zone_, hir->type());
  1097 
  1098     // If the source is *ever* an importable, we just fail.
  1099     if (from->isImportable())
  1100         return typeFailure(hir->node()->pos(), from, to);
  1101 
  1102     if (from->isInt32() && to->isFloat())
  1103         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
  1104     if (from->isInt32() && to->isBool())
  1105         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
  1106 
  1107     if (to->isEnum() && *from != to)
  1108         return typeFailure(hir->node()->pos(), from, to);
  1109     
  1110     if (to->isArray()) {
  1111         Local<ArrayType> atype(zone_, ArrayType::cast(to));
  1112         return typeCheckArray(hir->node()->pos(), hir, atype, kind);
  1113     }
  1114     
  1115     return hir;
  1116 }
  1117 
  1118 void
  1119 SemanticAnalysis::set(VariableSymbol *sym)
  1120 {
  1121     if (sym->scope()->kind() == Scope::GLOBAL) {
  1122         __ setglobal(sym);
  1123     } else {
  1124         assert(sym->storage() == VariableSymbol::Local);
  1125         __ setlocal(sym);
  1126     }
  1127 }
  1128 
  1129 HIR *
  1130 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
  1131 {
  1132     Local<Type> coercion(zone_, coercionType(token, left, right));
  1133     if (!coercion)
  1134         return NULL;
  1135     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
  1136         return NULL;
  1137     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
  1138         return NULL;
  1139     
  1140     switch (token) {
  1141      case TOK_PLUS:
  1142       case TOK_MINUS:
  1143       case TOK_STAR:
  1144       case TOK_SLASH:
  1145       case TOK_PERCENT:
  1146       case TOK_AMPERSAND:
  1147       case TOK_BITOR:
  1148       case TOK_BITXOR:
  1149       case TOK_SHR:
  1150       case TOK_USHR:
  1151       case TOK_SHL:
  1152         return new (pool_) HBinary(node, left->type(), token, left, right);
  1153 
  1154       case TOK_EQUALS:
  1155       case TOK_NOTEQUALS:
  1156       case TOK_LT:
  1157       case TOK_LE:
  1158       case TOK_GT:
  1159       case TOK_GE:
  1160       case TOK_AND:
  1161       case TOK_OR:
  1162       {
  1163         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1164         return new (pool_) HBinary(node, result, token, left, right);
  1165       }
  1166 
  1167       default:
  1168         assert(false);
  1169         return NULL;
  1170     }
  1171 }
  1172 
  1173 static inline bool
  1174 IsValidUncheckedType(Type *type)
  1175 {
  1176     return type->isEnum() ||
  1177            type->isFloat() ||
  1178            type->isInt32() ||
  1179            type->isChar() ||
  1180            type->isUnchecked() ||
  1181            type->isBool();
  1182 }
  1183 
  1184 void
  1185 SemanticAnalysis::visitUnaryExpression(UnaryExpression *node)
  1186 {
  1187     HIR *hir = eval(node->expression());
  1188     if (!hir)
  1189         return;
  1190 
  1191     switch (node->token()) {
  1192       case TOK_TILDE:
  1193       {
  1194         if (!hir->type()->isInt32() && !hir->type()->isEnum()) {
  1195             char name[255];
  1196             cc_.reportError(node->pos(), Message_InvalidUnaryType,
  1197                             "~",
  1198                             GetTypeName(hir->type(), name, sizeof(name)));
  1199         }
  1200         Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
  1201         hir_ = new (pool_) HUnary(node, hir->type(), TOK_TILDE, hir);
  1202         return;
  1203       }
  1204 
  1205       case TOK_MINUS:
  1206       {
  1207         if (hir->type()->isInt32() || hir->type()->isEnum()) {
  1208             Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
  1209             hir_ = new (pool_) HUnary(node, type, TOK_MINUS, hir);
  1210             return;
  1211         }
  1212         if (hir->type()->isFloat()) {
  1213             hir_ = new (pool_) HUnary(node, hir->type(), TOK_MINUS, hir);
  1214             return;
  1215         }
  1216 
  1217         char name[255];
  1218         cc_.reportError(node->pos(), Message_InvalidUnaryType,
  1219                         "-",
  1220                         GetTypeName(hir->type(), name, sizeof(name)));
  1221         break;
  1222       }
  1223 
  1224       default:
  1225       {
  1226         assert(node->token() == TOK_LABEL);
  1227 
  1228         TypeSymbol *sym = node->tag()->sym()->asType();
  1229         if (!sym) {
  1230             cc_.reportError(node->pos(), Message_IdentifierIsNotAType,
  1231                             sym->name()->chars());
  1232             return;
  1233         }
  1234 
  1235         if (!IsValidUncheckedType(sym->type())) {
  1236             char name[255];
  1237             cc_.reportError(node->pos(), Message_InvalidUncheckedCastTo,
  1238                             GetTypeName(hir->type(), name, sizeof(name)));
  1239             return;
  1240         }
  1241         if (!IsValidUncheckedType(hir->type())) {
  1242             char name[255];
  1243             cc_.reportError(node->pos(), Message_InvalidUncheckedCastFrom,
  1244                             GetTypeName(hir->type(), name, sizeof(name)));
  1245             return;
  1246         }
  1247 
  1248         hir_ = new (pool_) HUnary(node, hir->type(), TOK_LABEL, hir);
  1249         break;
  1250       }
  1251     }
  1252 }
  1253 
  1254 void
  1255 SemanticAnalysis::import(HIR *hir, FieldExpression *node)
  1256 {
  1257     // Note that we don't care if the hir type is "importable", since we
  1258     // can only do anything if the important has a constant binding.
  1259     unsigned index = hir->toImport()->index();
  1260     Local<Importable> importable(zone_, unit_->module()->getImportAt(index));
  1261 
  1262     if (importable->isPackage()) {
  1263         // Look at what's already loaded and see if anything exists. We
  1264         // can't create stuff on-demand here since it's too late to add
  1265         // new translation units to the CompileContext.
  1266         Local<Package> package(zone_, Package::cast(importable));
  1267         Local<Importable> found(zone_, package->import(node->field()));
  1268         if (!found) {
  1269             cc_.reportError(node->pos(), Message_PackageDoesNotHaveMember, node->field()->chars());
  1270             return;
  1271         }
  1272 
  1273         // If we did find something, make sure it is in our import list.
  1274         // If we didn't explicitly import it, we have no right to use it.
  1275         for (index = 0; index < unit_->module()->imports(); index++) {
  1276             if (unit_->module()->getImportAt(index) == importable)
  1277                 break;
  1278         }
  1279 
  1280         if (index == unit_->module()->imports()) {
  1281             cc_.reportError(node->pos(), Message_ImportWasNeverImported, node->field()->chars());
  1282             return;
  1283         }
  1284 
  1285         // Just create a new HImport.
  1286         hir_ = new (pool_) HImport(node, hir->type(), index);
  1287     } else {
  1288         // Modules can never have sub-modules or sub-packages.
  1289         unsigned index;
  1290         Local<Module> module(zone_, Module::cast(importable));
  1291         Local<StructMap> map(zone_, module->globals()->map());
  1292         Local<Descriptor> desc(zone_, map->type()->lookupField(node->field(), &index));
  1293         if (!desc) {
  1294             cc_.reportError(node->pos(), Message_FieldNotFound, node->field()->chars());
  1295             return;
  1296         }
  1297         hir_ = new (pool_) HField(node, hir, desc->type(), index);
  1298     }
  1299 }
  1300 
  1301 void
  1302 SemanticAnalysis::visitFieldExpression(FieldExpression *node)
  1303 {
  1304     HIR *hir = eval(node->left());
  1305     if (!hir)
  1306         return;
  1307 
  1308     if (hir->isImport()) {
  1309         import(hir, node);
  1310         return;
  1311     }
  1312 
  1313     char name[255];
  1314     cc_.reportError(node->pos(), Message_InvalidFieldExpression,
  1315                     GetTypeName(hir->type(), name, sizeof(name)));
  1316 }
  1317 
  1318 static inline TokenKind
  1319 ToCompare(Expression *expr)
  1320 {
  1321     if (expr->isBinaryExpression()) {
  1322         BinaryExpression *b = expr->toBinaryExpression();
  1323         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
  1324             return b->token();
  1325     } else if (expr->isUnaryExpression()) {
  1326         UnaryExpression *u = expr->toUnaryExpression();
  1327         if (u->token() == TOK_NOT)
  1328             return TOK_NOT;
  1329     }
  1330     return TOK_EOF;
  1331 }
  1332 
  1333 void
  1334 SemanticAnalysis::visitForTest(Expression *expr,
  1335                                Label *trueBranch,
  1336                                Label *falseBranch,
  1337                                Label *fallthrough)
  1338 {
  1339     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1340 
  1341     TokenKind token = ToCompare(expr);
  1342     if (token == TOK_EOF || token == TOK_NOT) {
  1343         HIR *hir;
  1344         if (token == TOK_EOF)
  1345             hir = eval(expr);
  1346         else
  1347             hir = eval(expr->toUnaryExpression()->expression());
  1348         if (!hir)
  1349             return;
  1350         if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1351             return;
  1352 
  1353         discharge(hir);
  1354 
  1355         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
  1356         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
  1357         
  1358         if (fallthrough == falseBranch)
  1359             __ j(op, trueBranch);
  1360         else
  1361             __ j(op, falseBranch);
  1362         return;
  1363     }
  1364 
  1365     BinaryExpression *bin = expr->toBinaryExpression();
  1366     if (token == TOK_AND || token == TOK_OR) {
  1367         Label next;
  1368         if (token == TOK_AND)
  1369             visitForTest(bin->left(), &next, falseBranch, &next);
  1370         else
  1371             visitForTest(bin->left(), trueBranch, &next, &next);
  1372         __ bind(&next);
  1373         visitForTest(bin->right(), trueBranch, falseBranch, fallthrough);
  1374         return;
  1375     }
  1376 
  1377     HIR *left = eval(bin->left());
  1378     HIR *right = eval(bin->right());
  1379     if (!left || !right)
  1380         return;
  1381 
  1382     HIR *hir = binary(bin, bin->token(), left, right);
  1383     if (!hir)
  1384         return;
  1385     if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1386         return;
  1387 
  1388     discharge(hir);
  1389     if (fallthrough == trueBranch)
  1390         __ j(OP_JF, falseBranch);
  1391     else
  1392         __ j(OP_JT, trueBranch);
  1393 }
  1394 
  1395 HLValue *
  1396 SemanticAnalysis::lvalue(Expression *expr)
  1397 {
  1398     HIR *hir = eval(expr);
  1399     if (!hir)
  1400         return NULL;
  1401     
  1402     if (!hir->isLValue()) {
  1403         cc_.reportError(expr->pos(), Message_ExpectedLValue);
  1404         return NULL;
  1405     }
  1406 
  1407     return static_cast<HLValue *>(hir);
  1408 }
  1409 
  1410 HIR *
  1411 SemanticAnalysis::eval(Expression *expr)
  1412 {
  1413     assert(!hir_);
  1414     expr->accept(this);
  1415 
  1416     HIR *hir = hir_;
  1417     hir_ = NULL;
  1418 
  1419     return hir;
  1420 }
  1421 
  1422 void
  1423 SemanticAnalysis::discharge(HIR *hir)
  1424 {
  1425     EmitHIR(zone_, emitter_, hir);
  1426 }