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)
70 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
71 : zone_(parent->zone_),
76 scope_(parent->scope_),
85 SemanticAnalysis::analyze()
87 scope_ = unit_->globalScope();
89 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
90 Statement *stmt = unit_->tree()->statements()->at(i);
94 Local<Code> code(zone_, __ finish());
97 code->setModule(unit_->module());
98 unit_->module()->setCode(code);
101 // Disassemble(code, stdout);
106 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
108 FunctionSymbol *sym = stmt->sym();
109 Local<FunctionType> type(zone_, sym->type());
111 assert(scope_->kind() == Scope::GLOBAL);
113 if (stmt->token() == TOK_NATIVE) {
114 // Define the native now.
116 if (!zone_->nativeTable()->add(stmt->name(), &index))
119 Local<Native> native(zone_, Native::New(zone_, type, index));
128 // If the function is a forward or native, we don't have to do anything.
129 if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
132 SemanticAnalysis child(this, type);
133 Local<Function> funobj(zone_, child.compile(stmt));
139 if (stmt->token() == TOK_PUBLIC)
146 SemanticAnalysis::compile(FunctionStatement *stmt)
148 __ setFirstLine(stmt->pos().line);
150 AutoEnterScope argScope(&scope_, stmt->argScope());
152 for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
153 Parameter *param = stmt->signature().parameters()->at(i);
154 param->sym()->allocate(VariableSymbol::Arg, i);
157 AutoEnterScope varScope(&scope_, stmt->varScope());
158 ControlStatus status = visitForControl(stmt->body());
160 if (!fun_->returnType()->isVoid()) {
161 // If the function is not void, report if not all paths return a value.
162 // All other incorrect return cases have been caught already.
163 if (status.returns() == Returns_Sometimes) {
164 cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
168 if (status.returns() == Returns_Never) {
169 cc_.reportError(stmt->pos(), Message_MissingReturnValue);
174 Local<Code> code(zone_, __ finish());
177 code->setModule(unit_->module());
179 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
184 // Disassemble(code, stdout);
191 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
193 AutoEnterScope scope(&scope_, node->scope());
195 for (size_t i = 0; i < node->statements()->length(); i++) {
196 Statement *stmt = node->statements()->at(i);
197 __ note_position(stmt->pos());
199 assert(__ stackDepth() == 0);
204 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
209 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
211 // While building HIR, we enter new pool and root scopes, since HIR
212 // creation is purely temporary.
213 PoolScope poolScope(zone_->pool());
214 RootScope rootScope(zone_);
216 HIR *hir = eval(node->expression());
221 if (!hir->type()->isVoid())
226 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
228 // If both sides terminate in a return, we consider this a return as well.
229 if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
230 terminate(Returns_Always);
234 ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
238 if (left.terminates() && right.terminates())
244 SemanticAnalysis::ControlStatus
245 SemanticAnalysis::visitForControl(Statement *statement)
247 ControlScope scope(&control_);
248 statement->accept(this);
249 return scope.status();
253 SemanticAnalysis::visitIfStatement(IfStatement *node)
257 ControlStatus trueBranch;
258 ControlStatus falseBranch(false, Returns_Never);
260 if (!node->ifFalse()) {
263 visitForTest(node->condition(), &success, &join, &success);
265 trueBranch = visitForControl(node->ifTrue());
269 visitForTest(node->condition(), &success, &next, &success);
271 trueBranch = visitForControl(node->ifTrue());
274 falseBranch = visitForControl(node->ifFalse());
279 control_->merge(trueBranch, falseBranch);
283 SemanticAnalysis::requireLifoStack()
288 loop_->setUsesLifoStack();
291 SemanticAnalysis::ControlStatus
292 SemanticAnalysis::visitLoopBody(Statement *stmt)
294 // We always mark off a loop body, so on each edge, we can balance the
295 // LIFO stack. Right now, we don't have the ability to budget the LIFO
296 // stack ahead of time. If we turn out to never need the LIFO stack, we
297 // mark it as unnecessary. (The interpreter can't really make use of this,
300 // Note that balancing the LIFO stack isn't even necessary, so this
301 // feature may be removed. All this mechanism does is mitigate the
302 // possibility that a long-running loop will overflow the LIFO region
303 // and therefore start requiring nursery allocations.
304 int pos = __ enterloop();
305 ControlStatus status = visitForControl(stmt);
308 if (loop_->usesLifoStack())
309 __ setLoopUsesLifoStack(pos);
315 SemanticAnalysis::visitForStatement(ForStatement *node)
317 AutoEnterScope scope(&scope_, node->scope());
318 PoolScope poolScope(zone_->pool());
319 RootScope rootScope(zone_);
322 LoopScope loop(scope_, &join, &update, &loop_);
324 if (node->initialization())
325 node->initialization()->accept(this);
328 if (node->condition())
332 ControlStatus status = visitLoopBody(node->body());
336 node->update()->accept(this);
338 if (node->condition()) {
340 visitForTest(node->condition(), &header, &join, &join);
347 // If there was a condition, we treat this like a while loop. Otherwise,
348 // the join point is only reachable if the loop contains a break. The
349 // termination status doesn't tell us anything yet.
350 if (node->condition() || loop.breaks())
351 control_->merge(status, ControlStatus(false, Returns_Never));
353 control_->terminate(status.returns());
355 assert(__ stackDepth() == 0);
359 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
361 PoolScope poolScope(zone_->pool());
362 RootScope rootScope(zone_);
368 ControlStatus status;
370 LoopScope loop(scope_, &join, &header, &loop_);
371 if (node->token() == TOK_WHILE) {
373 visitForTest(node->condition(), &body, &join, &body);
374 status = visitLoopBody(node->body());
377 status = visitLoopBody(node->body());
378 visitForTest(node->condition(), &header, &join, &join);
383 // Detect loops that will always have a fork in the contro-flow graph.
384 // This will be a |while| loop, or a |do-while| loop whose body does
385 // not terminate. For now, we treat these as an |if| regardless of the
386 // direction the branch can take. That means the control-flow is always
388 if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
389 control_->merge(status, ControlStatus(false, Returns_Never));
391 // At this point, we've got a do-while loop with a |return| or
392 // |continue|, meaning that the rest of the block is unreachable.
393 control_->terminate(status.returns());
396 assert(__ stackDepth() == 0);
399 static inline Heap::Tenure
400 InferTenure(Symbol *sym)
402 if (sym->scope()->kind() == Scope::GLOBAL)
403 return Heap::Tenure_Old;
405 // SP2's array semantics allow any array kind to escape, so we must use
406 // the normal heap. (Hopefully escape analysis can ease this pain later).
407 if (sym->type()->isArray())
408 return Heap::Tenure_Default;
410 return Heap::Tenure_Default;
414 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
416 PoolScope poolScope(zone_->pool());
417 RootScope rootScope(zone_);
419 Local<Type> type(zone_, node->sym()->type());
421 if (node->sym()->type()->isVoid()) {
422 cc_.reportError(node->type()->pos(), Message_CannotDeclareVoid);
426 if (node->initialization()) {
429 if ((hir = eval(node->initialization())) == NULL)
431 if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
436 if (type->isInt32() || type->isEnum() ||
437 type->isChar() || type->isBool())
440 } else if (type->isFloat()) {
442 } else if (type->isArray()) {
443 Local<ArrayType> atype(zone_, ArrayType::cast(type));
444 Local<ArrayMap> map(zone_, atype->newMap());
448 if (atype->isFixedLength()) {
449 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
450 } else if (node->dims()->at(0)) {
451 // This may not be true if we allow typedefing, so :TODO:
452 // figure out proper semantics.
453 assert(node->dims()->length() == atype->levels());
455 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
456 for (size_t i = 0; i < node->dims()->length(); i++) {
457 Expression *expr = node->dims()->at(i);
459 HIR *hir = eval(expr);
460 if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
467 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
469 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
476 if (node->sym()->scope()->kind() != Scope::GLOBAL) {
477 if (!__ allocate(node->sym()))
486 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
488 control_->returns(Returns_Always);
490 if (!node->expression()) {
491 if (!fun_->returnType()->isVoid()) {
492 cc_.reportError(node->pos(), Message_MissingReturnValue);
500 if (fun_->returnType()->isVoid()) {
501 cc_.reportError(node->pos(), Message_UsedVoidReturn);
505 PoolScope poolScope(zone_->pool());
506 RootScope rootScope(zone_);
508 HIR *hir = eval(node->expression());
512 Local<Type> returnType(zone_, fun_->returnType());
513 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
518 if (hir->type()->isVoid())
525 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
527 HIR *left = eval(node->left());
528 HIR *right = eval(node->right());
532 hir_ = binary(node, node->token(), left, right);
536 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
538 if (type->parameters()->length() == actual)
541 if (actual > type->parameters()->length()) {
542 if (!type->isNative() || !type->isNativeVariadic())
547 if (!type->defaults())
550 // Missing arguments. See if there's a default argument for each missing
552 for (unsigned i = actual; i < type->parameters()->length(); i++) {
553 if (!type->defaults()->at(i))
561 BindImplicitName(Module *from, ImplicitSymbol *sym)
564 return sym->fieldIndex();
566 Module *module = Module::cast(from->getImportAt(sym->index()));
567 StructMap *map = module->globals()->map();
570 Descriptor *desc = map->type()->lookupField(sym->name(), &fieldIndex);
571 assert(desc && desc->type() == sym->type());
573 sym->bind(fieldIndex);
578 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
580 Symbol *sym = proxy->sym();
582 switch (sym->kind()) {
583 case Symbol::kImport:
585 ImportSymbol *import = sym->toImport();
586 hir_ = new (pool_) HImport(proxy, sym->type(), import->index());
590 case Symbol::kImplicit:
592 ImplicitSymbol *import = sym->toImplicit();
593 unsigned fieldIndex = BindImplicitName(unit_->module(), import);
595 hir_ = new (pool_) HImport(proxy, zone_->types()->getImportable(), import->index());
596 hir_ = new (pool_) HField(proxy, hir_, sym->type(), fieldIndex);
600 case Symbol::kConstant:
602 ConstantSymbol *val = sym->toConstant();
603 hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
607 // This is kind of screwy. Symbol::kFunction is like a constant we can't
608 // evaluate yet. Maybe we should extract the GLOBAL case and say that
609 // kFunction is only used for global functions (and use const vars for
611 case Symbol::kFunction:
612 case Symbol::kVariable:
614 Scope *in = sym->scope();
615 switch (in->kind()) {
617 hir_ = new (pool_) HGlobal(proxy, sym);
620 case Scope::FUNCTION:
622 VariableSymbol *var = sym->toVariable();
623 assert(var->storage() == VariableSymbol::Arg);
624 hir_ = new (pool_) HLocal(proxy, var);
630 VariableSymbol *var = sym->toVariable();
631 assert(in->kind() == Scope::BLOCK);
632 assert(var->storage() == VariableSymbol::Local);
633 hir_ = new (pool_) HLocal(proxy, var);
647 SemanticAnalysis::visitBooleanLiteral(BooleanLiteral *node)
649 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
650 hir_ = new (pool_) HBoolean(node, type, node->token() == TOK_TRUE);
654 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
656 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
657 hir_ = new (pool_) HInteger(lit, type, lit->value());
661 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
663 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
664 hir_ = new (pool_) HFloat(node, type, (float)node->value());
668 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
670 Type *type = zone_->types()->getString();
671 hir_ = new (pool_) HString(node, type, node->string());
675 SemanticAnalysis::visitCallExpression(CallExpression *node)
677 HIR *callee = eval(node->callee());
681 if (!callee->type()->isFunction()) {
682 cc_.reportError(node->pos(), Message_CalleeNotFunction);
686 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
688 if (!checkArgumentCount(fun, node->arguments()->length())) {
689 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
693 if (fun->isForward()) {
694 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
698 HIRList *args = new (pool_) HIRList;
699 for (unsigned i = 0; i < node->arguments()->length(); i++) {
700 Expression *expression = node->arguments()->at(i);
701 HIR *arg = eval(expression);
705 Handle<Type> given = arg->type();
707 bool mustComputeReference;
708 if (i >= fun->parameters()->length()) {
709 // Special handling for natives. Arguments past the formal must
710 // always have references computed. However, arrays are already
711 // references for natives.
712 assert(fun->isNative() && fun->isNativeVariadic());
713 mustComputeReference = !given->isReference() &&
716 Local<Type> actual(zone_, fun->parameterAt(i));
718 if (expression->isIndexExpression() && arg->isIndex()) {
719 // If the expression is the form x[y], and this produced a
720 // normal array indexing operation, then we apply some
723 if (actual->isReference()) {
724 // Disabled, since this doesn't have easily definable or
725 // sensible semantics with SP2 arrays, but we don't want
726 // to silently break SP1 semantics.
727 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
731 // As a special rule to account for SP1 semantics, we allow x[y]
732 // to automatically compute a sliced, read-only array view if
733 // the desired type is an array of one more dimension than x[y]
736 // As an additional restriction, this is only allowed for
737 // one-level char arrays, to minimize potential issues until
738 // we determine whether more compatibility is needed.
740 // Internally, for sanity, the dependent array operation does
741 // not necessarily create a dependent array. For extensible
742 // arrays, we instead create a duplicate arrary of just the
743 // sliced portion, rather than deal with the complexity of the
744 // source array being resized.
746 // Note that we don't really know whether a dependent array
747 // will be dependent at compile-time, so the dependent type's
748 // just inherits from the source.
749 if (actual->isArray()) {
750 HIndex *index = arg->toIndex();
751 Local<ArrayType> basetype(zone_, ArrayType::cast(index->base()->type()));
752 Local<ArrayType> atype(zone_, ArrayType::cast(actual));
754 if (atype->isCharArray() && basetype->isCharArray()) {
755 // There is no possible way this will type check, so
756 // it's safe to just try something completely
758 Local<Type> slicetype(zone_);
759 if (basetype->isFixedLength()) {
760 // If the base type is fixed length, we need to
761 // compute a new dynamic array type based on the
762 // fixed array's contents and qualifiers.
763 Local<Type> contained(zone_, basetype->contained());
764 slicetype = zone_->types()->newArray(contained, ArrayType::DYNAMIC_ARRAY_SIZE);
767 slicetype = zone_->types()->qualify(slicetype, basetype->quals());
771 slicetype = basetype;
773 arg = new (pool_) HNewDependentArray(expression, slicetype, index->base(), index->index());
779 if (actual->isReference()) {
780 // If the actual is a reference, the coercion rules are much
781 // stricter; the contained types must be identical.
782 // :TODO: make this not an assert
783 assert(ReferenceType::cast(actual)->contained() == arg->type());
785 // When we start overloading, coercion will have to happen later.
786 arg = coerce(arg, actual, Coerce_Arg);
791 mustComputeReference = actual->isReference() && !given->isReference();
794 if (mustComputeReference) {
795 // Refs always use the LIFO stack if they can.
796 arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
800 if (!args->append(arg))
804 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
808 SemanticAnalysis::visitAssignment(Assignment *node)
810 HLValue *lval = lvalue(node->lvalue());
814 if (lval->type()->quals() & TypeQual_Const) {
815 cc_.reportError(node->pos(), Message_CannotModifyConst);
819 HIR *hir = eval(node->expression());
822 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
825 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
829 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
832 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
837 __ j(OP_BREAK, loop_->break_());
841 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
844 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
848 __ j(OP_CONTINUE, loop_->continue_());
852 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
854 HIR *left = eval(node->left());
858 HIR *right = eval(node->right());
862 // Hrm... yes, for now, let's coerce here.
863 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
864 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
867 // Do not coerce here, there's no reason to yet.
868 if (!left->type()->isArray()) {
869 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
873 hir_ = new (pool_) HIndex(node,
874 ArrayType::cast(left->type())->contained(),
880 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
882 HLValue *lval = lvalue(node->expression());
886 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
892 if (lval->type()->isInt32())
893 rval = new (pool_) HInteger(node, lval->type(), 1);
895 rval = new (pool_) HFloat(node, lval->type(), 1.0);
898 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
900 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
904 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
906 Local<Type> l(zone_, left->type());
907 Local<Type> r(zone_, right->type());
910 l = l->unqualified();
912 r = r->unqualified();
914 if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
915 (token >= TOK_EQUALS && token <= TOK_GE))
917 // We allow: [float|int32] + [float|int32]
918 if (l->isFloat() && r->isInt32())
920 if (l->isInt32() && r->isFloat())
922 if (l->isInt32() && r->isInt32())
925 if (l->isChar() && r->isInt32())
927 if (l->isInt32() && r->isChar())
938 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
940 Handle<ArrayType> argActual,
943 Local<Type> argGiven(zone_, from->type());
945 // Special case: if we receive a string literal, and this is a char array,
946 // we allow a coercion.
947 if (from->isString() &&
948 argGiven->isString() &&
949 argActual->isArray() &&
950 ArrayType::cast(argActual)->isCharArray())
952 HString *hir = from->toString();
953 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
955 if (actual->isFixedLength()) {
956 if (hir->string()->length() + 1 > actual->fixedLength()) {
957 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
962 // Transform the string literal into an array literal. We give it the
963 // type of the left-hand side. The constness of the destination type
964 // will determine whether HArray duplicates it or not.
965 Local<ArrayMap> map(zone_, actual->newMap());
969 Local<Array> array(zone_);
970 array = Array::NewString(zone_,
972 hir->string()->chars(),
973 hir->string()->length(),
978 // Since we're creating a canonical copy of the char array, we have to
979 // be careful that it doesn't get mutated. There are two cases where
980 // we know it can't be mutated, and therefore don't need to specify
981 // that it be cloned after pushing it onto the stack.
983 // (1) The array type is const.
984 // (2) The array type is fixed-length, and the coercion is for
985 // assignment, meaning it will be immediately copied.
987 // We treat declaration separately from assignment, since for
988 // declaration we can just immediately use the cloned version.
989 bool shouldDuplicate = true;
990 if ((actual->quals() & TypeQual_Const) ||
991 (actual->isFixedLength() && kind == Coerce_Assign))
993 shouldDuplicate = false;
996 return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
999 if (!argGiven->isArray()) {
1000 cc_.reportError(pos, Message_ExpectedArray);
1004 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
1005 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
1007 if (actual->levels() != given->levels()) {
1008 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
1014 if (actual->isFixedLength()) {
1015 if (!given->isFixedLength()) {
1016 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1020 if (actual->isCharArray()) {
1021 // String assignment can have a truncated |given|.
1022 if (given->fixedLength() > actual->fixedLength()) {
1023 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
1027 if (given->fixedLength() != actual->fixedLength()) {
1028 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1032 } else if (given->isFixedLength()) {
1033 // We do not allow assignments in the form:
1036 // Otherwise, the following code could break the size guarantees
1037 // of the right-hand side:
1047 // Now |x[0]| contains a 3-length array.
1049 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
1054 if (!given->contained()->isArray() || !actual->contained()->isArray())
1057 given = ArrayType::cast(given->contained());
1058 actual = ArrayType::cast(actual->contained());
1061 bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
1062 bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
1064 // These arrays must contain the same innermost type.
1065 if (given->contained()->unqualified() != actual->contained()->unqualified() ||
1066 (givenConst && !actualConst))
1070 cc_.reportError(pos, Message_TypeMismatch,
1071 GetTypeName(argActual, aname, sizeof(aname)),
1072 GetTypeName(argGiven, gname, sizeof(gname)));
1080 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
1084 cc_.reportError(pos, Message_InvalidCoercion,
1085 GetTypeName(from, fname, sizeof(fname)),
1086 GetTypeName(to, tname, sizeof(tname)));
1091 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
1093 Local<Type> from(zone_, hir->type());
1095 // If the source is *ever* an importable, we just fail.
1096 if (from->isImportable())
1097 return typeFailure(hir->node()->pos(), from, to);
1099 if (from->isInt32() && to->isFloat())
1100 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
1101 if (from->isInt32() && to->isBool())
1102 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
1104 if (to->isEnum() && from->unqualified() != to->unqualified())
1105 return typeFailure(hir->node()->pos(), from, to);
1107 if (to->isArray()) {
1108 Local<ArrayType> atype(zone_, ArrayType::cast(to));
1109 return typeCheckArray(hir->node()->pos(), hir, atype, kind);
1116 SemanticAnalysis::set(VariableSymbol *sym)
1118 if (sym->scope()->kind() == Scope::GLOBAL) {
1121 assert(sym->storage() == VariableSymbol::Local);
1127 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
1129 Local<Type> coercion(zone_, coercionType(token, left, right));
1132 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
1134 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
1149 return new (pool_) HBinary(node, left->type(), token, left, right);
1160 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1161 return new (pool_) HBinary(node, result, token, left, right);
1171 IsValidUncheckedType(Type *type)
1173 return type->isEnum() ||
1177 type->isUnchecked() ||
1182 SemanticAnalysis::visitUnaryExpression(UnaryExpression *node)
1184 HIR *hir = eval(node->expression());
1188 switch (node->token()) {
1191 if (!hir->type()->isInt32() && !hir->type()->isEnum()) {
1193 cc_.reportError(node->pos(), Message_InvalidUnaryType,
1195 GetTypeName(hir->type(), name, sizeof(name)));
1197 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
1198 hir_ = new (pool_) HUnary(node, hir->type(), TOK_TILDE, hir);
1204 if (hir->type()->isInt32() || hir->type()->isEnum()) {
1205 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
1206 hir_ = new (pool_) HUnary(node, type, TOK_MINUS, hir);
1209 if (hir->type()->isFloat()) {
1210 hir_ = new (pool_) HUnary(node, hir->type(), TOK_MINUS, hir);
1215 cc_.reportError(node->pos(), Message_InvalidUnaryType,
1217 GetTypeName(hir->type(), name, sizeof(name)));
1223 assert(node->token() == TOK_LABEL);
1225 TypeSymbol *sym = node->tag()->sym()->asType();
1227 cc_.reportError(node->pos(), Message_IdentifierIsNotAType,
1228 sym->name()->chars());
1232 if (!IsValidUncheckedType(sym->effective())) {
1234 cc_.reportError(node->pos(), Message_InvalidUncheckedCastTo,
1235 GetTypeName(sym->type(), name, sizeof(name)));
1238 if (!IsValidUncheckedType(hir->type())) {
1240 cc_.reportError(node->pos(), Message_InvalidUncheckedCastFrom,
1241 GetTypeName(hir->type(), name, sizeof(name)));
1245 hir_ = new (pool_) HUnary(node, sym->effective(), TOK_LABEL, hir);
1252 SemanticAnalysis::import(HIR *hir, FieldExpression *node)
1254 // Note that we don't care if the hir type is "importable", since we
1255 // can only do anything if the important has a constant binding.
1256 unsigned index = hir->toImport()->index();
1257 Local<Importable> importable(zone_, unit_->module()->getImportAt(index));
1259 if (importable->isPackage()) {
1260 // Look at what's already loaded and see if anything exists. We
1261 // can't create stuff on-demand here since it's too late to add
1262 // new translation units to the CompileContext.
1263 Local<Package> package(zone_, Package::cast(importable));
1264 Local<Importable> found(zone_, package->import(node->field()));
1266 cc_.reportError(node->pos(), Message_PackageDoesNotHaveMember, node->field()->chars());
1270 // If we did find something, make sure it is in our import list.
1271 // If we didn't explicitly import it, we have no right to use it.
1272 for (index = 0; index < unit_->module()->imports(); index++) {
1273 if (unit_->module()->getImportAt(index) == importable)
1277 if (index == unit_->module()->imports()) {
1278 cc_.reportError(node->pos(), Message_ImportWasNeverImported, node->field()->chars());
1282 // Just create a new HImport.
1283 hir_ = new (pool_) HImport(node, hir->type(), index);
1285 // Modules can never have sub-modules or sub-packages.
1287 Local<Module> module(zone_, Module::cast(importable));
1288 Local<StructMap> map(zone_, module->globals()->map());
1289 Local<Descriptor> desc(zone_, map->type()->lookupField(node->field(), &index));
1291 cc_.reportError(node->pos(), Message_FieldNotFound, node->field()->chars());
1294 hir_ = new (pool_) HField(node, hir, desc->type(), index);
1299 SemanticAnalysis::visitFieldExpression(FieldExpression *node)
1301 HIR *hir = eval(node->left());
1305 if (hir->isImport()) {
1311 cc_.reportError(node->pos(), Message_InvalidFieldExpression,
1312 GetTypeName(hir->type(), name, sizeof(name)));
1315 static inline TokenKind
1316 ToCompare(Expression *expr)
1318 if (expr->isBinaryExpression()) {
1319 BinaryExpression *b = expr->toBinaryExpression();
1320 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
1322 } else if (expr->isUnaryExpression()) {
1323 UnaryExpression *u = expr->toUnaryExpression();
1324 if (u->token() == TOK_NOT)
1331 SemanticAnalysis::visitForTest(Expression *expr,
1336 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1338 TokenKind token = ToCompare(expr);
1339 if (token == TOK_EOF || token == TOK_NOT) {
1341 if (token == TOK_EOF)
1344 hir = eval(expr->toUnaryExpression()->expression());
1347 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1352 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
1353 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
1355 if (fallthrough == falseBranch)
1356 __ j(op, trueBranch);
1358 __ j(op, falseBranch);
1362 BinaryExpression *bin = expr->toBinaryExpression();
1363 if (token == TOK_AND || token == TOK_OR) {
1365 if (token == TOK_AND)
1366 visitForTest(bin->left(), &next, falseBranch, &next);
1368 visitForTest(bin->left(), trueBranch, &next, &next);
1370 visitForTest(bin->right(), trueBranch, falseBranch, fallthrough);
1374 HIR *left = eval(bin->left());
1375 HIR *right = eval(bin->right());
1376 if (!left || !right)
1379 HIR *hir = binary(bin, bin->token(), left, right);
1382 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1386 if (fallthrough == trueBranch)
1387 __ j(OP_JF, falseBranch);
1389 __ j(OP_JT, trueBranch);
1393 SemanticAnalysis::lvalue(Expression *expr)
1395 HIR *hir = eval(expr);
1399 if (!hir->isLValue()) {
1400 cc_.reportError(expr->pos(), Message_ExpectedLValue);
1404 return static_cast<HLValue *>(hir);
1408 SemanticAnalysis::eval(Expression *expr)
1420 SemanticAnalysis::discharge(HIR *hir)
1422 EmitHIR(zone_, emitter_, hir);