Get preinc working again.
1 /* vim: set ts=4 sw=4 tw=99 et:
3 * Copyright (C) 2012 David Anderson
5 * This file is part of SourcePawn.
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)
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.
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/.
21 #include "../Strings.h"
22 #include "../NativeTable.h"
23 #include "../TypeManager.h"
24 #include "../Modules.h"
26 #include "SemanticAnalysis.h"
27 #include "../Heap-inl.h"
33 typedef BytecodeEmitter::Label Label;
38 AutoEnterScope(Scope **prevp, Scope *scope)
47 assert(prev_ == scope->enclosing());
60 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, TranslationUnit *unit)
72 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
73 : zone_(parent->zone_),
78 scope_(parent->scope_),
80 module_(parent->module_),
88 SemanticAnalysis::analyze()
90 scope_ = unit_->globalScope();
92 module_ = Module::New(zone_);
94 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
95 Statement *stmt = unit_->tree()->statements()->at(i);
99 Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
102 module_->setGlobals(globals);
104 Local<Code> code(zone_, __ finish());
107 code->setModule(module_);
108 module_->setCode(code);
111 // Disassemble(code, stdout);
114 unit_->module_ = module_;
118 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
120 FunctionSymbol *sym = stmt->sym();
121 Local<FunctionType> type(zone_, sym->type());
123 assert(scope_->kind() == Scope::GLOBAL);
125 if (stmt->token() == TOK_NATIVE) {
126 // Define the native now.
128 if (!zone_->nativeTable()->add(stmt->name(), &index))
131 Local<Native> native(zone_, Native::New(zone_, type, index));
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)
144 SemanticAnalysis child(this, type);
145 Local<Function> funobj(zone_, child.compile(stmt));
151 if (stmt->token() == TOK_PUBLIC)
158 SemanticAnalysis::compile(FunctionStatement *stmt)
160 __ setFirstLine(stmt->pos().line);
162 AutoEnterScope argScope(&scope_, stmt->argScope());
163 AutoEnterScope varScope(&scope_, stmt->varScope());
165 stmt->body()->accept(this);
167 Local<Code> code(zone_, __ finish());
170 code->setModule(module_);
172 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
177 // Disassemble(code, stdout);
184 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
186 AutoEnterScope scope(&scope_, node->scope());
188 for (size_t i = 0; i < node->statements()->length(); i++) {
189 Statement *stmt = node->statements()->at(i);
191 assert(__ stackDepth() == 0);
196 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
198 // While building HIR, we enter new pool and root scopes, since HIR
199 // creation is purely temporary.
200 PoolScope poolScope(zone_->pool());
201 RootScope rootScope(zone_);
203 HIR *hir = eval(node->expression());
212 SemanticAnalysis::visitIfStatement(IfStatement *node)
216 if (!node->ifFalse()) {
219 visitForTest(node->condition(), &success, &join, &success);
221 node->ifTrue()->accept(this);
225 visitForTest(node->condition(), &success, &next, &success);
227 node->ifTrue()->accept(this);
230 node->ifFalse()->accept(this);
237 SemanticAnalysis::visitForStatement(ForStatement *node)
239 AutoEnterScope scope(&scope_, node->scope());
240 PoolScope poolScope(zone_->pool());
241 RootScope rootScope(zone_);
244 LoopScope loop(scope_, &join, &update, &loop_);
246 if (node->initialization())
247 node->initialization()->accept(this);
250 if (node->condition())
254 node->body()->accept(this);
258 node->update()->accept(this);
260 if (node->condition()) {
262 visitForTest(node->condition(), &header, &join, &join);
269 assert(__ stackDepth() == 0);
273 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
275 PoolScope poolScope(zone_->pool());
276 RootScope rootScope(zone_);
282 LoopScope loop(scope_, &join, &header, &loop_);
283 if (node->token() == TOK_WHILE) {
285 visitForTest(node->condition(), &body, &join, &body);
286 node->body()->accept(this);
289 node->body()->accept(this);
290 visitForTest(node->condition(), &header, &join, &join);
295 assert(__ stackDepth() == 0);
298 static inline Heap::Tenure
299 InferTenure(Symbol *sym)
301 if (sym->scope()->kind() == Scope::GLOBAL)
302 return Heap::Tenure_Old;
303 // :TODO: need to use LIFO!
304 return Heap::Tenure_Default;
308 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
310 PoolScope poolScope(zone_->pool());
311 RootScope rootScope(zone_);
313 if (node->initialization()) {
316 if ((hir = eval(node->initialization())) == NULL)
318 if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
323 if (node->sym()->type()->isInt32() ||
324 node->sym()->type()->isEnum() ||
325 node->sym()->type()->isChar() ||
326 node->sym()->type()->isBool())
329 } else if (node->sym()->type()->isFloat()) {
331 } else if (node->sym()->type()->isArray()) {
332 Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
333 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
337 if (type->isFixedLength()) {
338 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
339 } else if (node->dims()) {
341 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
343 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
348 if (!__ allocate(node->sym()))
356 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
358 if (!node->expression()) {
359 if (!fun_->returnType()->isVoid()) {
360 cc_.reportError(node->pos(), Message_UsedVoidReturn);
368 PoolScope poolScope(zone_->pool());
369 RootScope rootScope(zone_);
371 HIR *hir = eval(node->expression());
375 Local<Type> returnType(zone_, fun_->returnType());
376 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
384 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
386 HIR *left = eval(node->left());
387 HIR *right = eval(node->right());
391 hir_ = binary(node->token(), left, right);
395 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
397 if (type->parameters()->length() == actual)
400 if (actual > type->parameters()->length()) {
401 if (!type->isNative() || !type->isNativeVariadic())
406 if (!type->defaults())
409 // Missing arguments. See if there's a default argument for each missing
411 for (unsigned i = actual; i < type->parameters()->length(); i++) {
412 if (!type->defaults()->at(i))
420 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
422 Symbol *sym = proxy->sym();
423 VariableSymbol *var = sym->asVariable();
425 Scope *in = sym->scope();
426 switch (in->kind()) {
428 hir_ = new (pool_) HGlobal(sym);
432 assert(in->kind() == Scope::BLOCK);
433 assert(var->storage() == VariableSymbol::Local);
434 hir_ = new (pool_) HLocal(var);
440 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
442 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
443 hir_ = new (pool_) HInteger(type, lit->value());
447 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
449 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
450 hir_ = new (pool_) HFloat(type, (float)node->value());
454 SemanticAnalysis::visitCallExpression(CallExpression *node)
456 HIR *callee = eval(node->callee());
460 if (!callee->type()->isFunction()) {
461 cc_.reportError(node->pos(), Message_CalleeNotFunction);
465 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
467 if (!checkArgumentCount(fun, node->arguments()->length())) {
468 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
472 if (fun->isForward()) {
473 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
477 HIRList *args = new (pool_) HIRList;
478 for (unsigned i = 0; i < node->arguments()->length(); i++) {
479 Expression *expression = node->arguments()->at(i);
480 HIR *arg = eval(expression);
484 Handle<Type> given = arg->type();
486 bool mustComputeReference;
487 if (i >= fun->parameters()->length()) {
488 // Special handling for natives. Arguments past the formal must
489 // always have references computed. However, arrays are already
490 // references for natives.
491 assert(fun->isNative() && fun->isNativeVariadic());
492 mustComputeReference = !given->isReference() &&
495 Local<Type> actual(zone_, fun->parameterAt(i));
497 if (expression->isIndexExpression()) {
498 // Temporarily disabled.
499 assert(!actual->isArray());
500 if (actual->isReference()) {
501 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
506 // When we start overloading, coercion will have to happen later.
507 arg = coerce(arg, actual, Coerce_Arg);
511 mustComputeReference = actual->isReference() && !given->isReference();
514 // :TODO: handle mustComputeReference
515 assert(!mustComputeReference);
517 if (!args->append(arg))
521 hir_ = new (pool_) HCall(fun->returnType(), callee, args);
525 SemanticAnalysis::visitAssignment(Assignment *node)
527 HLValue *lval = lvalue(node->lvalue());
531 HIR *hir = eval(node->expression());
532 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
535 hir_ = new (pool_) HStore(node->token(), lval, hir);
539 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
542 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
546 // Note, if we re-introduce LIFO allocs, we need to unwind here.
547 __ jump(loop_->break_());
551 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
554 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
558 // Note, if we re-introduce LIFO allocs, we need to unwind here.
559 __ jump(loop_->continue_());
563 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
565 HIR *left = eval(node->left());
569 HIR *right = eval(node->right());
573 // Hrm... yes, for now, let's coerce here.
574 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
575 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
578 // Do not coerce here, there's no reason to yet.
579 if (!left->type()->isArray()) {
580 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
584 hir_ = new (pool_) HIndex(ArrayType::cast(left->type())->contained(),
590 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
592 HLValue *lval = lvalue(node->expression());
596 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
602 if (lval->type()->isInt32())
603 rval = new (pool_) HInteger(lval->type(), 1);
605 rval = new (pool_) HFloat(lval->type(), 1.0);
607 if (node->postfix()) {
610 hir_ = new (pool_) HStore(node->token(), lval, rval);
615 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
617 Handle<Type> l = left->type();
618 Handle<Type> r = right->type();
620 if (token >= TOK_PLUS && token <= TOK_SLASH) {
621 // We allow: [float|int32] + [float|int32]
622 if (l->isFloat() && r->isInt32())
624 if (l->isInt32() && r->isFloat())
626 if (l->isInt32() && r->isInt32())
636 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
638 Handle<Type> from = hir->type();
640 if (from->isInt32() && to->isFloat())
641 return new (pool_) HConvert(to, OP_CVT_I2F, hir);
642 if (from->isInt32() && to->isBool())
643 return new (pool_) HConvert(to, OP_CVT_I2B, hir);
651 SemanticAnalysis::set(VariableSymbol *sym)
653 if (sym->scope()->kind() == Scope::GLOBAL) {
656 assert(sym->storage() == VariableSymbol::Local);
662 SemanticAnalysis::binary(TokenKind token, HIR *left, HIR *right)
664 Local<Type> coercion(zone_, coercionType(token, left, right));
667 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
669 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
684 return new (pool_) HBinary(left->type(), token, left, right);
695 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
696 return new (pool_) HBinary(result, token, left, right);
705 static inline TokenKind
706 ToCompare(Expression *expr)
708 if (expr->isBinaryExpression()) {
709 BinaryExpression *b = expr->toBinaryExpression();
710 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
712 } else if (expr->isUnaryExpression()) {
713 UnaryExpression *u = expr->toUnaryExpression();
714 if (u->token() == TOK_NOT)
721 SemanticAnalysis::visitForTest(Expression *expr,
726 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
728 TokenKind token = ToCompare(expr);
729 if (token == TOK_EOF || token == TOK_NOT) {
731 if (token == TOK_EOF)
734 hir = eval(expr->toUnaryExpression()->expression());
737 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
742 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
743 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
745 if (fallthrough == falseBranch)
746 __ j(op, trueBranch);
748 __ j(op, falseBranch);
752 BinaryExpression *bin = expr->toBinaryExpression();
753 if (token == TOK_AND || token == TOK_OR) {
755 //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
759 HIR *left = eval(bin->left());
760 HIR *right = eval(bin->right());
764 HIR *hir = binary(bin->token(), left, right);
767 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
771 if (fallthrough == trueBranch)
772 __ j(OP_JF, falseBranch);
774 __ j(OP_JT, trueBranch);
778 SemanticAnalysis::lvalue(Expression *expr)
780 HIR *hir = eval(expr);
784 if (!hir->isLValue()) {
785 cc_.reportError(expr->pos(), Message_ExpectedLValue);
789 return static_cast<HLValue *>(hir);
793 SemanticAnalysis::eval(Expression *expr)
805 SemanticAnalysis::discharge(HIR *hir)
807 EmitHIR(zone_, emitter_, hir);