Re-add line and column information to bytecode.
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 // When we start overloading, coercion will have to happen later.
520 arg = coerce(arg, actual, Coerce_Arg);
524 mustComputeReference = actual->isReference() && !given->isReference();
527 // :TODO: handle mustComputeReference
528 assert(!mustComputeReference);
530 if (!args->append(arg))
534 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
538 SemanticAnalysis::visitAssignment(Assignment *node)
540 HLValue *lval = lvalue(node->lvalue());
544 HIR *hir = eval(node->expression());
545 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
548 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
552 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
555 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
559 // Note, if we re-introduce LIFO allocs, we need to unwind here.
560 __ jump(loop_->break_());
564 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
567 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
571 // Note, if we re-introduce LIFO allocs, we need to unwind here.
572 __ jump(loop_->continue_());
576 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
578 HIR *left = eval(node->left());
582 HIR *right = eval(node->right());
586 // Hrm... yes, for now, let's coerce here.
587 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
588 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
591 // Do not coerce here, there's no reason to yet.
592 if (!left->type()->isArray()) {
593 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
597 hir_ = new (pool_) HIndex(node,
598 ArrayType::cast(left->type())->contained(),
604 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
606 HLValue *lval = lvalue(node->expression());
610 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
616 if (lval->type()->isInt32())
617 rval = new (pool_) HInteger(node, lval->type(), 1);
619 rval = new (pool_) HFloat(node, lval->type(), 1.0);
622 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
624 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
628 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
630 Handle<Type> l = left->type();
631 Handle<Type> r = right->type();
633 if (token >= TOK_PLUS && token <= TOK_SLASH) {
634 // We allow: [float|int32] + [float|int32]
635 if (l->isFloat() && r->isInt32())
637 if (l->isInt32() && r->isFloat())
639 if (l->isInt32() && r->isInt32())
649 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
650 Handle<Type> argGiven,
651 Handle<Type> argActual,
654 if (!argGiven->isArray()) {
655 cc_.reportError(pos, Message_ExpectedArray);
659 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
660 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
662 if (actual->levels() != given->levels()) {
663 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
669 if (actual->isFixedLength()) {
670 if (kind == Coerce_Return || kind == Coerce_Assign) {
671 if (!given->isFixedLength()) {
672 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
676 if (actual->isCharArray()) {
677 // String assignment can have a truncated |given|.
678 if (given->fixedLength() > actual->fixedLength()) {
679 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
683 if (given->fixedLength() != actual->fixedLength()) {
684 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
689 } else if (given->isFixedLength()) {
690 // We do not allow assignments in the form:
693 // Otherwise, the following code could break the size guarantees
694 // of the right-hand side:
704 // Now |x[0]| contains a 3-length array.
706 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
711 if (!given->contained()->isArray() || !actual->contained()->isArray())
714 given = ArrayType::cast(given->contained());
715 actual = ArrayType::cast(actual->contained());
718 // These arrays must contain the same innermost type.
719 if (given->contained() != actual->contained()) {
720 cc_.reportError(pos, Message_TypeMismatch,
721 GetTypeName(actual->contained()),
722 GetTypeName(given->contained()));
730 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
732 Handle<Type> from = hir->type();
734 if (from->isInt32() && to->isFloat())
735 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
736 if (from->isInt32() && to->isBool())
737 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
740 if (!typeCheckArray(SourcePosition(), from, to, kind))
751 SemanticAnalysis::set(VariableSymbol *sym)
753 if (sym->scope()->kind() == Scope::GLOBAL) {
756 assert(sym->storage() == VariableSymbol::Local);
762 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
764 Local<Type> coercion(zone_, coercionType(token, left, right));
767 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
769 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
784 return new (pool_) HBinary(node, left->type(), token, left, right);
795 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
796 return new (pool_) HBinary(node, result, token, left, right);
805 static inline TokenKind
806 ToCompare(Expression *expr)
808 if (expr->isBinaryExpression()) {
809 BinaryExpression *b = expr->toBinaryExpression();
810 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
812 } else if (expr->isUnaryExpression()) {
813 UnaryExpression *u = expr->toUnaryExpression();
814 if (u->token() == TOK_NOT)
821 SemanticAnalysis::visitForTest(Expression *expr,
826 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
828 TokenKind token = ToCompare(expr);
829 if (token == TOK_EOF || token == TOK_NOT) {
831 if (token == TOK_EOF)
834 hir = eval(expr->toUnaryExpression()->expression());
837 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
842 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
843 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
845 if (fallthrough == falseBranch)
846 __ j(op, trueBranch);
848 __ j(op, falseBranch);
852 BinaryExpression *bin = expr->toBinaryExpression();
853 if (token == TOK_AND || token == TOK_OR) {
855 //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
859 HIR *left = eval(bin->left());
860 HIR *right = eval(bin->right());
864 HIR *hir = binary(bin, bin->token(), left, right);
867 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
871 if (fallthrough == trueBranch)
872 __ j(OP_JF, falseBranch);
874 __ j(OP_JT, trueBranch);
878 SemanticAnalysis::lvalue(Expression *expr)
880 HIR *hir = eval(expr);
884 if (!hir->isLValue()) {
885 cc_.reportError(expr->pos(), Message_ExpectedLValue);
889 return static_cast<HLValue *>(hir);
893 SemanticAnalysis::eval(Expression *expr)
905 SemanticAnalysis::discharge(HIR *hir)
907 EmitHIR(zone_, emitter_, hir);