Added array support back.
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));
155 SemanticAnalysis::compile(FunctionStatement *stmt)
157 __ setFirstLine(stmt->pos().line);
159 AutoEnterScope argScope(&scope_, stmt->argScope());
160 AutoEnterScope varScope(&scope_, stmt->varScope());
162 stmt->body()->accept(this);
164 Local<Code> code(zone_, __ finish());
167 code->setModule(module_);
169 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
174 // Disassemble(code, stdout);
181 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
183 AutoEnterScope scope(&scope_, node->scope());
185 for (size_t i = 0; i < node->statements()->length(); i++) {
186 Statement *stmt = node->statements()->at(i);
188 assert(__ stackDepth() == 0);
193 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
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_);
200 HIR *hir = eval(node->expression());
209 SemanticAnalysis::visitIfStatement(IfStatement *node)
213 if (!node->ifFalse()) {
216 visitForTest(node->condition(), &success, &join, &success);
218 node->ifTrue()->accept(this);
222 visitForTest(node->condition(), &success, &next, &success);
224 node->ifTrue()->accept(this);
227 node->ifFalse()->accept(this);
234 SemanticAnalysis::visitForStatement(ForStatement *node)
236 AutoEnterScope scope(&scope_, node->scope());
237 PoolScope poolScope(zone_->pool());
238 RootScope rootScope(zone_);
241 LoopScope loop(scope_, &join, &update, &loop_);
243 if (node->initialization())
244 node->initialization()->accept(this);
247 if (node->condition())
251 node->body()->accept(this);
255 node->update()->accept(this);
257 if (node->condition()) {
259 visitForTest(node->condition(), &header, &join, &join);
266 assert(__ stackDepth() == 0);
270 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
272 PoolScope poolScope(zone_->pool());
273 RootScope rootScope(zone_);
279 LoopScope loop(scope_, &join, &header, &loop_);
280 if (node->token() == TOK_WHILE) {
282 visitForTest(node->condition(), &body, &join, &body);
283 node->body()->accept(this);
286 node->body()->accept(this);
287 visitForTest(node->condition(), &header, &join, &join);
292 assert(__ stackDepth() == 0);
295 static inline Heap::Tenure
296 InferTenure(Symbol *sym)
298 if (sym->scope()->kind() == Scope::GLOBAL)
299 return Heap::Tenure_Old;
300 // :TODO: need to use LIFO!
301 return Heap::Tenure_Default;
305 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
307 PoolScope poolScope(zone_->pool());
308 RootScope rootScope(zone_);
310 if (node->initialization()) {
313 if ((hir = eval(node->initialization())) == NULL)
315 if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
320 if (node->sym()->type()->isInt32() ||
321 node->sym()->type()->isEnum() ||
322 node->sym()->type()->isChar() ||
323 node->sym()->type()->isBool())
326 } else if (node->sym()->type()->isFloat()) {
328 } else if (node->sym()->type()->isArray()) {
329 Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
330 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
334 if (type->isFixedLength()) {
335 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
336 } else if (node->dims()) {
338 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
340 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
345 if (!__ allocate(node->sym()))
353 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
355 if (!node->expression()) {
356 if (!fun_->returnType()->isVoid()) {
357 cc_.reportError(node->pos(), Message_UsedVoidReturn);
365 PoolScope poolScope(zone_->pool());
366 RootScope rootScope(zone_);
368 HIR *hir = eval(node->expression());
372 Local<Type> returnType(zone_, fun_->returnType());
373 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
381 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
383 HIR *left = eval(node->left());
384 HIR *right = eval(node->right());
388 hir_ = binary(node->token(), left, right);
392 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
394 if (type->parameters()->length() == actual)
397 if (actual > type->parameters()->length()) {
398 if (!type->isNative() || !type->isNativeVariadic())
403 if (!type->defaults())
406 // Missing arguments. See if there's a default argument for each missing
408 for (unsigned i = actual; i < type->parameters()->length(); i++) {
409 if (!type->defaults()->at(i))
417 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
419 Symbol *sym = proxy->sym();
420 VariableSymbol *var = sym->asVariable();
422 Scope *in = sym->scope();
423 switch (in->kind()) {
425 hir_ = new (pool_) HGlobal(sym);
429 assert(in->kind() == Scope::BLOCK);
430 assert(var->storage() == VariableSymbol::Local);
431 hir_ = new (pool_) HLocal(var);
437 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
439 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
440 hir_ = new (pool_) HInteger(type, lit->value());
444 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
446 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
447 hir_ = new (pool_) HFloat(type, (float)node->value());
451 SemanticAnalysis::visitCallExpression(CallExpression *node)
453 HIR *callee = eval(node->callee());
457 if (!callee->type()->isFunction()) {
458 cc_.reportError(node->pos(), Message_CalleeNotFunction);
462 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
464 if (!checkArgumentCount(fun, node->arguments()->length())) {
465 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
469 if (fun->isForward()) {
470 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
474 HIRList *args = new (pool_) HIRList;
475 for (unsigned i = 0; i < node->arguments()->length(); i++) {
476 Expression *expression = node->arguments()->at(i);
477 HIR *arg = eval(expression);
481 Handle<Type> given = arg->type();
483 bool mustComputeReference;
484 if (i >= fun->parameters()->length()) {
485 // Special handling for natives. Arguments past the formal must
486 // always have references computed. However, arrays are already
487 // references for natives.
488 assert(fun->isNative() && fun->isNativeVariadic());
489 mustComputeReference = !given->isReference() &&
492 Local<Type> actual(zone_, fun->parameterAt(i));
494 if (expression->isIndexExpression()) {
495 // Temporarily disabled.
496 assert(!actual->isArray());
497 if (actual->isReference()) {
498 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
503 // When we start overloading, coercion will have to happen later.
504 arg = coerce(arg, actual, Coerce_Arg);
508 mustComputeReference = actual->isReference() && !given->isReference();
511 // :TODO: handle mustComputeReference
512 assert(!mustComputeReference);
514 if (!args->append(arg))
518 hir_ = new (pool_) HCall(fun->returnType(), callee, args);
522 SemanticAnalysis::visitAssignment(Assignment *node)
524 HLValue *lval = lvalue(node->lvalue());
528 HIR *hir = eval(node->expression());
529 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
532 hir_ = new (pool_) HStore(lval, hir);
536 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
539 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
543 // Note, if we re-introduce LIFO allocs, we need to unwind here.
544 __ jump(loop_->break_());
548 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
551 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
555 // Note, if we re-introduce LIFO allocs, we need to unwind here.
556 __ jump(loop_->continue_());
560 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
562 HIR *left = eval(node->left());
566 HIR *right = eval(node->right());
570 // Hrm... yes, for now, let's coerce here.
571 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
572 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
575 // Do not coerce here, there's no reason to yet.
576 if (!left->type()->isArray()) {
577 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
581 hir_ = new (pool_) HIndex(ArrayType::cast(left->type())->contained(),
587 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
589 Handle<Type> l = left->type();
590 Handle<Type> r = right->type();
592 if (token >= TOK_PLUS && token <= TOK_SLASH) {
593 // We allow: [float|int32] + [float|int32]
594 if (l->isFloat() && r->isInt32())
596 if (l->isInt32() && r->isFloat())
598 if (l->isInt32() && r->isInt32())
608 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
610 Handle<Type> from = hir->type();
612 if (from->isInt32() && to->isFloat())
613 return new (pool_) HConvert(to, OP_CVT_I2F, hir);
614 if (from->isInt32() && to->isBool())
615 return new (pool_) HConvert(to, OP_CVT_I2B, hir);
623 SemanticAnalysis::set(VariableSymbol *sym)
625 if (sym->scope()->kind() == Scope::GLOBAL) {
628 assert(sym->storage() == VariableSymbol::Local);
634 SemanticAnalysis::binary(TokenKind token, HIR *left, HIR *right)
636 Local<Type> coercion(zone_, coercionType(token, left, right));
639 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
641 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
656 return new (pool_) HBinary(left->type(), token, left, right);
667 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
668 return new (pool_) HBinary(result, token, left, right);
677 static inline TokenKind
678 ToCompare(Expression *expr)
680 if (expr->isBinaryExpression()) {
681 BinaryExpression *b = expr->toBinaryExpression();
682 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
684 } else if (expr->isUnaryExpression()) {
685 UnaryExpression *u = expr->toUnaryExpression();
686 if (u->token() == TOK_NOT)
693 SemanticAnalysis::visitForTest(Expression *expr,
698 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
700 TokenKind token = ToCompare(expr);
701 if (token == TOK_EOF || token == TOK_NOT) {
703 if (token == TOK_EOF)
706 hir = eval(expr->toUnaryExpression()->expression());
709 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
714 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
715 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
717 if (fallthrough == falseBranch)
718 __ j(op, trueBranch);
720 __ j(op, falseBranch);
724 BinaryExpression *bin = expr->toBinaryExpression();
725 if (token == TOK_AND || token == TOK_OR) {
727 //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
731 HIR *left = eval(bin->left());
732 HIR *right = eval(bin->right());
736 HIR *hir = binary(bin->token(), left, right);
739 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
743 if (fallthrough == trueBranch)
744 __ j(OP_JF, falseBranch);
746 __ j(OP_JT, trueBranch);
750 SemanticAnalysis::lvalue(Expression *expr)
752 HIR *hir = eval(expr);
756 if (!hir->isLValue()) {
757 cc_.reportError(expr->pos(), Message_ExpectedLValue);
761 return static_cast<HLValue *>(hir);
765 SemanticAnalysis::eval(Expression *expr)
777 SemanticAnalysis::discharge(HIR *hir)
779 EmitHIR(zone_, emitter_, hir);