Add support for importing enum types and enum values (as constexprs).
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<Code> code(zone_, __ finish());
99 code->setModule(unit_->module());
100 unit_->module()->setCode(code);
103 // Disassemble(code, stdout);
108 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
110 FunctionSymbol *sym = stmt->sym();
111 Local<FunctionType> type(zone_, sym->type());
113 assert(scope_->kind() == Scope::GLOBAL);
115 if (stmt->token() == TOK_NATIVE) {
116 // Define the native now.
118 if (!zone_->nativeTable()->add(stmt->name(), &index))
121 Local<Native> native(zone_, Native::New(zone_, type, index));
130 // If the function is a forward or native, we don't have to do anything.
131 if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
134 SemanticAnalysis child(this, type);
135 Local<Function> funobj(zone_, child.compile(stmt));
141 if (stmt->token() == TOK_PUBLIC)
148 SemanticAnalysis::compile(FunctionStatement *stmt)
150 __ setFirstLine(stmt->pos().line);
152 AutoEnterScope argScope(&scope_, stmt->argScope());
154 for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
155 Parameter *param = stmt->signature().parameters()->at(i);
156 param->sym()->allocate(VariableSymbol::Arg, i);
159 AutoEnterScope varScope(&scope_, stmt->varScope());
160 ControlStatus status = visitForControl(stmt->body());
162 if (!fun_->returnType()->isVoid()) {
163 // If the function is not void, report if not all paths return a value.
164 // All other incorrect return cases have been caught already.
165 if (status.returns() == Returns_Sometimes) {
166 cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
170 if (status.returns() == Returns_Never) {
171 cc_.reportError(stmt->pos(), Message_MissingReturnValue);
176 Local<Code> code(zone_, __ finish());
179 code->setModule(unit_->module());
181 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
186 // Disassemble(code, stdout);
193 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
195 AutoEnterScope scope(&scope_, node->scope());
197 for (size_t i = 0; i < node->statements()->length(); i++) {
198 Statement *stmt = node->statements()->at(i);
199 __ note_position(stmt->pos());
201 assert(__ stackDepth() == 0);
206 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
211 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
213 // While building HIR, we enter new pool and root scopes, since HIR
214 // creation is purely temporary.
215 PoolScope poolScope(zone_->pool());
216 RootScope rootScope(zone_);
218 HIR *hir = eval(node->expression());
223 if (!hir->type()->isVoid())
228 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
230 // If both sides terminate in a return, we consider this a return as well.
231 if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
232 terminate(Returns_Always);
236 ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
240 if (left.terminates() && right.terminates())
246 SemanticAnalysis::ControlStatus
247 SemanticAnalysis::visitForControl(Statement *statement)
249 ControlScope scope(&control_);
250 statement->accept(this);
251 return scope.status();
255 SemanticAnalysis::visitIfStatement(IfStatement *node)
259 ControlStatus trueBranch;
260 ControlStatus falseBranch(false, Returns_Never);
262 if (!node->ifFalse()) {
265 visitForTest(node->condition(), &success, &join, &success);
267 trueBranch = visitForControl(node->ifTrue());
271 visitForTest(node->condition(), &success, &next, &success);
273 trueBranch = visitForControl(node->ifTrue());
276 falseBranch = visitForControl(node->ifFalse());
281 control_->merge(trueBranch, falseBranch);
285 SemanticAnalysis::requireLifoStack()
290 loop_->setUsesLifoStack();
293 SemanticAnalysis::ControlStatus
294 SemanticAnalysis::visitLoopBody(Statement *stmt)
296 // We always mark off a loop body, so on each edge, we can balance the
297 // LIFO stack. Right now, we don't have the ability to budget the LIFO
298 // stack ahead of time. If we turn out to never need the LIFO stack, we
299 // mark it as unnecessary. (The interpreter can't really make use of this,
302 // Note that balancing the LIFO stack isn't even necessary, so this
303 // feature may be removed. All this mechanism does is mitigate the
304 // possibility that a long-running loop will overflow the LIFO region
305 // and therefore start requiring nursery allocations.
306 int pos = __ enterloop();
307 ControlStatus status = visitForControl(stmt);
310 if (loop_->usesLifoStack())
311 __ setLoopUsesLifoStack(pos);
317 SemanticAnalysis::visitForStatement(ForStatement *node)
319 AutoEnterScope scope(&scope_, node->scope());
320 PoolScope poolScope(zone_->pool());
321 RootScope rootScope(zone_);
324 LoopScope loop(scope_, &join, &update, &loop_);
326 if (node->initialization())
327 node->initialization()->accept(this);
330 if (node->condition())
334 ControlStatus status = visitLoopBody(node->body());
338 node->update()->accept(this);
340 if (node->condition()) {
342 visitForTest(node->condition(), &header, &join, &join);
349 // If there was a condition, we treat this like a while loop. Otherwise,
350 // the join point is only reachable if the loop contains a break. The
351 // termination status doesn't tell us anything yet.
352 if (node->condition() || loop.breaks())
353 control_->merge(status, ControlStatus(false, Returns_Never));
355 control_->terminate(status.returns());
357 assert(__ stackDepth() == 0);
361 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
363 PoolScope poolScope(zone_->pool());
364 RootScope rootScope(zone_);
370 ControlStatus status;
372 LoopScope loop(scope_, &join, &header, &loop_);
373 if (node->token() == TOK_WHILE) {
375 visitForTest(node->condition(), &body, &join, &body);
376 status = visitLoopBody(node->body());
379 status = visitLoopBody(node->body());
380 visitForTest(node->condition(), &header, &join, &join);
385 // Detect loops that will always have a fork in the contro-flow graph.
386 // This will be a |while| loop, or a |do-while| loop whose body does
387 // not terminate. For now, we treat these as an |if| regardless of the
388 // direction the branch can take. That means the control-flow is always
390 if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
391 control_->merge(status, ControlStatus(false, Returns_Never));
393 // At this point, we've got a do-while loop with a |return| or
394 // |continue|, meaning that the rest of the block is unreachable.
395 control_->terminate(status.returns());
398 assert(__ stackDepth() == 0);
401 static inline Heap::Tenure
402 InferTenure(Symbol *sym)
404 if (sym->scope()->kind() == Scope::GLOBAL)
405 return Heap::Tenure_Old;
407 // SP2's array semantics allow any array kind to escape, so we must use
408 // the normal heap. (Hopefully escape analysis can ease this pain later).
409 if (sym->type()->isArray())
410 return Heap::Tenure_Default;
412 return Heap::Tenure_Default;
416 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
418 PoolScope poolScope(zone_->pool());
419 RootScope rootScope(zone_);
421 Local<Type> type(zone_, node->sym()->type());
423 if (node->sym()->type()->isVoid()) {
424 cc_.reportError(node->type()->pos(), Message_CannotDeclareVoid);
428 if (node->initialization()) {
431 if ((hir = eval(node->initialization())) == NULL)
433 if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
438 if (type->isInt32() || type->isEnum() ||
439 type->isChar() || type->isBool())
442 } else if (type->isFloat()) {
444 } else if (type->isArray()) {
445 Local<ArrayType> atype(zone_, ArrayType::cast(type));
446 Local<ArrayMap> map(zone_, atype->newMap());
450 if (atype->isFixedLength()) {
451 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
452 } else if (node->dims()->at(0)) {
453 // This may not be true if we allow typedefing, so :TODO:
454 // figure out proper semantics.
455 assert(node->dims()->length() == atype->levels());
457 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
458 for (size_t i = 0; i < node->dims()->length(); i++) {
459 Expression *expr = node->dims()->at(i);
461 HIR *hir = eval(expr);
462 if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
469 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
471 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
478 if (node->sym()->scope()->kind() != Scope::GLOBAL) {
479 if (!__ allocate(node->sym()))
488 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
490 control_->returns(Returns_Always);
492 if (!node->expression()) {
493 if (!fun_->returnType()->isVoid()) {
494 cc_.reportError(node->pos(), Message_MissingReturnValue);
502 if (fun_->returnType()->isVoid()) {
503 cc_.reportError(node->pos(), Message_UsedVoidReturn);
507 PoolScope poolScope(zone_->pool());
508 RootScope rootScope(zone_);
510 HIR *hir = eval(node->expression());
514 Local<Type> returnType(zone_, fun_->returnType());
515 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
520 if (hir->type()->isVoid())
527 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
529 HIR *left = eval(node->left());
530 HIR *right = eval(node->right());
534 hir_ = binary(node, node->token(), left, right);
538 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
540 if (type->parameters()->length() == actual)
543 if (actual > type->parameters()->length()) {
544 if (!type->isNative() || !type->isNativeVariadic())
549 if (!type->defaults())
552 // Missing arguments. See if there's a default argument for each missing
554 for (unsigned i = actual; i < type->parameters()->length(); i++) {
555 if (!type->defaults()->at(i))
563 BindImplicitName(Module *from, ImplicitSymbol *sym)
566 return sym->fieldIndex();
568 Module *module = Module::cast(from->getImportAt(sym->index()));
569 StructMap *map = module->globals()->map();
572 Descriptor *desc = map->type()->lookupField(sym->name(), &fieldIndex);
573 assert(desc && desc->type() == sym->type());
575 sym->bind(fieldIndex);
580 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
582 Symbol *sym = proxy->sym();
584 switch (sym->kind()) {
585 case Symbol::kImport:
587 ImportSymbol *import = sym->toImport();
588 hir_ = new (pool_) HImport(proxy, sym->type(), import->index());
592 case Symbol::kImplicit:
594 ImplicitSymbol *import = sym->toImplicit();
595 unsigned fieldIndex = BindImplicitName(unit_->module(), import);
597 hir_ = new (pool_) HImport(proxy, zone_->types()->getImportable(), import->index());
598 hir_ = new (pool_) HField(proxy, hir_, sym->type(), fieldIndex);
602 case Symbol::kConstant:
604 ConstantSymbol *val = sym->toConstant();
605 hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
609 // This is kind of screwy. Symbol::kFunction is like a constant we can't
610 // evaluate yet. Maybe we should extract the GLOBAL case and say that
611 // kFunction is only used for global functions (and use const vars for
613 case Symbol::kFunction:
614 case Symbol::kVariable:
616 Scope *in = sym->scope();
617 switch (in->kind()) {
619 hir_ = new (pool_) HGlobal(proxy, sym);
622 case Scope::FUNCTION:
624 VariableSymbol *var = sym->toVariable();
625 assert(var->storage() == VariableSymbol::Arg);
626 hir_ = new (pool_) HLocal(proxy, var);
632 VariableSymbol *var = sym->toVariable();
633 assert(in->kind() == Scope::BLOCK);
634 assert(var->storage() == VariableSymbol::Local);
635 hir_ = new (pool_) HLocal(proxy, var);
649 SemanticAnalysis::visitBooleanLiteral(BooleanLiteral *node)
651 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
652 hir_ = new (pool_) HBoolean(node, type, node->token() == TOK_TRUE);
656 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
658 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
659 hir_ = new (pool_) HInteger(lit, type, lit->value());
663 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
665 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
666 hir_ = new (pool_) HFloat(node, type, (float)node->value());
670 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
672 Type *type = zone_->types()->getString();
673 hir_ = new (pool_) HString(node, type, node->string());
677 SemanticAnalysis::visitCallExpression(CallExpression *node)
679 HIR *callee = eval(node->callee());
683 if (!callee->type()->isFunction()) {
684 cc_.reportError(node->pos(), Message_CalleeNotFunction);
688 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
690 if (!checkArgumentCount(fun, node->arguments()->length())) {
691 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
695 if (fun->isForward()) {
696 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
700 HIRList *args = new (pool_) HIRList;
701 for (unsigned i = 0; i < node->arguments()->length(); i++) {
702 Expression *expression = node->arguments()->at(i);
703 HIR *arg = eval(expression);
707 Handle<Type> given = arg->type();
709 bool mustComputeReference;
710 if (i >= fun->parameters()->length()) {
711 // Special handling for natives. Arguments past the formal must
712 // always have references computed. However, arrays are already
713 // references for natives.
714 assert(fun->isNative() && fun->isNativeVariadic());
715 mustComputeReference = !given->isReference() &&
718 Local<Type> actual(zone_, fun->parameterAt(i));
720 if (expression->isIndexExpression() && arg->isIndex()) {
721 // If the expression is the form x[y], and this produced a
722 // normal array indexing operation, then we apply some
725 if (actual->isReference()) {
726 // Disabled, since this doesn't have easily definable or
727 // sensible semantics with SP2 arrays, but we don't want
728 // to silently break SP1 semantics.
729 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
733 // As a special rule to account for SP1 semantics, we allow x[y]
734 // to automatically compute a sliced, read-only array view if
735 // the desired type is an array of one more dimension than x[y]
738 // As an additional restriction, this is only allowed for
739 // one-level char arrays, to minimize potential issues until
740 // we determine whether more compatibility is needed.
742 // Internally, for sanity, the dependent array operation does
743 // not necessarily create a dependent array. For extensible
744 // arrays, we instead create a duplicate arrary of just the
745 // sliced portion, rather than deal with the complexity of the
746 // source array being resized.
748 // Note that we don't really know whether a dependent array
749 // will be dependent at compile-time, so the dependent type's
750 // just inherits from the source.
751 if (actual->isArray()) {
752 HIndex *index = arg->toIndex();
753 Local<ArrayType> basetype(zone_, ArrayType::cast(index->base()->type()));
754 Local<ArrayType> atype(zone_, ArrayType::cast(actual));
756 if (atype->isCharArray() && basetype->isCharArray()) {
757 // There is no possible way this will type check, so
758 // it's safe to just try something completely
760 Local<Type> slicetype(zone_);
761 if (basetype->isFixedLength()) {
762 // If the base type is fixed length, we need to
763 // compute a new dynamic array type based on the
764 // fixed array's contents and qualifiers.
765 Local<Type> contained(zone_, basetype->contained());
766 slicetype = zone_->types()->newArray(contained, ArrayType::DYNAMIC_ARRAY_SIZE);
769 slicetype = zone_->types()->qualify(slicetype, basetype->quals());
773 slicetype = basetype;
775 arg = new (pool_) HNewDependentArray(expression, slicetype, index->base(), index->index());
781 if (actual->isReference()) {
782 // If the actual is a reference, the coercion rules are much
783 // stricter; the contained types must be identical.
784 // :TODO: make this not an assert
785 assert(ReferenceType::cast(actual)->contained() == arg->type());
787 // When we start overloading, coercion will have to happen later.
788 arg = coerce(arg, actual, Coerce_Arg);
793 mustComputeReference = actual->isReference() && !given->isReference();
796 if (mustComputeReference) {
797 // Refs always use the LIFO stack if they can.
798 arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
802 if (!args->append(arg))
806 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
810 SemanticAnalysis::visitAssignment(Assignment *node)
812 HLValue *lval = lvalue(node->lvalue());
816 if (lval->type()->quals() & TypeQual_Const) {
817 cc_.reportError(node->pos(), Message_CannotModifyConst);
821 HIR *hir = eval(node->expression());
824 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
827 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
831 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
834 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
839 __ j(OP_BREAK, loop_->break_());
843 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
846 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
850 __ j(OP_CONTINUE, loop_->continue_());
854 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
856 HIR *left = eval(node->left());
860 HIR *right = eval(node->right());
864 // Hrm... yes, for now, let's coerce here.
865 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
866 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
869 // Do not coerce here, there's no reason to yet.
870 if (!left->type()->isArray()) {
871 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
875 hir_ = new (pool_) HIndex(node,
876 ArrayType::cast(left->type())->contained(),
882 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
884 HLValue *lval = lvalue(node->expression());
888 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
894 if (lval->type()->isInt32())
895 rval = new (pool_) HInteger(node, lval->type(), 1);
897 rval = new (pool_) HFloat(node, lval->type(), 1.0);
900 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
902 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
906 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
908 Local<Type> l(zone_, left->type());
909 Local<Type> r(zone_, right->type());
912 l = l->unqualified();
914 r = r->unqualified();
916 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
917 (token >= TOK_EQUALS && token <= TOK_GE))
919 // We allow: [float|int32] + [float|int32]
920 if (l->isFloat() && r->isInt32())
922 if (l->isInt32() && r->isFloat())
924 if (l->isInt32() && r->isInt32())
927 if (l->isChar() && r->isInt32())
929 if (l->isInt32() && r->isChar())
940 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
942 Handle<ArrayType> argActual,
945 Local<Type> argGiven(zone_, from->type());
947 // Special case: if we receive a string literal, and this is a char array,
948 // we allow a coercion.
949 if (from->isString() &&
950 argGiven->isString() &&
951 argActual->isArray() &&
952 ArrayType::cast(argActual)->isCharArray())
954 HString *hir = from->toString();
955 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
957 if (actual->isFixedLength()) {
958 if (hir->string()->length() + 1 > actual->fixedLength()) {
959 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
964 // Transform the string literal into an array literal. We give it the
965 // type of the left-hand side. The constness of the destination type
966 // will determine whether HArray duplicates it or not.
967 Local<ArrayMap> map(zone_, actual->newMap());
971 Local<Array> array(zone_);
972 array = Array::NewString(zone_,
974 hir->string()->chars(),
975 hir->string()->length(),
980 // Since we're creating a canonical copy of the char array, we have to
981 // be careful that it doesn't get mutated. There are two cases where
982 // we know it can't be mutated, and therefore don't need to specify
983 // that it be cloned after pushing it onto the stack.
985 // (1) The array type is const.
986 // (2) The array type is fixed-length, and the coercion is for
987 // assignment, meaning it will be immediately copied.
989 // We treat declaration separately from assignment, since for
990 // declaration we can just immediately use the cloned version.
991 bool shouldDuplicate = true;
992 if ((actual->quals() & TypeQual_Const) ||
993 (actual->isFixedLength() && kind == Coerce_Assign))
995 shouldDuplicate = false;
998 return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
1001 if (!argGiven->isArray()) {
1002 cc_.reportError(pos, Message_ExpectedArray);
1006 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
1007 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
1009 if (actual->levels() != given->levels()) {
1010 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
1016 if (actual->isFixedLength()) {
1017 if (!given->isFixedLength()) {
1018 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1022 if (actual->isCharArray()) {
1023 // String assignment can have a truncated |given|.
1024 if (given->fixedLength() > actual->fixedLength()) {
1025 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
1029 if (given->fixedLength() != actual->fixedLength()) {
1030 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1034 } else if (given->isFixedLength()) {
1035 // We do not allow assignments in the form:
1038 // Otherwise, the following code could break the size guarantees
1039 // of the right-hand side:
1049 // Now |x[0]| contains a 3-length array.
1051 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1056 if (!given->contained()->isArray() || !actual->contained()->isArray())
1059 given = ArrayType::cast(given->contained());
1060 actual = ArrayType::cast(actual->contained());
1063 bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
1064 bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
1066 // These arrays must contain the same innermost type.
1067 if (given->contained()->unqualified() != actual->contained()->unqualified() ||
1068 (givenConst && !actualConst))
1072 cc_.reportError(pos, Message_TypeMismatch,
1073 GetTypeName(argActual, aname, sizeof(aname)),
1074 GetTypeName(argGiven, gname, sizeof(gname)));
1082 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
1086 cc_.reportError(pos, Message_InvalidCoercion,
1087 GetTypeName(from, fname, sizeof(fname)),
1088 GetTypeName(to, tname, sizeof(tname)));
1093 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
1095 Local<Type> from(zone_, hir->type());
1097 // If the source is *ever* an importable, we just fail.
1098 if (from->isImportable())
1099 return typeFailure(hir->node()->pos(), from, to);
1101 if (from->isInt32() && to->isFloat())
1102 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
1103 if (from->isInt32() && to->isBool())
1104 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
1106 if (to->isEnum() && from->unqualified() != to->unqualified())
1107 return typeFailure(hir->node()->pos(), from, to);
1109 if (to->isArray()) {
1110 Local<ArrayType> atype(zone_, ArrayType::cast(to));
1111 return typeCheckArray(hir->node()->pos(), hir, atype, kind);
1118 SemanticAnalysis::set(VariableSymbol *sym)
1120 if (sym->scope()->kind() == Scope::GLOBAL) {
1123 assert(sym->storage() == VariableSymbol::Local);
1129 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
1131 Local<Type> coercion(zone_, coercionType(token, left, right));
1134 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
1136 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
1151 return new (pool_) HBinary(node, left->type(), token, left, right);
1162 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1163 return new (pool_) HBinary(node, result, token, left, right);
1173 IsValidUncheckedType(Type *type)
1175 return type->isEnum() ||
1179 type->isUnchecked() ||
1184 SemanticAnalysis::visitUnaryExpression(UnaryExpression *node)
1186 HIR *hir = eval(node->expression());
1190 switch (node->token()) {
1193 if (!hir->type()->isInt32() && !hir->type()->isEnum()) {
1195 cc_.reportError(node->pos(), Message_InvalidUnaryType,
1197 GetTypeName(hir->type(), name, sizeof(name)));
1199 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
1200 hir_ = new (pool_) HUnary(node, hir->type(), TOK_TILDE, hir);
1206 if (hir->type()->isInt32() || hir->type()->isEnum()) {
1207 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
1208 hir_ = new (pool_) HUnary(node, type, TOK_MINUS, hir);
1211 if (hir->type()->isFloat()) {
1212 hir_ = new (pool_) HUnary(node, hir->type(), TOK_MINUS, hir);
1217 cc_.reportError(node->pos(), Message_InvalidUnaryType,
1219 GetTypeName(hir->type(), name, sizeof(name)));
1225 assert(node->token() == TOK_LABEL);
1227 TypeSymbol *sym = node->tag()->sym()->asType();
1229 cc_.reportError(node->pos(), Message_IdentifierIsNotAType,
1230 sym->name()->chars());
1234 if (!IsValidUncheckedType(sym->effective())) {
1236 cc_.reportError(node->pos(), Message_InvalidUncheckedCastTo,
1237 GetTypeName(sym->type(), name, sizeof(name)));
1240 if (!IsValidUncheckedType(hir->type())) {
1242 cc_.reportError(node->pos(), Message_InvalidUncheckedCastFrom,
1243 GetTypeName(hir->type(), name, sizeof(name)));
1247 hir_ = new (pool_) HUnary(node, sym->effective(), TOK_LABEL, hir);
1254 SemanticAnalysis::import(HIR *hir, FieldExpression *node)
1256 // Note that we don't care if the hir type is "importable", since we
1257 // can only do anything if the important has a constant binding.
1258 unsigned index = hir->toImport()->index();
1259 Local<Importable> importable(zone_, unit_->module()->getImportAt(index));
1261 if (importable->isPackage()) {
1262 // Look at what's already loaded and see if anything exists. We
1263 // can't create stuff on-demand here since it's too late to add
1264 // new translation units to the CompileContext.
1265 Local<Package> package(zone_, Package::cast(importable));
1266 Local<Importable> found(zone_, package->import(node->field()));
1268 cc_.reportError(node->pos(), Message_PackageDoesNotHaveMember, node->field()->chars());
1272 // If we did find something, make sure it is in our import list.
1273 // If we didn't explicitly import it, we have no right to use it.
1274 for (index = 0; index < unit_->module()->imports(); index++) {
1275 if (unit_->module()->getImportAt(index) == importable)
1279 if (index == unit_->module()->imports()) {
1280 cc_.reportError(node->pos(), Message_ImportWasNeverImported, node->field()->chars());
1284 // Just create a new HImport.
1285 hir_ = new (pool_) HImport(node, hir->type(), index);
1287 // Modules can never have sub-modules or sub-packages.
1289 Local<Module> module(zone_, Module::cast(importable));
1290 Local<StructMap> map(zone_, module->globals()->map());
1291 Local<Descriptor> desc(zone_, map->type()->lookupField(node->field(), &index));
1293 cc_.reportError(node->pos(), Message_FieldNotFound, node->field()->chars());
1296 hir_ = new (pool_) HField(node, hir, desc->type(), index);
1301 SemanticAnalysis::visitFieldExpression(FieldExpression *node)
1303 HIR *hir = eval(node->left());
1307 if (hir->isImport()) {
1313 cc_.reportError(node->pos(), Message_InvalidFieldExpression,
1314 GetTypeName(hir->type(), name, sizeof(name)));
1317 static inline TokenKind
1318 ToCompare(Expression *expr)
1320 if (expr->isBinaryExpression()) {
1321 BinaryExpression *b = expr->toBinaryExpression();
1322 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
1324 } else if (expr->isUnaryExpression()) {
1325 UnaryExpression *u = expr->toUnaryExpression();
1326 if (u->token() == TOK_NOT)
1333 SemanticAnalysis::visitForTest(Expression *expr,
1338 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1340 TokenKind token = ToCompare(expr);
1341 if (token == TOK_EOF || token == TOK_NOT) {
1343 if (token == TOK_EOF)
1346 hir = eval(expr->toUnaryExpression()->expression());
1349 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1354 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
1355 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
1357 if (fallthrough == falseBranch)
1358 __ j(op, trueBranch);
1360 __ j(op, falseBranch);
1364 BinaryExpression *bin = expr->toBinaryExpression();
1365 if (token == TOK_AND || token == TOK_OR) {
1367 if (token == TOK_AND)
1368 visitForTest(bin->left(), &next, falseBranch, &next);
1370 visitForTest(bin->left(), trueBranch, &next, &next);
1372 visitForTest(bin->right(), trueBranch, falseBranch, fallthrough);
1376 HIR *left = eval(bin->left());
1377 HIR *right = eval(bin->right());
1378 if (!left || !right)
1381 HIR *hir = binary(bin, bin->token(), left, right);
1384 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1388 if (fallthrough == trueBranch)
1389 __ j(OP_JF, falseBranch);
1391 __ j(OP_JT, trueBranch);
1395 SemanticAnalysis::lvalue(Expression *expr)
1397 HIR *hir = eval(expr);
1401 if (!hir->isLValue()) {
1402 cc_.reportError(expr->pos(), Message_ExpectedLValue);
1406 return static_cast<HLValue *>(hir);
1410 SemanticAnalysis::eval(Expression *expr)
1422 SemanticAnalysis::discharge(HIR *hir)
1424 EmitHIR(zone_, emitter_, hir);