Re-added parameter support.
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);
197 assert(__ stackDepth() == 0);
202 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
204 // While building HIR, we enter new pool and root scopes, since HIR
205 // creation is purely temporary.
206 PoolScope poolScope(zone_->pool());
207 RootScope rootScope(zone_);
209 HIR *hir = eval(node->expression());
214 if (!hir->type()->isVoid())
219 SemanticAnalysis::visitIfStatement(IfStatement *node)
223 if (!node->ifFalse()) {
226 visitForTest(node->condition(), &success, &join, &success);
228 node->ifTrue()->accept(this);
232 visitForTest(node->condition(), &success, &next, &success);
234 node->ifTrue()->accept(this);
237 node->ifFalse()->accept(this);
244 SemanticAnalysis::visitForStatement(ForStatement *node)
246 AutoEnterScope scope(&scope_, node->scope());
247 PoolScope poolScope(zone_->pool());
248 RootScope rootScope(zone_);
251 LoopScope loop(scope_, &join, &update, &loop_);
253 if (node->initialization())
254 node->initialization()->accept(this);
257 if (node->condition())
261 node->body()->accept(this);
265 node->update()->accept(this);
267 if (node->condition()) {
269 visitForTest(node->condition(), &header, &join, &join);
276 assert(__ stackDepth() == 0);
280 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
282 PoolScope poolScope(zone_->pool());
283 RootScope rootScope(zone_);
289 LoopScope loop(scope_, &join, &header, &loop_);
290 if (node->token() == TOK_WHILE) {
292 visitForTest(node->condition(), &body, &join, &body);
293 node->body()->accept(this);
296 node->body()->accept(this);
297 visitForTest(node->condition(), &header, &join, &join);
302 assert(__ stackDepth() == 0);
305 static inline Heap::Tenure
306 InferTenure(Symbol *sym)
308 if (sym->scope()->kind() == Scope::GLOBAL)
309 return Heap::Tenure_Old;
310 // :TODO: need to use LIFO!
311 return Heap::Tenure_Default;
315 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
317 PoolScope poolScope(zone_->pool());
318 RootScope rootScope(zone_);
320 if (node->initialization()) {
323 if ((hir = eval(node->initialization())) == NULL)
325 if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
330 if (node->sym()->type()->isInt32() ||
331 node->sym()->type()->isEnum() ||
332 node->sym()->type()->isChar() ||
333 node->sym()->type()->isBool())
336 } else if (node->sym()->type()->isFloat()) {
338 } else if (node->sym()->type()->isArray()) {
339 Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
340 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
344 if (type->isFixedLength()) {
345 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
346 } else if (node->dims()) {
348 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
350 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
355 if (!__ allocate(node->sym()))
363 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
365 if (!node->expression()) {
366 if (!fun_->returnType()->isVoid()) {
367 cc_.reportError(node->pos(), Message_UsedVoidReturn);
375 PoolScope poolScope(zone_->pool());
376 RootScope rootScope(zone_);
378 HIR *hir = eval(node->expression());
382 Local<Type> returnType(zone_, fun_->returnType());
383 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
391 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
393 HIR *left = eval(node->left());
394 HIR *right = eval(node->right());
398 hir_ = binary(node->token(), left, right);
402 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
404 if (type->parameters()->length() == actual)
407 if (actual > type->parameters()->length()) {
408 if (!type->isNative() || !type->isNativeVariadic())
413 if (!type->defaults())
416 // Missing arguments. See if there's a default argument for each missing
418 for (unsigned i = actual; i < type->parameters()->length(); i++) {
419 if (!type->defaults()->at(i))
427 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
429 Symbol *sym = proxy->sym();
430 VariableSymbol *var = sym->asVariable();
432 Scope *in = sym->scope();
433 switch (in->kind()) {
435 hir_ = new (pool_) HGlobal(sym);
438 case Scope::FUNCTION:
439 assert(var->storage() == VariableSymbol::Arg);
440 hir_ = new (pool_) HLocal(var);
444 assert(in->kind() == Scope::BLOCK);
445 assert(var->storage() == VariableSymbol::Local);
446 hir_ = new (pool_) HLocal(var);
452 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
454 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
455 hir_ = new (pool_) HInteger(type, lit->value());
459 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
461 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
462 hir_ = new (pool_) HFloat(type, (float)node->value());
466 SemanticAnalysis::visitCallExpression(CallExpression *node)
468 HIR *callee = eval(node->callee());
472 if (!callee->type()->isFunction()) {
473 cc_.reportError(node->pos(), Message_CalleeNotFunction);
477 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
479 if (!checkArgumentCount(fun, node->arguments()->length())) {
480 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
484 if (fun->isForward()) {
485 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
489 HIRList *args = new (pool_) HIRList;
490 for (unsigned i = 0; i < node->arguments()->length(); i++) {
491 Expression *expression = node->arguments()->at(i);
492 HIR *arg = eval(expression);
496 Handle<Type> given = arg->type();
498 bool mustComputeReference;
499 if (i >= fun->parameters()->length()) {
500 // Special handling for natives. Arguments past the formal must
501 // always have references computed. However, arrays are already
502 // references for natives.
503 assert(fun->isNative() && fun->isNativeVariadic());
504 mustComputeReference = !given->isReference() &&
507 Local<Type> actual(zone_, fun->parameterAt(i));
509 if (expression->isIndexExpression()) {
510 // Temporarily disabled.
511 assert(!actual->isArray());
512 if (actual->isReference()) {
513 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
518 // When we start overloading, coercion will have to happen later.
519 arg = coerce(arg, actual, Coerce_Arg);
523 mustComputeReference = actual->isReference() && !given->isReference();
526 // :TODO: handle mustComputeReference
527 assert(!mustComputeReference);
529 if (!args->append(arg))
533 hir_ = new (pool_) HCall(fun->returnType(), callee, args);
537 SemanticAnalysis::visitAssignment(Assignment *node)
539 HLValue *lval = lvalue(node->lvalue());
543 HIR *hir = eval(node->expression());
544 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
547 hir_ = new (pool_) HStore(node->token(), lval, hir);
551 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
554 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
558 // Note, if we re-introduce LIFO allocs, we need to unwind here.
559 __ jump(loop_->break_());
563 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
566 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
570 // Note, if we re-introduce LIFO allocs, we need to unwind here.
571 __ jump(loop_->continue_());
575 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
577 HIR *left = eval(node->left());
581 HIR *right = eval(node->right());
585 // Hrm... yes, for now, let's coerce here.
586 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
587 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
590 // Do not coerce here, there's no reason to yet.
591 if (!left->type()->isArray()) {
592 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
596 hir_ = new (pool_) HIndex(ArrayType::cast(left->type())->contained(),
602 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
604 HLValue *lval = lvalue(node->expression());
608 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
614 if (lval->type()->isInt32())
615 rval = new (pool_) HInteger(lval->type(), 1);
617 rval = new (pool_) HFloat(lval->type(), 1.0);
620 hir_ = new (pool_) HPostIncDec(node->token(), lval, rval);
622 hir_ = new (pool_) HStore(node->token(), lval, rval);
626 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
628 Handle<Type> l = left->type();
629 Handle<Type> r = right->type();
631 if (token >= TOK_PLUS && token <= TOK_SLASH) {
632 // We allow: [float|int32] + [float|int32]
633 if (l->isFloat() && r->isInt32())
635 if (l->isInt32() && r->isFloat())
637 if (l->isInt32() && r->isInt32())
647 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
648 Handle<Type> argGiven,
649 Handle<Type> argActual,
652 if (!argGiven->isArray()) {
653 cc_.reportError(pos, Message_ExpectedArray);
657 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
658 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
660 if (actual->levels() != given->levels()) {
661 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
667 if (actual->isFixedLength()) {
668 if (kind == Coerce_Return || kind == Coerce_Assign) {
669 if (!given->isFixedLength()) {
670 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
674 if (actual->isCharArray()) {
675 // String assignment can have a truncated |given|.
676 if (given->fixedLength() > actual->fixedLength()) {
677 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
681 if (given->fixedLength() != actual->fixedLength()) {
682 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
687 } else if (given->isFixedLength()) {
688 // We do not allow assignments in the form:
691 // Otherwise, the following code could break the size guarantees
692 // of the right-hand side:
702 // Now |x[0]| contains a 3-length array.
704 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
709 if (!given->contained()->isArray() || !actual->contained()->isArray())
712 given = ArrayType::cast(given->contained());
713 actual = ArrayType::cast(actual->contained());
716 // These arrays must contain the same innermost type.
717 if (given->contained() != actual->contained()) {
718 cc_.reportError(pos, Message_TypeMismatch,
719 GetTypeName(actual->contained()),
720 GetTypeName(given->contained()));
728 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
730 Handle<Type> from = hir->type();
732 if (from->isInt32() && to->isFloat())
733 return new (pool_) HConvert(to, OP_CVT_I2F, hir);
734 if (from->isInt32() && to->isBool())
735 return new (pool_) HConvert(to, OP_CVT_I2B, hir);
738 if (!typeCheckArray(SourcePosition(), from, to, kind))
747 SemanticAnalysis::set(VariableSymbol *sym)
749 if (sym->scope()->kind() == Scope::GLOBAL) {
752 assert(sym->storage() == VariableSymbol::Local);
758 SemanticAnalysis::binary(TokenKind token, HIR *left, HIR *right)
760 Local<Type> coercion(zone_, coercionType(token, left, right));
763 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
765 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
780 return new (pool_) HBinary(left->type(), token, left, right);
791 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
792 return new (pool_) HBinary(result, token, left, right);
801 static inline TokenKind
802 ToCompare(Expression *expr)
804 if (expr->isBinaryExpression()) {
805 BinaryExpression *b = expr->toBinaryExpression();
806 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
808 } else if (expr->isUnaryExpression()) {
809 UnaryExpression *u = expr->toUnaryExpression();
810 if (u->token() == TOK_NOT)
817 SemanticAnalysis::visitForTest(Expression *expr,
822 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
824 TokenKind token = ToCompare(expr);
825 if (token == TOK_EOF || token == TOK_NOT) {
827 if (token == TOK_EOF)
830 hir = eval(expr->toUnaryExpression()->expression());
833 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
838 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
839 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
841 if (fallthrough == falseBranch)
842 __ j(op, trueBranch);
844 __ j(op, falseBranch);
848 BinaryExpression *bin = expr->toBinaryExpression();
849 if (token == TOK_AND || token == TOK_OR) {
851 //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
855 HIR *left = eval(bin->left());
856 HIR *right = eval(bin->right());
860 HIR *hir = binary(bin->token(), left, right);
863 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
867 if (fallthrough == trueBranch)
868 __ j(OP_JF, falseBranch);
870 __ j(OP_JT, trueBranch);
874 SemanticAnalysis::lvalue(Expression *expr)
876 HIR *hir = eval(expr);
880 if (!hir->isLValue()) {
881 cc_.reportError(expr->pos(), Message_ExpectedLValue);
885 return static_cast<HLValue *>(hir);
889 SemanticAnalysis::eval(Expression *expr)
901 SemanticAnalysis::discharge(HIR *hir)
903 EmitHIR(zone_, emitter_, hir);