Support admin.inc again.
1 /* vim: set ts=4 sw=4 tw=99 et:
3 * Copyright (C) 2012 David Anderson
5 * This file is part of SourcePawn.
7 * SourcePawn is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License as published by the Free
9 * Software Foundation, either version 3 of the License, or (at your option)
12 * SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY
13 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with
17 * SourcePawn. If not, see http://www.gnu.org/licenses/.
21 #include "../Strings.h"
22 #include "../NativeTable.h"
23 #include "../TypeManager.h"
24 #include "../Modules.h"
26 #include "SemanticAnalysis.h"
27 #include "../Heap-inl.h"
33 typedef BytecodeEmitter::Label Label;
38 AutoEnterScope(Scope **prevp, Scope *scope)
47 assert(prev_ == scope->enclosing());
60 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, TranslationUnit *unit)
72 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
73 : zone_(parent->zone_),
78 scope_(parent->scope_),
80 module_(parent->module_),
89 SemanticAnalysis::analyze()
91 scope_ = unit_->globalScope();
93 module_ = Module::New(zone_);
95 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
96 Statement *stmt = unit_->tree()->statements()->at(i);
100 Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
103 module_->setGlobals(globals);
105 Local<Code> code(zone_, __ finish());
108 code->setModule(module_);
109 module_->setCode(code);
112 // Disassemble(code, stdout);
115 unit_->module_ = module_;
119 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
121 FunctionSymbol *sym = stmt->sym();
122 Local<FunctionType> type(zone_, sym->type());
124 assert(scope_->kind() == Scope::GLOBAL);
126 if (stmt->token() == TOK_NATIVE) {
127 // Define the native now.
129 if (!zone_->nativeTable()->add(stmt->name(), &index))
132 Local<Native> native(zone_, Native::New(zone_, type, index));
141 // If the function is a forward or native, we don't have to do anything.
142 if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
145 SemanticAnalysis child(this, type);
146 Local<Function> funobj(zone_, child.compile(stmt));
152 if (stmt->token() == TOK_PUBLIC)
159 SemanticAnalysis::compile(FunctionStatement *stmt)
161 __ setFirstLine(stmt->pos().line);
163 AutoEnterScope argScope(&scope_, stmt->argScope());
165 for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
166 Parameter *param = stmt->signature().parameters()->at(i);
167 param->sym()->allocate(VariableSymbol::Arg, i);
170 AutoEnterScope varScope(&scope_, stmt->varScope());
171 ControlStatus status = visitForControl(stmt->body());
173 if (!fun_->returnType()->isVoid()) {
174 // If the function is not void, report if not all paths return a value.
175 // All other incorrect return cases have been caught already.
176 if (status.returns() == Returns_Sometimes) {
177 cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
181 if (status.returns() == Returns_Never) {
182 cc_.reportError(stmt->pos(), Message_MissingReturnValue);
187 Local<Code> code(zone_, __ finish());
190 code->setModule(module_);
192 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
197 // Disassemble(code, stdout);
204 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
206 AutoEnterScope scope(&scope_, node->scope());
208 for (size_t i = 0; i < node->statements()->length(); i++) {
209 Statement *stmt = node->statements()->at(i);
210 __ note_position(stmt->pos());
212 assert(__ stackDepth() == 0);
217 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
222 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
224 // While building HIR, we enter new pool and root scopes, since HIR
225 // creation is purely temporary.
226 PoolScope poolScope(zone_->pool());
227 RootScope rootScope(zone_);
229 HIR *hir = eval(node->expression());
234 if (!hir->type()->isVoid())
239 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
241 // If both sides terminate in a return, we consider this a return as well.
242 if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
243 terminate(Returns_Always);
247 ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
251 if (left.terminates() && right.terminates())
257 SemanticAnalysis::ControlStatus
258 SemanticAnalysis::visitForControl(Statement *statement)
260 ControlScope scope(&control_);
261 statement->accept(this);
262 return scope.status();
266 SemanticAnalysis::visitIfStatement(IfStatement *node)
270 ControlStatus trueBranch;
271 ControlStatus falseBranch(false, Returns_Never);
273 if (!node->ifFalse()) {
276 visitForTest(node->condition(), &success, &join, &success);
278 trueBranch = visitForControl(node->ifTrue());
282 visitForTest(node->condition(), &success, &next, &success);
284 trueBranch = visitForControl(node->ifTrue());
287 falseBranch = visitForControl(node->ifFalse());
292 control_->merge(trueBranch, falseBranch);
296 SemanticAnalysis::requireLifoStack()
301 loop_->setUsesLifoStack();
304 SemanticAnalysis::ControlStatus
305 SemanticAnalysis::visitLoopBody(Statement *stmt)
307 // We always mark off a loop body, so on each edge, we can balance the
308 // LIFO stack. Right now, we don't have the ability to budget the LIFO
309 // stack ahead of time. If we turn out to never need the LIFO stack, we
310 // mark it as unnecessary. (The interpreter can't really make use of this,
313 // Note that balancing the LIFO stack isn't even necessary, so this
314 // feature may be removed. All this mechanism does is mitigate the
315 // possibility that a long-running loop will overflow the LIFO region
316 // and therefore start requiring nursery allocations.
317 int pos = __ enterloop();
318 ControlStatus status = visitForControl(stmt);
321 if (loop_->usesLifoStack())
322 __ setLoopUsesLifoStack(pos);
328 SemanticAnalysis::visitForStatement(ForStatement *node)
330 AutoEnterScope scope(&scope_, node->scope());
331 PoolScope poolScope(zone_->pool());
332 RootScope rootScope(zone_);
335 LoopScope loop(scope_, &join, &update, &loop_);
337 if (node->initialization())
338 node->initialization()->accept(this);
341 if (node->condition())
345 ControlStatus status = visitLoopBody(node->body());
349 node->update()->accept(this);
351 if (node->condition()) {
353 visitForTest(node->condition(), &header, &join, &join);
360 // If there was a condition, we treat this like a while loop. Otherwise,
361 // the join point is only reachable if the loop contains a break. The
362 // termination status doesn't tell us anything yet.
363 if (node->condition() || loop.breaks())
364 control_->merge(status, ControlStatus(false, Returns_Never));
366 control_->terminate(status.returns());
368 assert(__ stackDepth() == 0);
372 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
374 PoolScope poolScope(zone_->pool());
375 RootScope rootScope(zone_);
381 ControlStatus status;
383 LoopScope loop(scope_, &join, &header, &loop_);
384 if (node->token() == TOK_WHILE) {
386 visitForTest(node->condition(), &body, &join, &body);
387 status = visitLoopBody(node->body());
390 status = visitLoopBody(node->body());
391 visitForTest(node->condition(), &header, &join, &join);
396 // Detect loops that will always have a fork in the contro-flow graph.
397 // This will be a |while| loop, or a |do-while| loop whose body does
398 // not terminate. For now, we treat these as an |if| regardless of the
399 // direction the branch can take. That means the control-flow is always
401 if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
402 control_->merge(status, ControlStatus(false, Returns_Never));
404 // At this point, we've got a do-while loop with a |return| or
405 // |continue|, meaning that the rest of the block is unreachable.
406 control_->terminate(status.returns());
409 assert(__ stackDepth() == 0);
412 static inline Heap::Tenure
413 InferTenure(Symbol *sym)
415 if (sym->scope()->kind() == Scope::GLOBAL)
416 return Heap::Tenure_Old;
418 // SP2's array semantics allow any array kind to escape, so we must use
419 // the normal heap. (Hopefully escape analysis can ease this pain later).
420 if (sym->type()->isArray())
421 return Heap::Tenure_Default;
423 return Heap::Tenure_Default;
427 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
429 PoolScope poolScope(zone_->pool());
430 RootScope rootScope(zone_);
432 Local<Type> type(zone_, node->sym()->type());
434 if (node->sym()->type()->isVoid()) {
435 cc_.reportError(node->type()->pos(), Message_CannotDeclareVoid);
439 if (node->initialization()) {
442 if ((hir = eval(node->initialization())) == NULL)
444 if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
449 if (type->isInt32() || type->isEnum() ||
450 type->isChar() || type->isBool())
453 } else if (type->isFloat()) {
455 } else if (type->isArray()) {
456 Local<ArrayType> atype(zone_, ArrayType::cast(type));
457 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, atype));
461 if (atype->isFixedLength()) {
462 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
463 } else if (node->dims()->at(0)) {
464 // This may not be true if we allow typedefing, so :TODO:
465 // figure out proper semantics.
466 assert(node->dims()->length() == atype->levels());
468 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
469 for (size_t i = 0; i < node->dims()->length(); i++) {
470 Expression *expr = node->dims()->at(i);
472 HIR *hir = eval(expr);
473 if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
480 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
482 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
489 if (node->sym()->scope()->kind() != Scope::GLOBAL) {
490 if (!__ allocate(node->sym()))
499 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
501 control_->returns(Returns_Always);
503 if (!node->expression()) {
504 if (!fun_->returnType()->isVoid()) {
505 cc_.reportError(node->pos(), Message_MissingReturnValue);
513 if (fun_->returnType()->isVoid()) {
514 cc_.reportError(node->pos(), Message_UsedVoidReturn);
518 PoolScope poolScope(zone_->pool());
519 RootScope rootScope(zone_);
521 HIR *hir = eval(node->expression());
525 Local<Type> returnType(zone_, fun_->returnType());
526 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
531 if (hir->type()->isVoid())
538 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
540 HIR *left = eval(node->left());
541 HIR *right = eval(node->right());
545 hir_ = binary(node, node->token(), left, right);
549 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
551 if (type->parameters()->length() == actual)
554 if (actual > type->parameters()->length()) {
555 if (!type->isNative() || !type->isNativeVariadic())
560 if (!type->defaults())
563 // Missing arguments. See if there's a default argument for each missing
565 for (unsigned i = actual; i < type->parameters()->length(); i++) {
566 if (!type->defaults()->at(i))
574 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
576 Symbol *sym = proxy->sym();
578 switch (sym->kind()) {
579 case Symbol::kConstant:
581 ConstantSymbol *val = sym->toConstant();
582 hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
586 // This is kind of screwy. Symbol::kFunction is like a constant we can't
587 // evaluate yet. Maybe we should extract the GLOBAL case and say that
588 // kFunction is only used for global functions (and use const vars for
590 case Symbol::kFunction:
591 case Symbol::kVariable:
593 Scope *in = sym->scope();
594 switch (in->kind()) {
596 hir_ = new (pool_) HGlobal(proxy, sym);
599 case Scope::FUNCTION:
601 VariableSymbol *var = sym->toVariable();
602 assert(var->storage() == VariableSymbol::Arg);
603 hir_ = new (pool_) HLocal(proxy, var);
609 VariableSymbol *var = sym->toVariable();
610 assert(in->kind() == Scope::BLOCK);
611 assert(var->storage() == VariableSymbol::Local);
612 hir_ = new (pool_) HLocal(proxy, var);
626 SemanticAnalysis::visitBooleanLiteral(BooleanLiteral *node)
628 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
629 hir_ = new (pool_) HBoolean(node, type, node->token() == TOK_TRUE);
633 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
635 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
636 hir_ = new (pool_) HInteger(lit, type, lit->value());
640 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
642 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
643 hir_ = new (pool_) HFloat(node, type, (float)node->value());
647 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
649 Type *type = zone_->types()->getString();
650 hir_ = new (pool_) HString(node, type, node->string());
654 SemanticAnalysis::visitCallExpression(CallExpression *node)
656 HIR *callee = eval(node->callee());
660 if (!callee->type()->isFunction()) {
661 cc_.reportError(node->pos(), Message_CalleeNotFunction);
665 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
667 if (!checkArgumentCount(fun, node->arguments()->length())) {
668 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
672 if (fun->isForward()) {
673 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
677 HIRList *args = new (pool_) HIRList;
678 for (unsigned i = 0; i < node->arguments()->length(); i++) {
679 Expression *expression = node->arguments()->at(i);
680 HIR *arg = eval(expression);
684 Handle<Type> given = arg->type();
686 bool mustComputeReference;
687 if (i >= fun->parameters()->length()) {
688 // Special handling for natives. Arguments past the formal must
689 // always have references computed. However, arrays are already
690 // references for natives.
691 assert(fun->isNative() && fun->isNativeVariadic());
692 mustComputeReference = !given->isReference() &&
695 Local<Type> actual(zone_, fun->parameterAt(i));
697 if (expression->isIndexExpression()) {
698 // Temporarily disabled.
699 assert(!actual->isArray());
700 if (actual->isReference()) {
701 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
706 if (actual->isReference()) {
707 // If the actual is a reference, the coercion rules are much
708 // stricter; the contained types must be identical.
709 // :TODO: make this not an assert
710 assert(ReferenceType::cast(actual)->contained() == arg->type());
712 // When we start overloading, coercion will have to happen later.
713 arg = coerce(arg, actual, Coerce_Arg);
718 mustComputeReference = actual->isReference() && !given->isReference();
721 if (mustComputeReference) {
722 // Refs always use the LIFO stack if they can.
723 arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
727 if (!args->append(arg))
731 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
735 SemanticAnalysis::visitAssignment(Assignment *node)
737 HLValue *lval = lvalue(node->lvalue());
741 if (lval->type()->quals() & TypeQual_Const) {
742 cc_.reportError(node->pos(), Message_CannotModifyConst);
746 HIR *hir = eval(node->expression());
747 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
750 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
754 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
757 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
762 __ j(OP_BREAK, loop_->break_());
766 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
769 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
773 __ j(OP_CONTINUE, loop_->continue_());
777 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
779 HIR *left = eval(node->left());
783 HIR *right = eval(node->right());
787 // Hrm... yes, for now, let's coerce here.
788 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
789 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
792 // Do not coerce here, there's no reason to yet.
793 if (!left->type()->isArray()) {
794 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
798 hir_ = new (pool_) HIndex(node,
799 ArrayType::cast(left->type())->contained(),
805 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
807 HLValue *lval = lvalue(node->expression());
811 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
817 if (lval->type()->isInt32())
818 rval = new (pool_) HInteger(node, lval->type(), 1);
820 rval = new (pool_) HFloat(node, lval->type(), 1.0);
823 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
825 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
829 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
831 Handle<Type> l = left->type();
832 Handle<Type> r = right->type();
834 if (token >= TOK_PLUS && token <= TOK_SLASH) {
835 // We allow: [float|int32] + [float|int32]
836 if (l->isFloat() && r->isInt32())
838 if (l->isInt32() && r->isFloat())
840 if (l->isInt32() && r->isInt32())
851 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
853 Handle<ArrayType> argActual,
856 Local<Type> argGiven(zone_, from->type());
858 // Special case: if we receive a string literal, and this is a char array,
859 // we allow a coercion.
860 if (from->isString() &&
861 argGiven->isString() &&
862 argActual->isArray() &&
863 ArrayType::cast(argActual)->isCharArray())
865 HString *hir = from->toString();
866 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
868 if (actual->isFixedLength()) {
869 if (hir->string()->length() + 1 > actual->fixedLength()) {
870 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
875 // Transform the string literal into an array literal. We give it the
876 // type of the left-hand side. The constness of the destination type
877 // will determine whether HArray duplicates it or not.
878 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, actual));
882 Local<Array> array(zone_);
883 array = Array::NewString(zone_,
885 hir->string()->chars(),
886 hir->string()->length(),
891 // Since we're creating a canonical copy of the char array, we have to
892 // be careful that it doesn't get mutated. There are two cases where
893 // we know it can't be mutated, and therefore don't need to specify
894 // that it be cloned after pushing it onto the stack.
896 // (1) The array type is const.
897 // (2) The array type is fixed-length, and the coercion is for
898 // assignment, meaning it will be immediately copied.
900 // We treat declaration separately from assignment, since for
901 // declaration we can just immediately use the cloned version.
902 bool shouldDuplicate = true;
903 if ((actual->quals() & TypeQual_Const) ||
904 (actual->isFixedLength() && kind == Coerce_Assign))
906 shouldDuplicate = false;
909 return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
912 if (!argGiven->isArray()) {
913 cc_.reportError(pos, Message_ExpectedArray);
917 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
918 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
920 if (actual->levels() != given->levels()) {
921 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
927 if (actual->isFixedLength()) {
928 if (!given->isFixedLength()) {
929 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
933 if (actual->isCharArray()) {
934 // String assignment can have a truncated |given|.
935 if (given->fixedLength() > actual->fixedLength()) {
936 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
940 if (given->fixedLength() != actual->fixedLength()) {
941 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
945 } else if (given->isFixedLength()) {
946 // We do not allow assignments in the form:
949 // Otherwise, the following code could break the size guarantees
950 // of the right-hand side:
960 // Now |x[0]| contains a 3-length array.
962 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
967 if (!given->contained()->isArray() || !actual->contained()->isArray())
970 given = ArrayType::cast(given->contained());
971 actual = ArrayType::cast(actual->contained());
974 bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
975 bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
977 // These arrays must contain the same innermost type.
978 if (given->contained()->unqualified() != actual->contained()->unqualified() ||
979 (givenConst && !actualConst))
983 cc_.reportError(pos, Message_TypeMismatch,
984 GetTypeName(argActual, aname, sizeof(aname)),
985 GetTypeName(argGiven, gname, sizeof(gname)));
993 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
997 cc_.reportError(pos, Message_InvalidCoercion,
998 GetTypeName(from, fname, sizeof(fname)),
999 GetTypeName(to, tname, sizeof(tname)));
1004 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
1006 Local<Type> from(zone_, hir->type());
1008 if (from->isInt32() && to->isFloat())
1009 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
1010 if (from->isInt32() && to->isBool())
1011 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
1013 if (to->isEnum() && *from != to)
1014 return typeFailure(hir->node()->pos(), from, to);
1016 if (to->isArray()) {
1017 Local<ArrayType> atype(zone_, ArrayType::cast(to));
1018 return typeCheckArray(hir->node()->pos(), hir, atype, kind);
1025 SemanticAnalysis::set(VariableSymbol *sym)
1027 if (sym->scope()->kind() == Scope::GLOBAL) {
1030 assert(sym->storage() == VariableSymbol::Local);
1036 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
1038 Local<Type> coercion(zone_, coercionType(token, left, right));
1041 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
1043 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
1058 return new (pool_) HBinary(node, left->type(), token, left, right);
1069 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1070 return new (pool_) HBinary(node, result, token, left, right);
1080 IsValidUncheckedType(Type *type)
1082 return type->isEnum() ||
1086 type->isUnchecked() ||
1091 SemanticAnalysis::visitUnaryExpression(UnaryExpression *node)
1093 switch (node->token()) {
1096 assert(node->token() == TOK_LABEL);
1097 HIR *hir = eval(node->expression());
1101 TypeSymbol *sym = node->tag()->sym()->asType();
1103 cc_.reportError(node->pos(), Message_IdentifierIsNotAType,
1104 sym->name()->chars());
1108 if (!IsValidUncheckedType(sym->type())) {
1110 cc_.reportError(node->pos(), Message_InvalidUncheckedCastTo,
1111 GetTypeName(hir->type(), name, sizeof(name)));
1114 if (!IsValidUncheckedType(hir->type())) {
1116 cc_.reportError(node->pos(), Message_InvalidUncheckedCastFrom,
1117 GetTypeName(hir->type(), name, sizeof(name)));
1126 static inline TokenKind
1127 ToCompare(Expression *expr)
1129 if (expr->isBinaryExpression()) {
1130 BinaryExpression *b = expr->toBinaryExpression();
1131 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
1133 } else if (expr->isUnaryExpression()) {
1134 UnaryExpression *u = expr->toUnaryExpression();
1135 if (u->token() == TOK_NOT)
1142 SemanticAnalysis::visitForTest(Expression *expr,
1147 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
1149 TokenKind token = ToCompare(expr);
1150 if (token == TOK_EOF || token == TOK_NOT) {
1152 if (token == TOK_EOF)
1155 hir = eval(expr->toUnaryExpression()->expression());
1158 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1163 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
1164 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
1166 if (fallthrough == falseBranch)
1167 __ j(op, trueBranch);
1169 __ j(op, falseBranch);
1173 BinaryExpression *bin = expr->toBinaryExpression();
1174 if (token == TOK_AND || token == TOK_OR) {
1176 //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
1180 HIR *left = eval(bin->left());
1181 HIR *right = eval(bin->right());
1182 if (!left || !right)
1185 HIR *hir = binary(bin, bin->token(), left, right);
1188 if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
1192 if (fallthrough == trueBranch)
1193 __ j(OP_JF, falseBranch);
1195 __ j(OP_JT, trueBranch);
1199 SemanticAnalysis::lvalue(Expression *expr)
1201 HIR *hir = eval(expr);
1205 if (!hir->isLValue()) {
1206 cc_.reportError(expr->pos(), Message_ExpectedLValue);
1210 return static_cast<HLValue *>(hir);
1214 SemanticAnalysis::eval(Expression *expr)
1226 SemanticAnalysis::discharge(HIR *hir)
1228 EmitHIR(zone_, emitter_, hir);