Re-added support for reference arguments.
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());
164 for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
165 Parameter *param = stmt->signature().parameters()->at(i);
166 param->sym()->allocate(VariableSymbol::Arg, i);
169 AutoEnterScope varScope(&scope_, stmt->varScope());
171 stmt->body()->accept(this);
173 Local<Code> code(zone_, __ finish());
176 code->setModule(module_);
178 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
183 // Disassemble(code, stdout);
190 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
192 AutoEnterScope scope(&scope_, node->scope());
194 for (size_t i = 0; i < node->statements()->length(); i++) {
195 Statement *stmt = node->statements()->at(i);
196 __ note_position(stmt->pos());
198 assert(__ stackDepth() == 0);
203 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
205 // While building HIR, we enter new pool and root scopes, since HIR
206 // creation is purely temporary.
207 PoolScope poolScope(zone_->pool());
208 RootScope rootScope(zone_);
210 HIR *hir = eval(node->expression());
215 if (!hir->type()->isVoid())
220 SemanticAnalysis::visitIfStatement(IfStatement *node)
224 if (!node->ifFalse()) {
227 visitForTest(node->condition(), &success, &join, &success);
229 node->ifTrue()->accept(this);
233 visitForTest(node->condition(), &success, &next, &success);
235 node->ifTrue()->accept(this);
238 node->ifFalse()->accept(this);
245 SemanticAnalysis::visitForStatement(ForStatement *node)
247 AutoEnterScope scope(&scope_, node->scope());
248 PoolScope poolScope(zone_->pool());
249 RootScope rootScope(zone_);
252 LoopScope loop(scope_, &join, &update, &loop_);
254 if (node->initialization())
255 node->initialization()->accept(this);
258 if (node->condition())
262 node->body()->accept(this);
266 node->update()->accept(this);
268 if (node->condition()) {
270 visitForTest(node->condition(), &header, &join, &join);
277 assert(__ stackDepth() == 0);
281 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
283 PoolScope poolScope(zone_->pool());
284 RootScope rootScope(zone_);
290 LoopScope loop(scope_, &join, &header, &loop_);
291 if (node->token() == TOK_WHILE) {
293 visitForTest(node->condition(), &body, &join, &body);
294 node->body()->accept(this);
297 node->body()->accept(this);
298 visitForTest(node->condition(), &header, &join, &join);
303 assert(__ stackDepth() == 0);
306 static inline Heap::Tenure
307 InferTenure(Symbol *sym)
309 if (sym->scope()->kind() == Scope::GLOBAL)
310 return Heap::Tenure_Old;
311 // :TODO: need to use LIFO!
312 return Heap::Tenure_Default;
316 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
318 PoolScope poolScope(zone_->pool());
319 RootScope rootScope(zone_);
321 if (node->initialization()) {
324 if ((hir = eval(node->initialization())) == NULL)
326 if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
331 if (node->sym()->type()->isInt32() ||
332 node->sym()->type()->isEnum() ||
333 node->sym()->type()->isChar() ||
334 node->sym()->type()->isBool())
337 } else if (node->sym()->type()->isFloat()) {
339 } else if (node->sym()->type()->isArray()) {
340 Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
341 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
345 if (type->isFixedLength()) {
346 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
347 } else if (node->dims()) {
349 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
351 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
356 if (!__ allocate(node->sym()))
364 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
366 if (!node->expression()) {
367 if (!fun_->returnType()->isVoid()) {
368 cc_.reportError(node->pos(), Message_UsedVoidReturn);
376 PoolScope poolScope(zone_->pool());
377 RootScope rootScope(zone_);
379 HIR *hir = eval(node->expression());
383 Local<Type> returnType(zone_, fun_->returnType());
384 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
392 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
394 HIR *left = eval(node->left());
395 HIR *right = eval(node->right());
399 hir_ = binary(node, node->token(), left, right);
403 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
405 if (type->parameters()->length() == actual)
408 if (actual > type->parameters()->length()) {
409 if (!type->isNative() || !type->isNativeVariadic())
414 if (!type->defaults())
417 // Missing arguments. See if there's a default argument for each missing
419 for (unsigned i = actual; i < type->parameters()->length(); i++) {
420 if (!type->defaults()->at(i))
428 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
430 Symbol *sym = proxy->sym();
431 VariableSymbol *var = sym->asVariable();
433 Scope *in = sym->scope();
434 switch (in->kind()) {
436 hir_ = new (pool_) HGlobal(proxy, sym);
439 case Scope::FUNCTION:
440 assert(var->storage() == VariableSymbol::Arg);
441 hir_ = new (pool_) HLocal(proxy, var);
445 assert(in->kind() == Scope::BLOCK);
446 assert(var->storage() == VariableSymbol::Local);
447 hir_ = new (pool_) HLocal(proxy, var);
453 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
455 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
456 hir_ = new (pool_) HInteger(lit, type, lit->value());
460 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
462 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
463 hir_ = new (pool_) HFloat(node, type, (float)node->value());
467 SemanticAnalysis::visitCallExpression(CallExpression *node)
469 HIR *callee = eval(node->callee());
473 if (!callee->type()->isFunction()) {
474 cc_.reportError(node->pos(), Message_CalleeNotFunction);
478 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
480 if (!checkArgumentCount(fun, node->arguments()->length())) {
481 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
485 if (fun->isForward()) {
486 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
490 HIRList *args = new (pool_) HIRList;
491 for (unsigned i = 0; i < node->arguments()->length(); i++) {
492 Expression *expression = node->arguments()->at(i);
493 HIR *arg = eval(expression);
497 Handle<Type> given = arg->type();
499 bool mustComputeReference;
500 if (i >= fun->parameters()->length()) {
501 // Special handling for natives. Arguments past the formal must
502 // always have references computed. However, arrays are already
503 // references for natives.
504 assert(fun->isNative() && fun->isNativeVariadic());
505 mustComputeReference = !given->isReference() &&
508 Local<Type> actual(zone_, fun->parameterAt(i));
510 if (expression->isIndexExpression()) {
511 // Temporarily disabled.
512 assert(!actual->isArray());
513 if (actual->isReference()) {
514 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
519 if (actual->isReference()) {
520 // If the actual is a reference, the coercion rules are much
521 // stricter; the contained types must be identical.
522 // :TODO: make this not an assert
523 assert(ReferenceType::cast(actual)->contained() == arg->type());
525 // When we start overloading, coercion will have to happen later.
526 arg = coerce(arg, actual, Coerce_Arg);
531 mustComputeReference = actual->isReference() && !given->isReference();
534 if (mustComputeReference)
535 arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
537 if (!args->append(arg))
541 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
545 SemanticAnalysis::visitAssignment(Assignment *node)
547 HLValue *lval = lvalue(node->lvalue());
551 HIR *hir = eval(node->expression());
552 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
555 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
559 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
562 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
566 // Note, if we re-introduce LIFO allocs, we need to unwind here.
567 __ jump(loop_->break_());
571 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
574 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
578 // Note, if we re-introduce LIFO allocs, we need to unwind here.
579 __ jump(loop_->continue_());
583 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
585 HIR *left = eval(node->left());
589 HIR *right = eval(node->right());
593 // Hrm... yes, for now, let's coerce here.
594 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
595 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
598 // Do not coerce here, there's no reason to yet.
599 if (!left->type()->isArray()) {
600 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
604 hir_ = new (pool_) HIndex(node,
605 ArrayType::cast(left->type())->contained(),
611 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
613 HLValue *lval = lvalue(node->expression());
617 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
623 if (lval->type()->isInt32())
624 rval = new (pool_) HInteger(node, lval->type(), 1);
626 rval = new (pool_) HFloat(node, lval->type(), 1.0);
629 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
631 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
635 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
637 Handle<Type> l = left->type();
638 Handle<Type> r = right->type();
640 if (token >= TOK_PLUS && token <= TOK_SLASH) {
641 // We allow: [float|int32] + [float|int32]
642 if (l->isFloat() && r->isInt32())
644 if (l->isInt32() && r->isFloat())
646 if (l->isInt32() && r->isInt32())
657 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
658 Handle<Type> argGiven,
659 Handle<Type> argActual,
662 if (!argGiven->isArray()) {
663 cc_.reportError(pos, Message_ExpectedArray);
667 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
668 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
670 if (actual->levels() != given->levels()) {
671 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
677 if (actual->isFixedLength()) {
678 if (kind == Coerce_Return || kind == Coerce_Assign) {
679 if (!given->isFixedLength()) {
680 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
684 if (actual->isCharArray()) {
685 // String assignment can have a truncated |given|.
686 if (given->fixedLength() > actual->fixedLength()) {
687 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
691 if (given->fixedLength() != actual->fixedLength()) {
692 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
697 } else if (given->isFixedLength()) {
698 // We do not allow assignments in the form:
701 // Otherwise, the following code could break the size guarantees
702 // of the right-hand side:
712 // Now |x[0]| contains a 3-length array.
714 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
719 if (!given->contained()->isArray() || !actual->contained()->isArray())
722 given = ArrayType::cast(given->contained());
723 actual = ArrayType::cast(actual->contained());
726 // These arrays must contain the same innermost type.
727 if (given->contained() != actual->contained()) {
728 cc_.reportError(pos, Message_TypeMismatch,
729 GetTypeName(actual->contained()),
730 GetTypeName(given->contained()));
738 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
740 Handle<Type> from = hir->type();
742 if (from->isInt32() && to->isFloat())
743 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
744 if (from->isInt32() && to->isBool())
745 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
748 if (!typeCheckArray(SourcePosition(), from, to, kind))
757 SemanticAnalysis::set(VariableSymbol *sym)
759 if (sym->scope()->kind() == Scope::GLOBAL) {
762 assert(sym->storage() == VariableSymbol::Local);
768 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
770 Local<Type> coercion(zone_, coercionType(token, left, right));
773 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
775 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
790 return new (pool_) HBinary(node, left->type(), token, left, right);
801 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
802 return new (pool_) HBinary(node, result, token, left, right);
811 static inline TokenKind
812 ToCompare(Expression *expr)
814 if (expr->isBinaryExpression()) {
815 BinaryExpression *b = expr->toBinaryExpression();
816 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
818 } else if (expr->isUnaryExpression()) {
819 UnaryExpression *u = expr->toUnaryExpression();
820 if (u->token() == TOK_NOT)
827 SemanticAnalysis::visitForTest(Expression *expr,
832 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
834 TokenKind token = ToCompare(expr);
835 if (token == TOK_EOF || token == TOK_NOT) {
837 if (token == TOK_EOF)
840 hir = eval(expr->toUnaryExpression()->expression());
843 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
848 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
849 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
851 if (fallthrough == falseBranch)
852 __ j(op, trueBranch);
854 __ j(op, falseBranch);
858 BinaryExpression *bin = expr->toBinaryExpression();
859 if (token == TOK_AND || token == TOK_OR) {
861 //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
865 HIR *left = eval(bin->left());
866 HIR *right = eval(bin->right());
870 HIR *hir = binary(bin, bin->token(), left, right);
873 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
877 if (fallthrough == trueBranch)
878 __ j(OP_JF, falseBranch);
880 __ j(OP_JT, trueBranch);
884 SemanticAnalysis::lvalue(Expression *expr)
886 HIR *hir = eval(expr);
890 if (!hir->isLValue()) {
891 cc_.reportError(expr->pos(), Message_ExpectedLValue);
895 return static_cast<HLValue *>(hir);
899 SemanticAnalysis::eval(Expression *expr)
911 SemanticAnalysis::discharge(HIR *hir)
913 EmitHIR(zone_, emitter_, hir);