package abstractSyntaxTree.Statement; import TypeCheck.TypeCheckResult; import TypeCheck.AbstractType; import abstractSyntaxTree.Expression.IExpression; import org.objectweb.asm.*; public class WhileStatement extends AbstractType implements IStatement { IExpression condition; IStatement statement; public WhileStatement(IExpression condition, IStatement statement) { this.condition = condition; this.statement = statement; } @Override public TypeCheckResult typeCheck() throws Exception { TypeCheckResult result = new TypeCheckResult(); TypeCheckResult conditionType = condition.typeCheck(); if (!conditionType.equals("bool")) { throw new IllegalArgumentException("Expected boolean"); } TypeCheckResult statementType = statement.typeCheck(); result.type = statementType.type; return result; } @Override public void codeGen(MethodVisitor mv) throws Exception { Label conditionFalse = new Label(); Label LoopStart = new Label(); mv.visitLabel(LoopStart); condition.codeGen(mv); mv.visitJumpInsn(Opcodes.IFEQ, conditionFalse); // Checks if the condition is false (0) statement.codeGen(mv); //TODO: If the block ends with a return statement, we might have to pop it from the stack // So the next iteration starts with a clean stack mv.visitJumpInsn(Opcodes.GOTO, LoopStart); // Jump to the start of the while loop mv.visitLabel(conditionFalse); } }