59 lines
1.9 KiB
Java
59 lines
1.9 KiB
Java
package abstractSyntaxTree.Statement;
|
|
|
|
import TypeCheck.TypeCheckResult;
|
|
import TypeCheck.AbstractType;
|
|
import abstractSyntaxTree.Expression.IExpression;
|
|
import org.objectweb.asm.*;
|
|
|
|
public class IfElseStatement extends AbstractType implements IStatement{
|
|
IExpression condition;
|
|
IStatement ifStatement;
|
|
IStatement elseStatement;
|
|
|
|
public IfElseStatement(IExpression condition, IStatement ifStatement, IStatement elseStatement) {
|
|
this.condition = condition;
|
|
this.ifStatement = ifStatement;
|
|
this.elseStatement = elseStatement;
|
|
}
|
|
|
|
@Override
|
|
public TypeCheckResult typeCheck() throws Exception {
|
|
TypeCheckResult result = new TypeCheckResult();
|
|
|
|
TypeCheckResult conditionType = condition.typeCheck();
|
|
|
|
if (!conditionType.equals("bool")) {
|
|
throw new IllegalArgumentException("should be boolean");
|
|
}
|
|
|
|
TypeCheckResult ifStatementType = ifStatement.typeCheck();
|
|
TypeCheckResult elseStatementType = elseStatement.typeCheck();
|
|
|
|
if (!ifStatementType.equals(elseStatementType)) {
|
|
throw new IllegalArgumentException("if and else have different types");
|
|
}
|
|
|
|
result.type = elseStatementType.type;
|
|
return result;
|
|
}
|
|
|
|
@Override
|
|
public void codeGen(MethodVisitor mv) throws Exception {
|
|
|
|
Label conditionFalse = new Label();
|
|
Label statementEnd = new Label();
|
|
|
|
condition.CodeGen(mv);
|
|
|
|
mv.visitJumpInsn(Opcodes.IFEQ, conditionFalse); //Checks if the condition is false (0)
|
|
ifStatement.codeGen(mv); //If the condition is true, execute the ifBlock
|
|
mv.visitJumpInsn(Opcodes.GOTO, statementEnd); //Jump to the end of the if-else statement
|
|
|
|
mv.visitLabel(conditionFalse);
|
|
elseStatement.codeGen(mv); //If the condition is false, execute the elseBlock
|
|
|
|
mv.visitLabel(statementEnd); //End of the if-else statement
|
|
|
|
}
|
|
}
|