Fix linux/mac 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)
71 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
72 : zone_(parent->zone_),
77 scope_(parent->scope_),
87 SemanticAnalysis::analyze()
89 scope_ = unit_->globalScope();
91 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
92 Statement *stmt = unit_->tree()->statements()->at(i);
96 Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
99 unit_->module()->setGlobals(globals);
101 Local<Code> code(zone_, __ finish());
104 code->setModule(unit_->module());
105 unit_->module()->setCode(code);
108 // Disassemble(code, stdout);
113 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
115 FunctionSymbol *sym = stmt->sym();
116 Local<FunctionType> type(zone_, sym->type());
118 assert(scope_->kind() == Scope::GLOBAL);
120 if (stmt->token() == TOK_NATIVE) {
121 // Define the native now.
123 if (!zone_->nativeTable()->add(stmt->name(), &index))
126 Local<Native> native(zone_, Native::New(zone_, type, index));
135 // If the function is a forward or native, we don't have to do anything.
136 if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
139 SemanticAnalysis child(this, type);
140 Local<Function> funobj(zone_, child.compile(stmt));
146 if (stmt->token() == TOK_PUBLIC)
153 SemanticAnalysis::compile(FunctionStatement *stmt)
155 __ setFirstLine(stmt->pos().line);
157 AutoEnterScope argScope(&scope_, stmt->argScope());
159 for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
160 Parameter *param = stmt->signature().parameters()->at(i);
161 param->sym()->allocate(VariableSymbol::Arg, i);
164 AutoEnterScope varScope(&scope_, stmt->varScope());
165 ControlStatus status = visitForControl(stmt->body());
167 if (!fun_->returnType()->isVoid()) {
168 // If the function is not void, report if not all paths return a value.
169 // All other incorrect return cases have been caught already.
170 if (status.returns() == Returns_Sometimes) {
171 cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
175 if (status.returns() == Returns_Never) {
176 cc_.reportError(stmt->pos(), Message_MissingReturnValue);
181 Local<Code> code(zone_, __ finish());
184 code->setModule(unit_->module());
186 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
191 // Disassemble(code, stdout);
198 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
200 AutoEnterScope scope(&scope_, node->scope());
202 for (size_t i = 0; i < node->statements()->length(); i++) {
203 Statement *stmt = node->statements()->at(i);
204 __ note_position(stmt->pos());
206 assert(__ stackDepth() == 0);
211 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
216 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
218 // While building HIR, we enter new pool and root scopes, since HIR
219 // creation is purely temporary.
220 PoolScope poolScope(zone_->pool());
221 RootScope rootScope(zone_);
223 HIR *hir = eval(node->expression());
228 if (!hir->type()->isVoid())
233 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
235 // If both sides terminate in a return, we consider this a return as well.
236 if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
237 terminate(Returns_Always);
241 ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
245 if (left.terminates() && right.terminates())
251 SemanticAnalysis::ControlStatus
252 SemanticAnalysis::visitForControl(Statement *statement)
254 ControlScope scope(&control_);
255 statement->accept(this);
256 return scope.status();
260 SemanticAnalysis::visitIfStatement(IfStatement *node)
264 ControlStatus trueBranch;
265 ControlStatus falseBranch(false, Returns_Never);
267 if (!node->ifFalse()) {
270 visitForTest(node->condition(), &success, &join, &success);
272 trueBranch = visitForControl(node->ifTrue());
276 visitForTest(node->condition(), &success, &next, &success);
278 trueBranch = visitForControl(node->ifTrue());
281 falseBranch = visitForControl(node->ifFalse());
286 control_->merge(trueBranch, falseBranch);
290 SemanticAnalysis::requireLifoStack()
295 loop_->setUsesLifoStack();
298 SemanticAnalysis::ControlStatus
299 SemanticAnalysis::visitLoopBody(Statement *stmt)
301 // We always mark off a loop body, so on each edge, we can balance the
302 // LIFO stack. Right now, we don't have the ability to budget the LIFO
303 // stack ahead of time. If we turn out to never need the LIFO stack, we
304 // mark it as unnecessary. (The interpreter can't really make use of this,
307 // Note that balancing the LIFO stack isn't even necessary, so this
308 // feature may be removed. All this mechanism does is mitigate the
309 // possibility that a long-running loop will overflow the LIFO region
310 // and therefore start requiring nursery allocations.
311 int pos = __ enterloop();
312 ControlStatus status = visitForControl(stmt);
315 if (loop_->usesLifoStack())
316 __ setLoopUsesLifoStack(pos);
322 SemanticAnalysis::visitForStatement(ForStatement *node)
324 AutoEnterScope scope(&scope_, node->scope());
325 PoolScope poolScope(zone_->pool());
326 RootScope rootScope(zone_);
329 LoopScope loop(scope_, &join, &update, &loop_);
331 if (node->initialization())
332 node->initialization()->accept(this);
335 if (node->condition())
339 ControlStatus status = visitLoopBody(node->body());
343 node->update()->accept(this);
345 if (node->condition()) {
347 visitForTest(node->condition(), &header, &join, &join);
354 // If there was a condition, we treat this like a while loop. Otherwise,
355 // the join point is only reachable if the loop contains a break. The
356 // termination status doesn't tell us anything yet.
357 if (node->condition() || loop.breaks())
358 control_->merge(status, ControlStatus(false, Returns_Never));
360 control_->terminate(status.returns());
362 assert(__ stackDepth() == 0);
366 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
368 PoolScope poolScope(zone_->pool());
369 RootScope rootScope(zone_);
375 ControlStatus status;
377 LoopScope loop(scope_, &join, &header, &loop_);
378 if (node->token() == TOK_WHILE) {
380 visitForTest(node->condition(), &body, &join, &body);
381 status = visitLoopBody(node->body());
384 status = visitLoopBody(node->body());
385 visitForTest(node->condition(), &header, &join, &join);
390 // Detect loops that will always have a fork in the contro-flow graph.
391 // This will be a |while| loop, or a |do-while| loop whose body does
392 // not terminate. For now, we treat these as an |if| regardless of the
393 // direction the branch can take. That means the control-flow is always
395 if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
396 control_->merge(status, ControlStatus(false, Returns_Never));
398 // At this point, we've got a do-while loop with a |return| or
399 // |continue|, meaning that the rest of the block is unreachable.
400 control_->terminate(status.returns());
403 assert(__ stackDepth() == 0);
406 static inline Heap::Tenure
407 InferTenure(Symbol *sym)
409 if (sym->scope()->kind() == Scope::GLOBAL)
410 return Heap::Tenure_Old;
412 // SP2's array semantics allow any array kind to escape, so we must use
413 // the normal heap. (Hopefully escape analysis can ease this pain later).
414 if (sym->type()->isArray())
415 return Heap::Tenure_Default;
417 return Heap::Tenure_Default;
421 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
423 PoolScope poolScope(zone_->pool());
424 RootScope rootScope(zone_);
426 Local<Type> type(zone_, node->sym()->type());
428 if (node->sym()->type()->isVoid()) {
429 cc_.reportError(node->type()->pos(), Message_CannotDeclareVoid);
433 if (node->initialization()) {
436 if ((hir = eval(node->initialization())) == NULL)
438 if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
443 if (type->isInt32() || type->isEnum() ||
444 type->isChar() || type->isBool())
447 } else if (type->isFloat()) {
449 } else if (type->isArray()) {
450 Local<ArrayType> atype(zone_, ArrayType::cast(type));
451 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, atype));
455 if (atype->isFixedLength()) {
456 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
457 } else if (node->dims()->at(0)) {
458 // This may not be true if we allow typedefing, so :TODO:
459 // figure out proper semantics.
460 assert(node->dims()->length() == atype->levels());
462 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
463 for (size_t i = 0; i < node->dims()->length(); i++) {
464 Expression *expr = node->dims()->at(i);
466 HIR *hir = eval(expr);
467 if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
474 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
476 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
483 if (node->sym()->scope()->kind() != Scope::GLOBAL) {
484 if (!__ allocate(node->sym()))
493 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
495 control_->returns(Returns_Always);
497 if (!node->expression()) {
498 if (!fun_->returnType()->isVoid()) {
499 cc_.reportError(node->pos(), Message_MissingReturnValue);
507 if (fun_->returnType()->isVoid()) {
508 cc_.reportError(node->pos(), Message_UsedVoidReturn);
512 PoolScope poolScope(zone_->pool());
513 RootScope rootScope(zone_);
515 HIR *hir = eval(node->expression());
519 Local<Type> returnType(zone_, fun_->returnType());
520 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
525 if (hir->type()->isVoid())
532 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
534 HIR *left = eval(node->left());
535 HIR *right = eval(node->right());
539 hir_ = binary(node, node->token(), left, right);
543 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
545 if (type->parameters()->length() == actual)
548 if (actual > type->parameters()->length()) {
549 if (!type->isNative() || !type->isNativeVariadic())
554 if (!type->defaults())
557 // Missing arguments. See if there's a default argument for each missing
559 for (unsigned i = actual; i < type->parameters()->length(); i++) {
560 if (!type->defaults()->at(i))
568 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
570 Symbol *sym = proxy->sym();
572 switch (sym->kind()) {
573 case Symbol::kConstant:
575 ConstantSymbol *val = sym->toConstant();
576 hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
580 // This is kind of screwy. Symbol::kFunction is like a constant we can't
581 // evaluate yet. Maybe we should extract the GLOBAL case and say that
582 // kFunction is only used for global functions (and use const vars for
584 case Symbol::kFunction:
585 case Symbol::kVariable:
587 Scope *in = sym->scope();
588 switch (in->kind()) {
590 hir_ = new (pool_) HGlobal(proxy, sym);
593 case Scope::FUNCTION:
595 VariableSymbol *var = sym->toVariable();
596 assert(var->storage() == VariableSymbol::Arg);
597 hir_ = new (pool_) HLocal(proxy, var);
603 VariableSymbol *var = sym->toVariable();
604 assert(in->kind() == Scope::BLOCK);
605 assert(var->storage() == VariableSymbol::Local);
606 hir_ = new (pool_) HLocal(proxy, var);
620 SemanticAnalysis::visitBooleanLiteral(BooleanLiteral *node)
622 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
623 hir_ = new (pool_) HBoolean(node, type, node->token() == TOK_TRUE);
627 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
629 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
630 hir_ = new (pool_) HInteger(lit, type, lit->value());
634 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
636 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
637 hir_ = new (pool_) HFloat(node, type, (float)node->value());
641 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
643 Type *type = zone_->types()->getString();
644 hir_ = new (pool_) HString(node, type, node->string());
648 SemanticAnalysis::visitCallExpression(CallExpression *node)
650 HIR *callee = eval(node->callee());
654 if (!callee->type()->isFunction()) {
655 cc_.reportError(node->pos(), Message_CalleeNotFunction);
659 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
661 if (!checkArgumentCount(fun, node->arguments()->length())) {
662 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
666 if (fun->isForward()) {
667 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
671 HIRList *args = new (pool_) HIRList;
672 for (unsigned i = 0; i < node->arguments()->length(); i++) {
673 Expression *expression = node->arguments()->at(i);
674 HIR *arg = eval(expression);
678 Handle<Type> given = arg->type();
680 bool mustComputeReference;
681 if (i >= fun->parameters()->length()) {
682 // Special handling for natives. Arguments past the formal must
683 // always have references computed. However, arrays are already
684 // references for natives.
685 assert(fun->isNative() && fun->isNativeVariadic());
686 mustComputeReference = !given->isReference() &&
689 Local<Type> actual(zone_, fun->parameterAt(i));
692 if (expression->isIndexExpression() && arg->isIndex()) {
693 // If the expression is the form x[y], and this produced a
694 // normal array indexing operation, then we apply some
697 if (actual->isReference()) {
698 // Disabled, since this doesn't have easily definable or
699 // sensible semantics with SP2 arrays, but we don't want
700 // to silently break SP1 semantics.
701 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
705 // As a special rule to account for SP1 semantics, we allow x[y]
706 // to automatically compute a sliced, read-only array view if
707 // the desired type is an array of one more dimension than x[y]
710 // As an additional restriction, this is only allowed for
711 // one-level char arrays, to minimize potential issues until
712 // we determine whether more compatibility is needed.
714 // Internally, for sanity, the dependent array operation does
715 // not necessarily create a dependent array. For extensible
716 // arrays, we instead create a duplicate arrary of just the
717 // sliced portion, rather than deal with the complexity of the
718 // source array being resized.
720 // Note that we don't really know whether a dependent array
721 // will be dependent at compile-time, so the dependent type's
722 // just inherits from the source.
723 if (actual->isArray()) {
724 HIndex *index = arg->toIndex();
725 Local<ArrayType> basetype(zone_, ArrayType::cast(index->base()->type()));
726 Local<ArrayType> atype(zone_, ArrayType::cast(actual));
728 if (atype->isCharArray() && basetype->isCharArray()) {
729 // There is no possible way this will type check, so
730 // it's safe to just try something completely
732 Local<Type> slicetype(zone_);
733 if (basetype->isFixedLength()) {
734 // If the base type is fixed length, we need to
735 // compute a new dynamic array type based on the
736 // fixed array's contents and qualifiers.
737 Local<Type> contained(zone_, basetype->contained());
738 slicetype = zone_->types()->newArray(contained, ArrayType::DYNAMIC_ARRAY_SIZE);
741 slicetype = zone_->types()->qualify(slicetype, basetype->quals());
745 slicetype = basetype;
747 arg = new (pool_) HNewDependentArray(expression, slicetype, index->base(), index->index());
753 if (actual->isReference()) {
754 // If the actual is a reference, the coercion rules are much
755 // stricter; the contained types must be identical.
756 // :TODO: make this not an assert
757 assert(ReferenceType::cast(actual)->contained() == arg->type());
759 // When we start overloading, coercion will have to happen later.
760 arg = coerce(arg, actual, Coerce_Arg);
765 mustComputeReference = actual->isReference() && !given->isReference();
768 if (mustComputeReference) {
769 // Refs always use the LIFO stack if they can.
770 arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
774 if (!args->append(arg))
778 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
782 SemanticAnalysis::visitAssignment(Assignment *node)
784 HLValue *lval = lvalue(node->lvalue());
788 if (lval->type()->quals() & TypeQual_Const) {
789 cc_.reportError(node->pos(), Message_CannotModifyConst);
793 HIR *hir = eval(node->expression());
796 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
799 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
803 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
806 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
811 __ j(OP_BREAK, loop_->break_());
815 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
818 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
822 __ j(OP_CONTINUE, loop_->continue_());
826 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
828 HIR *left = eval(node->left());
832 HIR *right = eval(node->right());
836 // Hrm... yes, for now, let's coerce here.
837 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
838 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
841 // Do not coerce here, there's no reason to yet.
842 if (!left->type()->isArray()) {
843 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
847 hir_ = new (pool_) HIndex(node,
848 ArrayType::cast(left->type())->contained(),
854 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
856 HLValue *lval = lvalue(node->expression());
860 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
866 if (lval->type()->isInt32())
867 rval = new (pool_) HInteger(node, lval->type(), 1);
869 rval = new (pool_) HFloat(node, lval->type(), 1.0);
872 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
874 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
878 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
880 Local<Type> l(zone_, left->type());
881 Local<Type> r(zone_, right->type());
884 l = l->unqualified();
886 r = r->unqualified();
888 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
889 (token >= TOK_EQUALS && token <= TOK_GE))
891 // We allow: [float|int32] + [float|int32]
892 if (l->isFloat() && r->isInt32())
894 if (l->isInt32() && r->isFloat())
896 if (l->isInt32() && r->isInt32())
899 if (l->isChar() && r->isInt32())
901 if (l->isInt32() && r->isChar())
912 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
914 Handle<ArrayType> argActual,
917 Local<Type> argGiven(zone_, from->type());
919 // Special case: if we receive a string literal, and this is a char array,
920 // we allow a coercion.
921 if (from->isString() &&
922 argGiven->isString() &&
923 argActual->isArray() &&
924 ArrayType::cast(argActual)->isCharArray())
926 HString *hir = from->toString();
927 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
929 if (actual->isFixedLength()) {
930 if (hir->string()->length() + 1 > actual->fixedLength()) {
931 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
936 // Transform the string literal into an array literal. We give it the
937 // type of the left-hand side. The constness of the destination type
938 // will determine whether HArray duplicates it or not.
939 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, actual));
943 Local<Array> array(zone_);
944 array = Array::NewString(zone_,
946 hir->string()->chars(),
947 hir->string()->length(),
952 // Since we're creating a canonical copy of the char array, we have to
953 // be careful that it doesn't get mutated. There are two cases where
954 // we know it can't be mutated, and therefore don't need to specify
955 // that it be cloned after pushing it onto the stack.
957 // (1) The array type is const.
958 // (2) The array type is fixed-length, and the coercion is for
959 // assignment, meaning it will be immediately copied.
961 // We treat declaration separately from assignment, since for
962 // declaration we can just immediately use the cloned version.
963 bool shouldDuplicate = true;
964 if ((actual->quals() & TypeQual_Const) ||
965 (actual->isFixedLength() && kind == Coerce_Assign))
967 shouldDuplicate = false;
970 return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
973 if (!argGiven->isArray()) {
974 cc_.reportError(pos, Message_ExpectedArray);
978 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
979 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
981 if (actual->levels() != given->levels()) {
982 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
988 if (actual->isFixedLength()) {
989 if (!given->isFixedLength()) {
990 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
994 if (actual->isCharArray()) {
995 // String assignment can have a truncated |given|.
996 if (given->fixedLength() > actual->fixedLength()) {
997 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
1001 if (given->fixedLength() != actual->fixedLength()) {
1002 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1006 } else if (given->isFixedLength()) {
1007 // We do not allow assignments in the form:
1010 // Otherwise, the following code could break the size guarantees
1011 // of the right-hand side:
1021 // Now |x[0]| contains a 3-length array.
1023 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1028 if (!given->contained()->isArray() || !actual->contained()->isArray())
1031 given = ArrayType::cast(given->contained());
1032 actual = ArrayType::cast(actual->contained());
1035 bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
1036 bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
1038 // These arrays must contain the same innermost type.
1039 if (given->contained()->unqualified() != actual->contained()->unqualified() ||
1040 (givenConst && !actualConst))
1044 cc_.reportError(pos, Message_TypeMismatch,
1045 GetTypeName(argActual, aname, sizeof(aname)),
1046 GetTypeName(argGiven, gname, sizeof(gname)));
1054 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
1058 cc_.reportError(pos, Message_InvalidCoercion,
1059 GetTypeName(from, fname, sizeof(fname)),
1060 GetTypeName(to, tname, sizeof(tname)));
1065 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
1067 Local<Type> from(zone_, hir->type());
1069 if (from->isInt32() && to->isFloat())
1070 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
1071 if (from->isInt32() && to->isBool())
1072 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
1074 if (to->isEnum() && *from != to)
1075 return typeFailure(hir->node()->pos(), from, to);
1077 if (to->isArray()) {
1078 Local<ArrayType> atype(zone_, ArrayType::cast(to));
1079 return typeCheckArray(hir->node()->pos(), hir, atype, kind);
1086 SemanticAnalysis::set(VariableSymbol *sym)
1088 if (sym->scope()->kind() == Scope::GLOBAL) {
1091 assert(sym->storage() == VariableSymbol::Local);
1097 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
1099 Local<Type> coercion(zone_, coercionType(token, left, right));
1102 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
1104 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
1119 return new (pool_) HBinary(node, left->type(), token, left, right);
1130 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1131 return new (pool_) HBinary(node, result, token, left, right);
1141 IsValidUncheckedType(Type *type)
1143 return type->isEnum() ||
1147 type->isUnchecked() ||
1152 SemanticAnalysis::visitUnaryExpression(UnaryExpression *node)
1154 HIR *hir = eval(node->expression());
1158 switch (node->token()) {
1161 if (!hir->type()->isInt32() && !hir->type()->isEnum()) {
1163 cc_.reportError(node->pos(), Message_InvalidUnaryType,
1165 GetTypeName(hir->type(), name, sizeof(name)));
1167 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
1168 hir_ = new (pool_) HUnary(node, hir->type(), TOK_TILDE, hir);
1174 if (hir->type()->isInt32() || hir->type()->isEnum()) {
1175 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
1176 hir_ = new (pool_) HUnary(node, type, TOK_MINUS, hir);
1179 if (hir->type()->isFloat()) {
1180 hir_ = new (pool_) HUnary(node, hir->type(), TOK_MINUS, hir);
1185 cc_.reportError(node->pos(), Message_InvalidUnaryType,
1187 GetTypeName(hir->type(), name, sizeof(name)));
1193 assert(node->token() == TOK_LABEL);
1195 TypeSymbol *sym = node->tag()->sym()->asType();
1197 cc_.reportError(node->pos(), Message_IdentifierIsNotAType,
1198 sym->name()->chars());
1202 if (!IsValidUncheckedType(sym->type())) {
1204 cc_.reportError(node->pos(), Message_InvalidUncheckedCastTo,
1205 GetTypeName(hir->type(), name, sizeof(name)));
1208 if (!IsValidUncheckedType(hir->type())) {
1210 cc_.reportError(node->pos(), Message_InvalidUncheckedCastFrom,
1211 GetTypeName(hir->type(), name, sizeof(name)));
1215 hir_ = new (pool_) HUnary(node, hir->type(), TOK_LABEL, hir);
1221 static inline TokenKind
1222 ToCompare(Expression *expr)
1224 if (expr->isBinaryExpression()) {
1225 BinaryExpression *b = expr->toBinaryExpression();
1226 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
1228 } else if (expr->isUnaryExpression()) {
1229 UnaryExpression *u = expr->toUnaryExpression();
1230 if (u->token() == TOK_NOT)
1237 SemanticAnalysis::visitForTest(Expression *expr,
1242 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1244 TokenKind token = ToCompare(expr);
1245 if (token == TOK_EOF || token == TOK_NOT) {
1247 if (token == TOK_EOF)
1250 hir = eval(expr->toUnaryExpression()->expression());
1253 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1258 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
1259 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
1261 if (fallthrough == falseBranch)
1262 __ j(op, trueBranch);
1264 __ j(op, falseBranch);
1268 BinaryExpression *bin = expr->toBinaryExpression();
1269 if (token == TOK_AND || token == TOK_OR) {
1271 if (token == TOK_AND)
1272 visitForTest(bin->left(), &next, falseBranch, &next);
1274 visitForTest(bin->left(), trueBranch, &next, &next);
1276 visitForTest(bin->right(), trueBranch, falseBranch, fallthrough);
1280 HIR *left = eval(bin->left());
1281 HIR *right = eval(bin->right());
1282 if (!left || !right)
1285 HIR *hir = binary(bin, bin->token(), left, right);
1288 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1292 if (fallthrough == trueBranch)
1293 __ j(OP_JF, falseBranch);
1295 __ j(OP_JT, trueBranch);
1299 SemanticAnalysis::lvalue(Expression *expr)
1301 HIR *hir = eval(expr);
1305 if (!hir->isLValue()) {
1306 cc_.reportError(expr->pos(), Message_ExpectedLValue);
1310 return static_cast<HLValue *>(hir);
1314 SemanticAnalysis::eval(Expression *expr)
1326 SemanticAnalysis::discharge(HIR *hir)
1328 EmitHIR(zone_, emitter_, hir);