Implement |from x import *| syntax for modules.
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));
721 if (expression->isIndexExpression() && arg->isIndex()) {
722 // If the expression is the form x[y], and this produced a
723 // normal array indexing operation, then we apply some
726 if (actual->isReference()) {
727 // Disabled, since this doesn't have easily definable or
728 // sensible semantics with SP2 arrays, but we don't want
729 // to silently break SP1 semantics.
730 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
734 // As a special rule to account for SP1 semantics, we allow x[y]
735 // to automatically compute a sliced, read-only array view if
736 // the desired type is an array of one more dimension than x[y]
739 // As an additional restriction, this is only allowed for
740 // one-level char arrays, to minimize potential issues until
741 // we determine whether more compatibility is needed.
743 // Internally, for sanity, the dependent array operation does
744 // not necessarily create a dependent array. For extensible
745 // arrays, we instead create a duplicate arrary of just the
746 // sliced portion, rather than deal with the complexity of the
747 // source array being resized.
749 // Note that we don't really know whether a dependent array
750 // will be dependent at compile-time, so the dependent type's
751 // just inherits from the source.
752 if (actual->isArray()) {
753 HIndex *index = arg->toIndex();
754 Local<ArrayType> basetype(zone_, ArrayType::cast(index->base()->type()));
755 Local<ArrayType> atype(zone_, ArrayType::cast(actual));
757 if (atype->isCharArray() && basetype->isCharArray()) {
758 // There is no possible way this will type check, so
759 // it's safe to just try something completely
761 Local<Type> slicetype(zone_);
762 if (basetype->isFixedLength()) {
763 // If the base type is fixed length, we need to
764 // compute a new dynamic array type based on the
765 // fixed array's contents and qualifiers.
766 Local<Type> contained(zone_, basetype->contained());
767 slicetype = zone_->types()->newArray(contained, ArrayType::DYNAMIC_ARRAY_SIZE);
770 slicetype = zone_->types()->qualify(slicetype, basetype->quals());
774 slicetype = basetype;
776 arg = new (pool_) HNewDependentArray(expression, slicetype, index->base(), index->index());
782 if (actual->isReference()) {
783 // If the actual is a reference, the coercion rules are much
784 // stricter; the contained types must be identical.
785 // :TODO: make this not an assert
786 assert(ReferenceType::cast(actual)->contained() == arg->type());
788 // When we start overloading, coercion will have to happen later.
789 arg = coerce(arg, actual, Coerce_Arg);
794 mustComputeReference = actual->isReference() && !given->isReference();
797 if (mustComputeReference) {
798 // Refs always use the LIFO stack if they can.
799 arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
803 if (!args->append(arg))
807 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
811 SemanticAnalysis::visitAssignment(Assignment *node)
813 HLValue *lval = lvalue(node->lvalue());
817 if (lval->type()->quals() & TypeQual_Const) {
818 cc_.reportError(node->pos(), Message_CannotModifyConst);
822 HIR *hir = eval(node->expression());
825 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
828 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
832 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
835 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
840 __ j(OP_BREAK, loop_->break_());
844 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
847 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
851 __ j(OP_CONTINUE, loop_->continue_());
855 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
857 HIR *left = eval(node->left());
861 HIR *right = eval(node->right());
865 // Hrm... yes, for now, let's coerce here.
866 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
867 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
870 // Do not coerce here, there's no reason to yet.
871 if (!left->type()->isArray()) {
872 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
876 hir_ = new (pool_) HIndex(node,
877 ArrayType::cast(left->type())->contained(),
883 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
885 HLValue *lval = lvalue(node->expression());
889 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
895 if (lval->type()->isInt32())
896 rval = new (pool_) HInteger(node, lval->type(), 1);
898 rval = new (pool_) HFloat(node, lval->type(), 1.0);
901 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
903 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
907 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
909 Local<Type> l(zone_, left->type());
910 Local<Type> r(zone_, right->type());
913 l = l->unqualified();
915 r = r->unqualified();
917 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
918 (token >= TOK_EQUALS && token <= TOK_GE))
920 // We allow: [float|int32] + [float|int32]
921 if (l->isFloat() && r->isInt32())
923 if (l->isInt32() && r->isFloat())
925 if (l->isInt32() && r->isInt32())
928 if (l->isChar() && r->isInt32())
930 if (l->isInt32() && r->isChar())
941 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
943 Handle<ArrayType> argActual,
946 Local<Type> argGiven(zone_, from->type());
948 // Special case: if we receive a string literal, and this is a char array,
949 // we allow a coercion.
950 if (from->isString() &&
951 argGiven->isString() &&
952 argActual->isArray() &&
953 ArrayType::cast(argActual)->isCharArray())
955 HString *hir = from->toString();
956 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
958 if (actual->isFixedLength()) {
959 if (hir->string()->length() + 1 > actual->fixedLength()) {
960 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
965 // Transform the string literal into an array literal. We give it the
966 // type of the left-hand side. The constness of the destination type
967 // will determine whether HArray duplicates it or not.
968 Local<ArrayMap> map(zone_, actual->newMap());
972 Local<Array> array(zone_);
973 array = Array::NewString(zone_,
975 hir->string()->chars(),
976 hir->string()->length(),
981 // Since we're creating a canonical copy of the char array, we have to
982 // be careful that it doesn't get mutated. There are two cases where
983 // we know it can't be mutated, and therefore don't need to specify
984 // that it be cloned after pushing it onto the stack.
986 // (1) The array type is const.
987 // (2) The array type is fixed-length, and the coercion is for
988 // assignment, meaning it will be immediately copied.
990 // We treat declaration separately from assignment, since for
991 // declaration we can just immediately use the cloned version.
992 bool shouldDuplicate = true;
993 if ((actual->quals() & TypeQual_Const) ||
994 (actual->isFixedLength() && kind == Coerce_Assign))
996 shouldDuplicate = false;
999 return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
1002 if (!argGiven->isArray()) {
1003 cc_.reportError(pos, Message_ExpectedArray);
1007 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
1008 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
1010 if (actual->levels() != given->levels()) {
1011 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
1017 if (actual->isFixedLength()) {
1018 if (!given->isFixedLength()) {
1019 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1023 if (actual->isCharArray()) {
1024 // String assignment can have a truncated |given|.
1025 if (given->fixedLength() > actual->fixedLength()) {
1026 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
1030 if (given->fixedLength() != actual->fixedLength()) {
1031 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1035 } else if (given->isFixedLength()) {
1036 // We do not allow assignments in the form:
1039 // Otherwise, the following code could break the size guarantees
1040 // of the right-hand side:
1050 // Now |x[0]| contains a 3-length array.
1052 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1057 if (!given->contained()->isArray() || !actual->contained()->isArray())
1060 given = ArrayType::cast(given->contained());
1061 actual = ArrayType::cast(actual->contained());
1064 bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
1065 bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
1067 // These arrays must contain the same innermost type.
1068 if (given->contained()->unqualified() != actual->contained()->unqualified() ||
1069 (givenConst && !actualConst))
1073 cc_.reportError(pos, Message_TypeMismatch,
1074 GetTypeName(argActual, aname, sizeof(aname)),
1075 GetTypeName(argGiven, gname, sizeof(gname)));
1083 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
1087 cc_.reportError(pos, Message_InvalidCoercion,
1088 GetTypeName(from, fname, sizeof(fname)),
1089 GetTypeName(to, tname, sizeof(tname)));
1094 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
1096 Local<Type> from(zone_, hir->type());
1098 // If the source is *ever* an importable, we just fail.
1099 if (from->isImportable())
1100 return typeFailure(hir->node()->pos(), from, to);
1102 if (from->isInt32() && to->isFloat())
1103 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
1104 if (from->isInt32() && to->isBool())
1105 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
1107 if (to->isEnum() && *from != to)
1108 return typeFailure(hir->node()->pos(), from, to);
1110 if (to->isArray()) {
1111 Local<ArrayType> atype(zone_, ArrayType::cast(to));
1112 return typeCheckArray(hir->node()->pos(), hir, atype, kind);
1119 SemanticAnalysis::set(VariableSymbol *sym)
1121 if (sym->scope()->kind() == Scope::GLOBAL) {
1124 assert(sym->storage() == VariableSymbol::Local);
1130 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
1132 Local<Type> coercion(zone_, coercionType(token, left, right));
1135 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
1137 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
1152 return new (pool_) HBinary(node, left->type(), token, left, right);
1163 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1164 return new (pool_) HBinary(node, result, token, left, right);
1174 IsValidUncheckedType(Type *type)
1176 return type->isEnum() ||
1180 type->isUnchecked() ||
1185 SemanticAnalysis::visitUnaryExpression(UnaryExpression *node)
1187 HIR *hir = eval(node->expression());
1191 switch (node->token()) {
1194 if (!hir->type()->isInt32() && !hir->type()->isEnum()) {
1196 cc_.reportError(node->pos(), Message_InvalidUnaryType,
1198 GetTypeName(hir->type(), name, sizeof(name)));
1200 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
1201 hir_ = new (pool_) HUnary(node, hir->type(), TOK_TILDE, hir);
1207 if (hir->type()->isInt32() || hir->type()->isEnum()) {
1208 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
1209 hir_ = new (pool_) HUnary(node, type, TOK_MINUS, hir);
1212 if (hir->type()->isFloat()) {
1213 hir_ = new (pool_) HUnary(node, hir->type(), TOK_MINUS, hir);
1218 cc_.reportError(node->pos(), Message_InvalidUnaryType,
1220 GetTypeName(hir->type(), name, sizeof(name)));
1226 assert(node->token() == TOK_LABEL);
1228 TypeSymbol *sym = node->tag()->sym()->asType();
1230 cc_.reportError(node->pos(), Message_IdentifierIsNotAType,
1231 sym->name()->chars());
1235 if (!IsValidUncheckedType(sym->type())) {
1237 cc_.reportError(node->pos(), Message_InvalidUncheckedCastTo,
1238 GetTypeName(hir->type(), name, sizeof(name)));
1241 if (!IsValidUncheckedType(hir->type())) {
1243 cc_.reportError(node->pos(), Message_InvalidUncheckedCastFrom,
1244 GetTypeName(hir->type(), name, sizeof(name)));
1248 hir_ = new (pool_) HUnary(node, hir->type(), TOK_LABEL, hir);
1255 SemanticAnalysis::import(HIR *hir, FieldExpression *node)
1257 // Note that we don't care if the hir type is "importable", since we
1258 // can only do anything if the important has a constant binding.
1259 unsigned index = hir->toImport()->index();
1260 Local<Importable> importable(zone_, unit_->module()->getImportAt(index));
1262 if (importable->isPackage()) {
1263 // Look at what's already loaded and see if anything exists. We
1264 // can't create stuff on-demand here since it's too late to add
1265 // new translation units to the CompileContext.
1266 Local<Package> package(zone_, Package::cast(importable));
1267 Local<Importable> found(zone_, package->import(node->field()));
1269 cc_.reportError(node->pos(), Message_PackageDoesNotHaveMember, node->field()->chars());
1273 // If we did find something, make sure it is in our import list.
1274 // If we didn't explicitly import it, we have no right to use it.
1275 for (index = 0; index < unit_->module()->imports(); index++) {
1276 if (unit_->module()->getImportAt(index) == importable)
1280 if (index == unit_->module()->imports()) {
1281 cc_.reportError(node->pos(), Message_ImportWasNeverImported, node->field()->chars());
1285 // Just create a new HImport.
1286 hir_ = new (pool_) HImport(node, hir->type(), index);
1288 // Modules can never have sub-modules or sub-packages.
1290 Local<Module> module(zone_, Module::cast(importable));
1291 Local<StructMap> map(zone_, module->globals()->map());
1292 Local<Descriptor> desc(zone_, map->type()->lookupField(node->field(), &index));
1294 cc_.reportError(node->pos(), Message_FieldNotFound, node->field()->chars());
1297 hir_ = new (pool_) HField(node, hir, desc->type(), index);
1302 SemanticAnalysis::visitFieldExpression(FieldExpression *node)
1304 HIR *hir = eval(node->left());
1308 if (hir->isImport()) {
1314 cc_.reportError(node->pos(), Message_InvalidFieldExpression,
1315 GetTypeName(hir->type(), name, sizeof(name)));
1318 static inline TokenKind
1319 ToCompare(Expression *expr)
1321 if (expr->isBinaryExpression()) {
1322 BinaryExpression *b = expr->toBinaryExpression();
1323 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
1325 } else if (expr->isUnaryExpression()) {
1326 UnaryExpression *u = expr->toUnaryExpression();
1327 if (u->token() == TOK_NOT)
1334 SemanticAnalysis::visitForTest(Expression *expr,
1339 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1341 TokenKind token = ToCompare(expr);
1342 if (token == TOK_EOF || token == TOK_NOT) {
1344 if (token == TOK_EOF)
1347 hir = eval(expr->toUnaryExpression()->expression());
1350 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1355 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
1356 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
1358 if (fallthrough == falseBranch)
1359 __ j(op, trueBranch);
1361 __ j(op, falseBranch);
1365 BinaryExpression *bin = expr->toBinaryExpression();
1366 if (token == TOK_AND || token == TOK_OR) {
1368 if (token == TOK_AND)
1369 visitForTest(bin->left(), &next, falseBranch, &next);
1371 visitForTest(bin->left(), trueBranch, &next, &next);
1373 visitForTest(bin->right(), trueBranch, falseBranch, fallthrough);
1377 HIR *left = eval(bin->left());
1378 HIR *right = eval(bin->right());
1379 if (!left || !right)
1382 HIR *hir = binary(bin, bin->token(), left, right);
1385 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1389 if (fallthrough == trueBranch)
1390 __ j(OP_JF, falseBranch);
1392 __ j(OP_JT, trueBranch);
1396 SemanticAnalysis::lvalue(Expression *expr)
1398 HIR *hir = eval(expr);
1402 if (!hir->isLValue()) {
1403 cc_.reportError(expr->pos(), Message_ExpectedLValue);
1407 return static_cast<HLValue *>(hir);
1411 SemanticAnalysis::eval(Expression *expr)
1423 SemanticAnalysis::discharge(HIR *hir)
1425 EmitHIR(zone_, emitter_, hir);