src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Sat Nov 17 23:11:38 2012 -0800 (2012-11-17)
changeset 209 5cbec15fadfe
parent 208 7c5be05296e3
child 212 443d24cfdf2d
permissions -rw-r--r--
Split ArrayType from Type.
     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::visitIfStatement(IfStatement *node)
   210 {
   211     Label join;
   212 
   213     if (!node->ifFalse()) {
   214         Label success;
   215 
   216         visitForTest(node->condition(), &success, &join, &success);
   217         __ bind(&success);
   218         node->ifTrue()->accept(this);
   219     } else {
   220         Label success, next;
   221 
   222         visitForTest(node->condition(), &success, &next, &success);
   223         __ bind(&success);
   224         node->ifTrue()->accept(this);
   225         __ jump(&join);
   226         __ bind(&next);
   227         node->ifFalse()->accept(this);
   228     }
   229 
   230     __ bind(&join);
   231 }
   232 
   233 void
   234 SemanticAnalysis::visitForStatement(ForStatement *node)
   235 {
   236     AutoEnterScope scope(&scope_, node->scope());
   237     PoolScope poolScope(zone_->pool());
   238     RootScope rootScope(zone_);
   239 
   240     Label join, update;
   241     LoopScope loop(scope_, &join, &update, &loop_);
   242 
   243     if (node->initialization())
   244         node->initialization()->accept(this);
   245 
   246     Label header, test;
   247     if (node->condition())
   248         __ jump(&test);
   249 
   250     __ bind(&header);
   251     node->body()->accept(this);
   252 
   253     __ bind(&update);
   254     if (node->update())
   255         node->update()->accept(this);
   256 
   257     if (node->condition()) {
   258         __ bind(&test);
   259         visitForTest(node->condition(), &header, &join, &join);
   260     } else {
   261         __ jump(&header);
   262     }
   263 
   264     __ bind(&join);
   265 
   266     assert(__ stackDepth() == 0);
   267 }
   268 
   269 void
   270 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
   271 {
   272     PoolScope poolScope(zone_->pool());
   273     RootScope rootScope(zone_);
   274 
   275     Label header, join;
   276 
   277     __ bind(&header);
   278 
   279     LoopScope loop(scope_, &join, &header, &loop_);
   280     if (node->token() == TOK_WHILE) {
   281         Label body;
   282         visitForTest(node->condition(), &body, &join, &body);
   283         node->body()->accept(this);
   284         __ jump(&header);
   285     } else {
   286         node->body()->accept(this);
   287         visitForTest(node->condition(), &header, &join, &join);
   288     }
   289 
   290     __ bind(&join);
   291 
   292     assert(__ stackDepth() == 0);
   293 }
   294 
   295 void
   296 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   297 {
   298     PoolScope poolScope(zone_->pool());
   299     RootScope rootScope(zone_);
   300 
   301     HIR *hir = NULL;
   302     if (node->initialization()) {
   303         if ((hir = eval(node->initialization())) == NULL)
   304             return;
   305         if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
   306             return;
   307     } else {
   308         assert(false);
   309     }
   310 
   311     discharge(hir);
   312 
   313     if (!__ allocate(node->sym()))
   314         return;
   315 
   316     set(node->sym());
   317     __ pop();
   318 }
   319 
   320 void
   321 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   322 {
   323     if (!node->expression()) {
   324         if (!fun_->returnType()->isVoid()) {
   325             cc_.reportError(node->pos(), Message_UsedVoidReturn);
   326             return;
   327         }
   328 
   329         __ returnvoid();
   330         return;
   331     }
   332 
   333     PoolScope poolScope(zone_->pool());
   334     RootScope rootScope(zone_);
   335 
   336     HIR *hir = eval(node->expression());
   337     if (!hir)
   338         return;
   339 
   340     Local<Type> returnType(zone_, fun_->returnType());
   341     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   342         return;
   343 
   344     discharge(hir);
   345     __ return_();
   346 }
   347 
   348 void
   349 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   350 {
   351     HIR *left = eval(node->left());
   352     HIR *right = eval(node->right());
   353     if (!left || !right)
   354         return;
   355 
   356     hir_ = binary(node->token(), left, right);
   357 }
   358 
   359 bool
   360 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   361 {
   362     if (type->parameters()->length() == actual)
   363         return true;
   364 
   365     if (actual > type->parameters()->length()) {
   366         if (!type->isNative() || !type->isNativeVariadic())
   367             return false;
   368         return true;
   369     }
   370 
   371     if (!type->defaults())
   372         return false;
   373 
   374     // Missing arguments. See if there's a default argument for each missing
   375     // actual.
   376     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   377         if (!type->defaults()->at(i))
   378             return false;
   379     }
   380 
   381     return true;
   382 }
   383 
   384 void
   385 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   386 {
   387     Symbol *sym = proxy->sym();
   388     VariableSymbol *var = sym->asVariable();
   389 
   390     Scope *in = sym->scope();
   391     switch (in->kind()) {
   392       case Scope::GLOBAL:
   393         hir_ = new (pool_) HGlobal(sym);
   394         return;
   395 
   396       default:
   397         assert(in->kind() == Scope::BLOCK);
   398         assert(var->storage() == VariableSymbol::Local);
   399         hir_ = new (pool_) HLocal(var);
   400         return;
   401     }
   402 }
   403 
   404 void
   405 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   406 {
   407     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   408     hir_ = new (pool_) HInteger(type, lit->value());
   409 }
   410 
   411 void
   412 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   413 {
   414     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   415     hir_ = new (pool_) HFloat(type, (float)node->value());
   416 }
   417 
   418 void
   419 SemanticAnalysis::visitCallExpression(CallExpression *node)
   420 {
   421     HIR *callee = eval(node->callee());
   422     if (!callee)
   423         return;
   424 
   425     if (!callee->type()->isFunction()) {
   426         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   427         return;
   428     }
   429 
   430     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   431     
   432     if (!checkArgumentCount(fun, node->arguments()->length())) {
   433         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   434         return;
   435     }
   436 
   437     if (fun->isForward()) {
   438         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   439         return;
   440     }
   441 
   442     HIRList *args = new (pool_) HIRList;
   443     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   444         Expression *expression = node->arguments()->at(i);
   445         HIR *arg = eval(expression);
   446         if (!arg)
   447             return;
   448 
   449         Handle<Type> given = arg->type();
   450         
   451         bool mustComputeReference;
   452         if (i >= fun->parameters()->length()) {
   453             // Special handling for natives. Arguments past the formal must
   454             // always have references computed. However, arrays are already
   455             // references for natives.
   456             assert(fun->isNative() && fun->isNativeVariadic());
   457             mustComputeReference = !given->isReference() &&
   458                                    !given->isArray();
   459         } else {
   460             Local<Type> actual(zone_, fun->parameterAt(i));
   461 
   462             if (expression->isIndexExpression()) {
   463                 // Temporarily disabled.
   464                 assert(!actual->isArray());
   465                 if (actual->isReference()) {
   466                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   467                     return;
   468                 }
   469             }
   470 
   471             // When we start overloading, coercion will have to happen later.
   472             arg = coerce(arg, actual, Coerce_Arg);
   473             if (!arg)
   474                 return;
   475 
   476             mustComputeReference = actual->isReference() && !given->isReference();
   477         }
   478 
   479         // :TODO: handle mustComputeReference
   480         assert(!mustComputeReference);
   481 
   482         if (!args->append(arg))
   483             return;
   484     }
   485 
   486     hir_ = new (pool_) HCall(fun->returnType(), callee, args);
   487 }
   488 
   489 void
   490 SemanticAnalysis::visitAssignment(Assignment *node)
   491 {
   492     HLValue *lval = lvalue(node->lvalue());
   493     if (!lval)
   494         return;
   495 
   496     HIR *hir = eval(node->expression());
   497     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   498         return;
   499 
   500     hir_ = new (pool_) HStore(lval, hir);
   501 }
   502 
   503 void
   504 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   505 {
   506     if (!loop_) {
   507         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   508         return;
   509     }
   510 
   511     // Note, if we re-introduce LIFO allocs, we need to unwind here.
   512     __ jump(loop_->break_());
   513 }
   514 
   515 void
   516 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   517 {
   518     if (!loop_) {
   519         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   520         return;
   521     }
   522 
   523     // Note, if we re-introduce LIFO allocs, we need to unwind here.
   524     __ jump(loop_->continue_());
   525 }
   526 
   527 Type *
   528 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   529 {
   530     Handle<Type> l = left->type();
   531     Handle<Type> r = right->type();
   532 
   533     if (token >= TOK_PLUS && token <= TOK_SLASH) {
   534         // We allow: [float|int32] + [float|int32]
   535         if (l->isFloat() && r->isInt32())
   536             return l;
   537         if (l->isInt32() && r->isFloat())
   538             return r;
   539         if (l->isInt32() && r->isInt32())
   540             return l;
   541     }
   542 
   543     assert(l == r);
   544 
   545     return left->type();
   546 }
   547 
   548 HIR *
   549 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
   550 {
   551     Handle<Type> from = hir->type();
   552 
   553     if (from->isInt32() && to->isFloat())
   554         return new (pool_) HConvert(to, OP_CVT_I2F, hir);
   555     if (from->isInt32() && to->isBool())
   556         return new (pool_) HConvert(to, OP_CVT_I2B, hir);
   557     
   558     assert(from == to);
   559     
   560     return hir;
   561 }
   562 
   563 void
   564 SemanticAnalysis::set(VariableSymbol *sym)
   565 {
   566     if (sym->scope()->kind() == Scope::GLOBAL) {
   567         __ setglobal(sym);
   568     } else {
   569         assert(sym->storage() == VariableSymbol::Local);
   570         __ setlocal(sym);
   571     }
   572 }
   573 
   574 HIR *
   575 SemanticAnalysis::binary(TokenKind token, HIR *left, HIR *right)
   576 {
   577     Local<Type> coercion(zone_, coercionType(token, left, right));
   578     if (!coercion)
   579         return NULL;
   580     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
   581         return NULL;
   582     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
   583         return NULL;
   584     
   585     switch (token) {
   586      case TOK_PLUS:
   587       case TOK_MINUS:
   588       case TOK_STAR:
   589       case TOK_SLASH:
   590       case TOK_PERCENT:
   591       case TOK_AMPERSAND:
   592       case TOK_BITOR:
   593       case TOK_BITXOR:
   594       case TOK_SHR:
   595       case TOK_USHR:
   596       case TOK_SHL:
   597         return new (pool_) HBinary(left->type(), token, left, right);
   598 
   599       case TOK_EQUALS:
   600       case TOK_NOTEQUALS:
   601       case TOK_LT:
   602       case TOK_LE:
   603       case TOK_GT:
   604       case TOK_GE:
   605       case TOK_AND:
   606       case TOK_OR:
   607       {
   608         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   609         return new (pool_) HBinary(result, token, left, right);
   610       }
   611 
   612       default:
   613         assert(false);
   614         return NULL;
   615     }
   616 }
   617 
   618 static inline TokenKind
   619 ToCompare(Expression *expr)
   620 {
   621     if (expr->isBinaryExpression()) {
   622         BinaryExpression *b = expr->toBinaryExpression();
   623         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
   624             return b->token();
   625     } else if (expr->isUnaryExpression()) {
   626         UnaryExpression *u = expr->toUnaryExpression();
   627         if (u->token() == TOK_NOT)
   628             return TOK_NOT;
   629     }
   630     return TOK_EOF;
   631 }
   632 
   633 void
   634 SemanticAnalysis::visitForTest(Expression *expr,
   635                                Label *trueBranch,
   636                                Label *falseBranch,
   637                                Label *fallthrough)
   638 {
   639     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   640 
   641     TokenKind token = ToCompare(expr);
   642     if (token == TOK_EOF || token == TOK_NOT) {
   643         HIR *hir;
   644         if (token == TOK_EOF)
   645             hir = eval(expr);
   646         else
   647             hir = eval(expr->toUnaryExpression()->expression());
   648         if (!hir)
   649             return;
   650         if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
   651             return;
   652 
   653         discharge(hir);
   654 
   655         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
   656         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
   657         
   658         if (fallthrough == falseBranch)
   659             __ j(op, trueBranch);
   660         else
   661             __ j(op, falseBranch);
   662         return;
   663     }
   664 
   665     BinaryExpression *bin = expr->toBinaryExpression();
   666     if (token == TOK_AND || token == TOK_OR) {
   667         assert(false);
   668         //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
   669         return;
   670     }
   671 
   672     HIR *left = eval(bin->left());
   673     HIR *right = eval(bin->right());
   674     if (!left || !right)
   675         return;
   676 
   677     HIR *hir = binary(bin->token(), left, right);
   678     if (!hir)
   679         return;
   680     if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
   681         return;
   682 
   683     discharge(hir);
   684     if (fallthrough == trueBranch)
   685         __ j(OP_JF, falseBranch);
   686     else
   687         __ j(OP_JT, trueBranch);
   688 }
   689 
   690 HLValue *
   691 SemanticAnalysis::lvalue(Expression *expr)
   692 {
   693     HIR *hir = eval(expr);
   694     if (!hir)
   695         return NULL;
   696     
   697     if (!hir->isLValue()) {
   698         cc_.reportError(expr->pos(), Message_ExpectedLValue);
   699         return NULL;
   700     }
   701 
   702     return static_cast<HLValue *>(hir);
   703 }
   704 
   705 HIR *
   706 SemanticAnalysis::eval(Expression *expr)
   707 {
   708     assert(!hir_);
   709     expr->accept(this);
   710 
   711     HIR *hir = hir_;
   712     hir_ = NULL;
   713 
   714     return hir;
   715 }
   716 
   717 void
   718 SemanticAnalysis::discharge(HIR *hir)
   719 {
   720     EmitHIR(zone_, emitter_, hir);
   721 }