src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Sat Nov 17 19:22:27 2012 -0800 (2012-11-17)
changeset 199 b690381dcb35
parent 196 9904633b1dfc
child 200 e0a601465746
permissions -rw-r--r--
Fix Linux 64-bit build again.
     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     __ public_();
   152 }
   153 
   154 Function *
   155 SemanticAnalysis::compile(FunctionStatement *stmt)
   156 {
   157     __ setFirstLine(stmt->pos().line);
   158 
   159     AutoEnterScope argScope(&scope_, stmt->argScope());
   160     AutoEnterScope varScope(&scope_, stmt->varScope());
   161 
   162     stmt->body()->accept(this);
   163 
   164     Local<Code> code(zone_, __ finish());
   165     if (!code)
   166         return NULL;
   167     code->setModule(module_);
   168 
   169     Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
   170     if (!fun)
   171         return NULL;
   172 
   173 #ifndef NDEBUG
   174 //    Disassemble(code, stdout);
   175 #endif
   176 
   177     return fun;
   178 }
   179 
   180 void 
   181 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
   182 {
   183     AutoEnterScope scope(&scope_, node->scope());
   184 
   185     for (size_t i = 0; i < node->statements()->length(); i++) {
   186         Statement *stmt = node->statements()->at(i);
   187         stmt->accept(this);
   188         assert(__ stackDepth() == 0);
   189     }
   190 }
   191 
   192 void
   193 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
   194 {
   195     // While building HIR, we enter new pool and root scopes, since HIR
   196     // creation is purely temporary.
   197     PoolScope poolScope(zone_->pool());
   198     RootScope rootScope(zone_);
   199 
   200     HIR *hir = eval(node->expression());
   201     if (!hir)
   202         return;
   203 
   204     discharge(hir);
   205     __ pop();
   206 }
   207 
   208 void
   209 SemanticAnalysis::visitForStatement(ForStatement *node)
   210 {
   211     AutoEnterScope scope(&scope_, node->scope());
   212     PoolScope poolScope(zone_->pool());
   213     RootScope rootScope(zone_);
   214 
   215     Label join, update;
   216     LoopScope loop(scope_, &join, &update, &loop_);
   217 
   218     if (node->initialization())
   219         node->initialization()->accept(this);
   220 
   221     Label header, test;
   222     if (node->condition())
   223         __ jump(&test);
   224 
   225     __ bind(&header);
   226     node->body()->accept(this);
   227 
   228     __ bind(&update);
   229     if (node->update())
   230         node->update()->accept(this);
   231 
   232     if (node->condition()) {
   233         __ bind(&test);
   234         visitForTest(node->condition(), &header, &join, &join);
   235     } else {
   236         __ jump(&header);
   237     }
   238 
   239     __ bind(&join);
   240 
   241     assert(__ stackDepth() == 0);
   242 }
   243 
   244 void
   245 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   246 {
   247     PoolScope poolScope(zone_->pool());
   248     RootScope rootScope(zone_);
   249 
   250     HIR *hir = NULL;
   251     if (node->initialization()) {
   252         if ((hir = eval(node->initialization())) == NULL)
   253             return;
   254         if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
   255             return;
   256     } else {
   257         assert(false);
   258     }
   259 
   260     discharge(hir);
   261 
   262     if (!__ allocate(node->sym()))
   263         return;
   264 
   265     set(node->sym());
   266     __ pop();
   267 }
   268 
   269 void
   270 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   271 {
   272     if (!node->expression()) {
   273         if (!fun_->returnType()->isVoid()) {
   274             cc_.reportError(node->pos(), Message_UsedVoidReturn);
   275             return;
   276         }
   277 
   278         __ returnvoid();
   279         return;
   280     }
   281 
   282     PoolScope poolScope(zone_->pool());
   283     RootScope rootScope(zone_);
   284 
   285     HIR *hir = eval(node->expression());
   286     if (!hir)
   287         return;
   288 
   289     Local<Type> returnType(zone_, fun_->returnType());
   290     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   291         return;
   292 
   293     discharge(hir);
   294     __ return_();
   295 }
   296 
   297 void
   298 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   299 {
   300     HIR *left = eval(node->left());
   301     HIR *right = eval(node->right());
   302     if (!left || !right)
   303         return;
   304 
   305     hir_ = binary(node->token(), left, right);
   306 }
   307 
   308 bool
   309 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   310 {
   311     if (type->parameters()->length() == actual)
   312         return true;
   313 
   314     if (actual > type->parameters()->length()) {
   315         if (!type->isNative() || !type->isNativeVariadic())
   316             return false;
   317         return true;
   318     }
   319 
   320     if (!type->defaults())
   321         return false;
   322 
   323     // Missing arguments. See if there's a default argument for each missing
   324     // actual.
   325     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   326         if (!type->defaults()->at(i))
   327             return false;
   328     }
   329 
   330     return true;
   331 }
   332 
   333 void
   334 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   335 {
   336     Symbol *sym = proxy->sym();
   337     Handle<Type> type = sym->type();
   338 
   339     VariableSymbol *var = sym->asVariable();
   340 
   341     Scope *in = sym->scope();
   342     switch (in->kind()) {
   343       case Scope::GLOBAL:
   344         hir_ = new (pool_) HGlobal(sym);
   345         return;
   346 
   347       default:
   348         assert(in->kind() == Scope::BLOCK);
   349         assert(var->storage() == VariableSymbol::Local);
   350         hir_ = new (pool_) HLocal(var);
   351         return;
   352     }
   353 }
   354 
   355 void
   356 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   357 {
   358     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   359     hir_ = new (pool_) HInteger(type, lit->value());
   360 }
   361 
   362 void
   363 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   364 {
   365     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   366     hir_ = new (pool_) HFloat(type, (float)node->value());
   367 }
   368 
   369 void
   370 SemanticAnalysis::visitCallExpression(CallExpression *node)
   371 {
   372     HIR *callee = eval(node->callee());
   373     if (!callee)
   374         return;
   375 
   376     if (!callee->type()->isFunction()) {
   377         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   378         return;
   379     }
   380 
   381     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   382     
   383     if (!checkArgumentCount(fun, node->arguments()->length())) {
   384         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   385         return;
   386     }
   387 
   388     if (fun->isForward()) {
   389         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   390         return;
   391     }
   392 
   393     HIRList *args = new (pool_) HIRList;
   394     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   395         Expression *expression = node->arguments()->at(i);
   396         HIR *arg = eval(expression);
   397         if (!arg)
   398             return;
   399 
   400         Handle<Type> given = arg->type();
   401         
   402         bool mustComputeReference;
   403         if (i >= fun->parameters()->length()) {
   404             // Special handling for natives. Arguments past the formal must
   405             // always have references computed. However, arrays are already
   406             // references for natives.
   407             assert(fun->isNative() && fun->isNativeVariadic());
   408             mustComputeReference = !given->isReference() &&
   409                                    !given->isArray();
   410         } else {
   411             Local<Type> actual(zone_, fun->parameterAt(i));
   412 
   413             if (expression->isIndexExpression()) {
   414                 // Temporarily disabled.
   415                 assert(!actual->isArray());
   416                 if (actual->isReference()) {
   417                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   418                     return;
   419                 }
   420             }
   421 
   422             // When we start overloading, coercion will have to happen later.
   423             arg = coerce(arg, actual, Coerce_Arg);
   424             if (!arg)
   425                 return;
   426 
   427             mustComputeReference = actual->isReference() && !given->isReference();
   428         }
   429 
   430         // :TODO: handle mustComputeReference
   431         assert(!mustComputeReference);
   432 
   433         if (!args->append(arg))
   434             return;
   435     }
   436 
   437     hir_ = new (pool_) HCall(fun->returnType(), callee, args);
   438 }
   439 
   440 void
   441 SemanticAnalysis::visitAssignment(Assignment *node)
   442 {
   443     HLValue *lval = lvalue(node->lvalue());
   444     if (!lval)
   445         return;
   446 
   447     HIR *hir = eval(node->expression());
   448     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   449         return;
   450 
   451     hir_ = new (pool_) HStore(lval, hir);
   452 }
   453 
   454 Type *
   455 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   456 {
   457     Handle<Type> l = left->type();
   458     Handle<Type> r = right->type();
   459 
   460     if (token >= TOK_PLUS && token <= TOK_SLASH) {
   461         // We allow: [float|int32] + [float|int32]
   462         if (l->isFloat() && r->isInt32())
   463             return l;
   464         if (l->isInt32() && r->isFloat())
   465             return r;
   466         if (l->isInt32() && r->isInt32())
   467             return l;
   468     }
   469 
   470     assert(l == r);
   471 
   472     return left->type();
   473 }
   474 
   475 HIR *
   476 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
   477 {
   478     Handle<Type> from = hir->type();
   479 
   480     if (from->isInt32() && to->isFloat())
   481         return new (pool_) HConvert(to, OP_CVT_I2F, hir);
   482     
   483     assert(from == to);
   484     
   485     return hir;
   486 }
   487 
   488 void
   489 SemanticAnalysis::set(VariableSymbol *sym)
   490 {
   491     if (sym->scope()->kind() == Scope::GLOBAL) {
   492         __ setglobal(sym);
   493     } else {
   494         assert(sym->storage() == VariableSymbol::Local);
   495         __ setlocal(sym);
   496     }
   497 }
   498 
   499 HIR *
   500 SemanticAnalysis::binary(TokenKind token, HIR *left, HIR *right)
   501 {
   502     Local<Type> coercion(zone_, coercionType(token, left, right));
   503     if (!coercion)
   504         return NULL;
   505     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
   506         return NULL;
   507     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
   508         return NULL;
   509     
   510     switch (token) {
   511      case TOK_PLUS:
   512       case TOK_MINUS:
   513       case TOK_STAR:
   514       case TOK_SLASH:
   515       case TOK_PERCENT:
   516       case TOK_AMPERSAND:
   517       case TOK_BITOR:
   518       case TOK_BITXOR:
   519       case TOK_SHR:
   520       case TOK_USHR:
   521       case TOK_SHL:
   522         return new (pool_) HBinary(left->type(), token, left, right);
   523 
   524       case TOK_EQUALS:
   525       case TOK_NOTEQUALS:
   526       case TOK_LT:
   527       case TOK_LE:
   528       case TOK_GT:
   529       case TOK_GE:
   530       case TOK_AND:
   531       case TOK_OR:
   532       {
   533         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   534         return new (pool_) HBinary(result, token, left, right);
   535       }
   536 
   537       default:
   538         assert(false);
   539         return NULL;
   540     }
   541 }
   542 
   543 static inline TokenKind
   544 ToCompare(Expression *expr)
   545 {
   546     if (expr->isBinaryExpression()) {
   547         BinaryExpression *b = expr->toBinaryExpression();
   548         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
   549             return b->token();
   550     } else if (expr->isUnaryExpression()) {
   551         UnaryExpression *u = expr->toUnaryExpression();
   552         if (u->token() == TOK_NOT)
   553             return TOK_NOT;
   554     }
   555     return TOK_EOF;
   556 }
   557 
   558 void
   559 SemanticAnalysis::visitForTest(Expression *expr,
   560                                Label *trueBranch,
   561                                Label *falseBranch,
   562                                Label *fallthrough)
   563 {
   564     TokenKind token = ToCompare(expr);
   565     if (token == TOK_EOF || token == TOK_NOT) {
   566         assert(false);
   567         //visitForUnaryTest(expr, trueBranch, falseBranch, fallthrough);
   568         return;
   569     }
   570 
   571     BinaryExpression *bin = expr->toBinaryExpression();
   572     if (token == TOK_AND || token == TOK_OR) {
   573         assert(false);
   574         //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
   575         return;
   576     }
   577 
   578     HIR *left = eval(bin->left());
   579     HIR *right = eval(bin->right());
   580     if (!left || !right)
   581         return;
   582 
   583     HIR *hir = binary(bin->token(), left, right);
   584     if (!hir)
   585         return;
   586 
   587     discharge(hir);
   588     if (fallthrough == trueBranch)
   589         __ j(OP_JF, falseBranch);
   590     else
   591         __ j(OP_JT, trueBranch);
   592 }
   593 
   594 HLValue *
   595 SemanticAnalysis::lvalue(Expression *expr)
   596 {
   597     HIR *hir = eval(expr);
   598     if (!hir)
   599         return NULL;
   600     
   601     if (!hir->isLValue()) {
   602         cc_.reportError(expr->pos(), Message_ExpectedLValue);
   603         return NULL;
   604     }
   605 
   606     return static_cast<HLValue *>(hir);
   607 }
   608 
   609 HIR *
   610 SemanticAnalysis::eval(Expression *expr)
   611 {
   612     assert(!hir_);
   613     expr->accept(this);
   614 
   615     HIR *hir = hir_;
   616     hir_ = NULL;
   617 
   618     return hir;
   619 }
   620 
   621 void
   622 SemanticAnalysis::discharge(HIR *hir)
   623 {
   624     EmitHIR(zone_, emitter_, hir);
   625 }